多态中基类和子类相同名字的属性的相关问题

 测试1:

package polymorphism;

public class Hero {        

        
    int moveSpeed; //移动速度
     
    public boolean equals(Object o){
        if(o instanceof Hero){
            Hero h = (Hero) o;
            return this.hp == h.hp;
        }
        return false;
    }
    
    public int getMoveSpeed(){
        return this.moveSpeed;
    }
     
    public int getMoveSpeed2(){
        return 199;
    }


      
}
package polymorphism;


public class ADHero extends Hero {
 
    int moveSpeed=3; //移动速度 
     
    public int getMoveSpeed(){
        return this.moveSpeed;
    }
     
    public int getMoveSpeed2(){
        return super.moveSpeed;
    }
     
    public static void main(String[] args) {
    	Hero h1=new Hero();
    	h1.moveSpeed = 300;
    	Hero h2=new ADHero();
    	h2.moveSpeed = 300;
    	System.out.println(h2.getMoveSpeed());
    	System.out.println(h2.getMoveSpeed2());
    }
  
}

结果是:

3
300

h2.getMoveSpeed()和h2.getMoveSpeed2()使用了子类中的实现,然而h2.moveSpeed指向了父类中的属性

测试2:

package polymorphism;

public class Hero {
        
    int moveSpeed; //移动速度
     
    public boolean equals(Object o){
        if(o instanceof Hero){
            Hero h = (Hero) o;
            System.out.println(this.moveSpeed+" "+h.moveSpeed);
            return this.moveSpeed == h.moveSpeed;
        }
        return false;
    }    
      
}
package polymorphism;

public class ADHero extends Hero {
 
    int moveSpeed=300; //移动速度

    public static void main(String[] args) {
    	Hero h1=new Hero();
    	h1.moveSpeed = 300;
    	Hero h2=new ADHero();
    	System.out.println(h1.equals(h2));    	
    	System.out.println(h2.equals(h1));
    }
  
}

结果是:

300 0
false

0 300
false

在Hero h = (Hero) o中,如果o是Hero子类,转换之后,h默认使用o的父类中的moveSpeed。

你可能感兴趣的:(Java)