Java中对域和静态方法的访问不具有多态性

1.将方法调用同方法主体关联起来被称为

2.编译期绑定(静态)是在程序编译阶段就确定了引用对象的类型

3.运行期绑定(动态绑定)是指在执行期间判断所引用对象的实际类型,根据其实际的类型调用其相应的方法

4.除了static方法和final方法(private方法属于final方法),其他所有方法都是后期绑定,Java中所有的方法都是通过动态绑定来实现多态

5.访问某个域的行为不具有多态性

package polymorphism;

class SuperField {
	public int field = 1;

	public int getField() {
		return field;
	}
}

class SubField extends SuperField {
	public int field = 2;
	
	public int getField() {
		return field;
	}
	
	public int getSuperField() {
		return super.field;
	}
}

public class FieldPolymorphism {

	public static void main(String[] args) {
		SuperField sup = new SubField();
		System.out.println("sup.field = " + sup.field + ", sup.getField() = " + sup.getField());
		SubField sub = new SubField();
		System.out.println("sub.field = " + sub.field + ", sub.getField() = " + sub.getField() +
				", sub.getSuperField() = " + sub.getSuperField());
	}

}

 输出结果:

sup.field = 1, sup.getField() = 2
sub.field = 2, sub.getField() = 2, sub.getSuperField() = 1

 

当SubField对象转型为Super引用时,任何域访问操作都将由编译器解析,因此不是多态的,SubField实际包含两个称为field的域:自己的和从SuperField处继承来的

通常将域设置成private,不能直接访问,也不能被继承,通过调用方法来访问

6.访问某个静态方法不具有多态性,不与单个对象相关联

package polymorphism;

class Super {
	
	public static String staticMethod() {
		return "Super staticMethod()";
	}
}

class Sub extends Super {
	public static String staticMethod() {
		return "Sub staticMethod()";
	}
}

public class StaticPolymorphism {

	public static void main(String[] args) {
		Super sup = new Sub();
		System.out.println(sup.staticMethod());
		System.out.println(Sub.staticMethod());
	}

}

 输出结果:

Super staticMethod()
Sub staticMethod()

 

posted @ 2017-10-10 01:18  花弄影  阅读(1030)  评论(0编辑  收藏  举报