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

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

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

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

4.除了static方法和final方法(private方法属于final方法),其余全部方法都是后期绑定,Java中全部的方法都是经过动态绑定来实现多态blog

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());
	}

}

 输出结果:get

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

 

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

一般将域设置成private,不能直接访问,也不能被继承,经过调用方法来访问 class

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()