面向对象的理解(继承)

以下个人观点:

通过对象调用属性方法——

属性直接根据引用找到匹配的属性
方法
(1) 不覆盖方法情况:
遵循就近原则,就是调用继承自距离最近父类的方法。
(2) 覆盖方法情况:
调用实际对象的该覆盖的方法。(哪怕不做改变的覆盖也是不同于不写的。)



下面代码举例:

过程:通过实例对象调用属性

观点:直接根据引用找到匹配的属性。

代码:

public class Parent {
	int a = 3;
}


public class Son extends Parent {
	int a = 5;

	public static void main(String[] args) {
		Son son = new Son();
		System.out.println( son.a ); //结果5
		System.out.println( ((Parent)son).a ); //结果3
	}
}


过程:通过实例对象调用方法

观点:

        (1)不覆盖方法情况:遵循就近原则,就是调用继承自距离最近父类的方法。

(2)覆盖方法情况:调用实际对象的该覆盖的方法。(哪怕不做改变的覆盖也是不同于不写的。)


代码:

(1)不覆盖方法情况:遵循就近原则,就是调用继承自距离最近父类的方法。
public class Parent {
	public void A(){
		System.out.println("Parent---A");
	}
	public void B(){
		System.out.println("Parent---B");
	}
}




public class Son extends Parent {
	public void A(){
		System.out.println("Son---A");
	}
}





public class Grandson extends Son{
	public static void main(String[] args) {
		Grandson grandson = new Grandson();
		grandson.A(); // 结果:Son---A  ,Son覆盖了A() 且距离Crandson更近。
		grandson.B(); // 结果:Parent---B
	}
}


(2)覆盖方法情况:调用实际对象的该覆盖的方法。


public class Parent {
	public void A(){
		System.out.println("Parent---A");
	}
}




public class Son extends Parent {
	public void A(){
		System.out.println("Son---A");
	}
	public static void main(String[] args) {
		Son son = new Son();
		son.A(); // 结果:Son---A
	}
}




注意:通过对象调用方法且该方法里调用属性——       

        得看调用的那个方法与属性的关系。比如子类调用父类的方法,该方法中的属性为父类中的属性。这种情况,切不可于子类中覆盖的属性混为一谈。



个人对与super 和 this的理解是:

super指代强转为父类引用的一个对象,实际对象还是原对象,而且这种转换不会发生多态的(见下面代码);

this指代当前引用的当前对象


代码:

public class Parent {
	public void A(){
		System.out.println("Parent---A");
	}
}



public class Son extends Parent {
	public void A(){
		System.out.println("Son---A");
	}
	
	public void print(){
		this.A();  //结果:Son---A
		super.A(); // Parent---A,未发生多态
		((Parent)this).A();// Son---A,发生多态
		System.out.println(this); //Son@1db9742
		System.out.println(super.toString());//Son@1db9742
	}
	
	public static void main(String[] args) {
		new Son().print();
	}
}


对this和super想有更深了解参考:https://blog.csdn.net/weixin_42095279/article/details/80136733


猜你喜欢

转载自blog.csdn.net/chw0629/article/details/80143910