标签:
package jin.feng1; class Person{ void print(){ System.out.println(); } // } public class Student extends Person { public void sst(){} public static void main(String[] args) { Person p1=new Student(); p1.sst(); //编译错误,不能访问 p1.print(); } }
class Person{ void print(){System.out.println(" person");} void sst(){} } class Person1 extends Person{ void print(){System.out.println(" person1");} } class Person2 extends Person{ void print(){System.out.println(" person2");} } public class Student { static void tune(Person p1){ p1.print();//子类覆盖,则根据具体类型调用具体方法 } public static void main(String[] args) { Person p1=new Person1();//p1是基类Person类型,它可选的调用的子类没有覆盖方法sst()和子类覆盖的方法print() p1.sst();//子类没有覆盖,则直接调用基类 Person p2=new Person2(); tune(p1); tune(p2);// } }
public class Student{ private void print(){System.out.println(" Student");} public static void main(String[] args) { Student p1=new Student1(); p1.print();//貌似是动态绑定,其实调用的是自己类中的private方法。 } } class Student1 extends Student { void print(){System.out.println(" Student1");} } //output Student 缺陷2:成员变量和静态方法 package jin.feng1; class Super{ int field=0; int getField(){return field;} } class Sub extends Super{ int field=1; int getField(){return field;} int getSuperField(){return super.field;} } public class Student{ public static void main(String[] args) { Super super1=new Sub(); System.out.println("成员变量访问:"+super1.field+"方法访问:"+super1.getField()); Sub sub1=new Sub(); System.out.println(sub1.getField()+" "+sub1.getSuperField()); } }
package jin.feng1; class Static1{ static void print(){System.out.println("Static1 method");} void ss(){System.out.println("normal1 method");} } class Static2 extends Static1{ static void print(){System.out.println("Static2 method");} void ss(){System.out.println("normal2 method");} } public class StaticDynmic { public static void main(String args[]){ Static1 static1=new Static2(); static1.print(); static1.ss(); } }
package jin.feng1; class Constructor11{ void draw(){System.out.println(" Constructor11 draw()");} public Constructor11(){ System.out.println("Constructor11:before draw()"); draw(); System.out.println("Constructor11:after draw()"); } } class Constructor12 extends Constructor11{ private int radius=2; public Constructor12(){ System.out.println("Constructor12:before draw()"); draw(); System.out.println("Constructor12:after draw()"); } void draw() { System.out.println("Constructor12+draw "+radius); } } public class Constuctor22 { public static void main(String[] args) { new Constructor12(); } }
标签:
原文地址:http://blog.csdn.net/xu5025/article/details/42297589