java中的动态绑定

版权声明:本文内容为博主原创,仅为作者本人日后查阅,欢迎批评指正,转载请注明来源。 https://blog.csdn.net/qq_38709999/article/details/84000330

上代码:

class A {
	int i = 1;

	A(){
		
	}
	A(int x) {
		i=x;
	}
	
	public void show() {
		System.out.println("A::show  "+i);
	}
	
}

class B extends A {
	int i = 5;
	int j = 6;
	
	B(){
		
	}
	B(int x,int y) {
		i=y;
	}
	
	public void show() {
		System.out.println("B::show  "+i);
	}
	
	public void sonfun() {
		System.out.println("子类方法");
	}
}

public class JTest {
	public static void main(String[] args) {
		B b = new B();
		b.show();
		System.out.println(b.i);
		A a = new A();
		a.show();
		System.out.println(a.i);
		A c = new B();
		c.show();
		System.out.println(c.i);
		//c.sonfun();
		//System.out.println(c.j);
		
		A d = new B(1,2);
		//A e = new B(1);
		//B f = new B(1);
	}
}

运行结果:

B::show  5
5
A::show  1
1
B::show  5
1

java中的动态绑定,具体表现在以父类引用指向子类对象,在以上代码中,c指向的是一个A类,调用的属性和方法也都是A类中的属性和方法,由于方法show()在子类中被重写(overwrite),所以在运行时判断当前对象为子类A,所以调用时指向了子类;而方法sonfun()只是子类的方法,所以父类无法访问到。

构造函数当然只能使用B的构造函数,并且构造函数无法继承。

静态绑定:在程序编译的过程中,就可以判断当前调用哪个方法,或者说这个方法属于哪个类。(以static、private等修饰)

动态绑定:在程序运行的时候判断调用哪个类的方法。

this指针:方法内部所用属性为当前对象的属性。即c.getI()会返回子类的i,而c.i会返回父类的i。

猜你喜欢

转载自blog.csdn.net/qq_38709999/article/details/84000330