Together to learn Java (xxvii) ----- child inherits the parent class method call problem

Short step, a thousand miles; not small streams, into jianghai.

 

Java language foundation

 

When the subclass inherits the parent class, subclass, and has the same name as the parent class variables and methods of the same name, the object of which is called variable or method?

conclusion as below:

 

class Father{
	
	int i = 10;
	
	void set() {
		System.out.println("父类的方法");
	}
	
	void setted() {
		System.out.println("父类的方法");
	}
}

class Son extends Father{
	
	int i = 40;
	
	void set() {
		System.out.println("子类的方法");
	}
	
	void settedd(){
		System.out.println("子类的方法");
	}
}

public class Test {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Father f = new Father();
		Son s = new Son();
		Father ff = new Son();
		
		System.out.println(f.i);//10
		System.out.println(s.i);//40
		System.out.println (ff.i); 10 // 
		System.out.println (); 
		// Conclusion: subclass, the parent class member variables contain the same numerical references see class variable belongs, i.e. left 
		
		f. set (); // output: parent class; Conclusion: the methods of the same name, parent class object is called the parent class method 
		s.set (); // output: method subclass; Conclusion: the methods of the same name, subclass object the method is called a subclass 
		
		ff.set (); // output: method subclass; Conclusion: for this 'parent class instance = new subclass ()', call the same method is a subclass of method 
		ff.setted ( ); // output: the parent class; Conclusion: You can call the parent class's unique method 
// ff.settedd (); // wrong; Conclusion: Conclusion: the unique subclass method can not call 
		
// f.settedd () // wrong; conclusion: Conclusion: the parent object can call a unique subclass method 
		s.setted (); // output: parent class; Conclusion: subclass object can call the parent class unique method 
		
	} 
}

 

  

 

  

Guess you like

Origin www.cnblogs.com/smilexuezi/p/12638485.html