Correct the misunderstanding of testing the applicability of the fields and methods of the parent and child classes in java inheritance

Posted by phpcharan on Sat, 16 Nov 2019 22:05:28 +0100

java core technology Volume I p148

Although methods such as getName and getHireDay are not explicitly defined in the Manager class (subclass), objects belonging to the Manager class can use them, because the Manager class automatically inherits these methods in the superclass Employee

Also think

Similarly, name, salary and hireday are inherited from the superclass. As a result, each Manager class contains four domains (a bonus domain declared by a subclass itself)

Because of misunderstanding of the meaning, I have some doubts in actual use, that is, the parent class constructor called by the keyword super in the subclass constructor, so whether the instantiated domain belongs to a superclass or a subclass? Because this problem has always been ambiguous and many mistakes have been made.

package inheritanceTest;
public class InheritanceTest {
	public static void main(String[] args) {
		ChildClass kid = new ChildClass("kid"); 
		FatherClass[] superclass = new FatherClass[3];
		superclass[0] = kid;
		superclass[1] = new FatherClass("father");
		superclass[2] = new FatherClass("father");
		
		//superclass[0].setX(10);
		//error
		
		kid.setX(10);
		//ok
		
		System.out.println("kid name is " +kid.getName() + " and superclass[0]=kid, its class is " + superclass[0].getClass());
		//kid can call the father_class method getName()
		// superclass[0] class is ChildClass (by getClass())
		
		for(FatherClass e : superclass)
			System.out.println("name is : " + e.getName() + ";   class is :" + e.getClass());
		
		System.out.println("We call name by child class :"  + kid.getOwnName());
		// ok, and print "child class own name"

			
	}
}
package inheritanceTest;
public class FatherClass 
	{
	private String name; 
		public FatherClass(String name) 
		{
			this.name = name;
		}
	public String getName() 
	{
		return name;
	}
}
package inheritanceTest;
public class ChildClass extends FatherClass {
	private int x;
	public String name = "child class own name" ;
	public ChildClass(String name) {
		super(name);
		x = 0;
	}
		public String getName()
		{
			return super.getName();
		}
		
		public void setX(int x) {
			this.x = x;
		}
		
		public String getOwnName() 
		{
			return name;
		}
}

Summary
Parent [0] = child subclass, no error will be reported; parent [0]. Getclass() = class child subclass;
But the method of the family [0]. Childmesh subclass will report an error.
super calls the parent constructor, which actually completes the instantiation of the parent domain.

Topics: Java