你说的好乱,变量是没有多态的,方法存在多态
这是我之前写的一个关于多态的例子,我想你应该是这么个意思,看完你就知道了
关于多态,多方求解之后方得到的正确答案
import static Test_purview.print.*;
import Test_initalized.neum;
public class Test_diversifyTest1 {
public static void main(String[] args){
Cycle c = new Cycle();
print(" 车轮数:"+c.ride(neum.Bicycle).wh);
Unicycle c1 = new Unicycle();
print(" 车轮数:"+((Unicycle)c1.ride(neum.Unicycle)).wh);
print(" 车轮数:"+((Unicycle)c1.ride(neum.Unicycle)).wh1);
// 把返回的Cycle类型强制转换成Unicycle类型就能得到正确的wh了
// 向下面这样子会得到的结果是0而不是4
// print(" 车轮数:"+c1.ride(neum.Unicycle).wh);
}
}
class Cycle{
int wh = 0;
public Cycle(){
print("This is in The class Cycle!");
}
public Cycle ride(Object o){
print("Class: "+ this);
return this;
}
}
class Unicycle extends Cycle{
int wh1 = 4;
public Unicycle(){
print("This is in The class Unicycle!");
}
public Unicycle ride(Unicycle o){
print("Class: "+ this);
return this;
}
}
class Bicycle extends Cycle{
int wh = 2;
public Bicycle(){
print("This is in The class Bicycle!");
}
}
class Tricycle extends Cycle{
int wh = 3;
public Tricycle(){
print("This is in The Tricycle!");
}
}
//Output:
//This is in The class Cycle!
//Class: Diversify.Cycle@61de33
// 车轮数:0
//This is in The class Cycle!
//This is in The class Unicycle!
//Class: Diversify.Unicycle@ca0b6
// 车轮数:0
//Class: Diversify.Unicycle@ca0b6
// 车轮数:4 |