classFu{int num1 = 10;
public Fu(){
}
publicvoid show1(){
System.out.println("num1 is " + num1);
}
}
classZiextendsFu{int num1 = 11;
int num2 = 20;
public Zi(){}
publicvoid show1(){
System.out.println("num1 is " + num1);
}
publicvoid show2(){
System.out.println("num2 is " + num2);
}
}
classPolymorphicDemo2{publicstaticvoid main(String[] args) {
Fu f = new Zi();
System.out.println("num1 is " + f.num1); //member variable//System.out.println("num2 is " + f.num2); //This line must be commented out,or there is a fail during compilation.(error:can not find the symbol)
f.show1();
//f.show2();//This line must be commented out,or there is a fail during compilation.(error:can not find the symbol)
}
}
/*
running result:
num1 is 10
num1 is 11
*/
2 再看一个继承的Demo:
class Fu{
int num1;
publicFu(){
num1 = 10;
}
publicvoidshow1(){
System.out.println("num1 is " + num1);
}
}
class Zi extends Fu{
int num1 = 11;
int num2 = 20;
publicZi(){}
publicvoidshow1(){
System.out.println("num1 is " + num1);
}
publicvoidshow2(){
System.out.println("num2 is " + num2);
}
}
class InheritDemo1{
publicstaticvoidmain(String[] args) {
Zi z = new Zi();
System.out.println("num1 is " + z.num1); //member variable
System.out.println("num2 is " + z.num2);
System.out.println();
z.show1();//member method
z.show2();
}
}
/*
running result:
num1 is 11
num2 is 20
num1 is 11
num2 is 20
*/
1 首先看一个多态的Demo:class Fu{ int num1 = 10; public Fu(){ } public void show1(){ System.out.println("num1 is " + num1); }}class Zi extends Fu{ int num1 = 11; int num2 = 2