java里面的对象转型和多态

1.对象转型 

  需要两个类之间有继承关系

 

 

 class Animal{     
public String name;
      Animal(String name){
           this.name=name;
     }
}

class Cat extends Animal{
      public String eyeColor;
      Cat(String a, String e){
            super(a);
            this.eyeColor=e;
      }
}

class Dog extends Animal{
       public String furColor;
       Dog(String a,String e){
            super(a);
            this.furColor=e;
       }
}

    Animal a = new Dog("small dog","yellow");

    System.out.println(a.furColor); //error

    System.out.println(a.name); //ok

    System.out.println(a instance of Animal); //true

    System.out.println(a instance of Dog); //true

    Dog d = (Dog)a;

    System.out.println(d.furColor);//ok

 

2.多态

    1.要有继承;

    2.要有重写;

    3.父类引用指向子类对象;(在方法里)

class Animal {
  private String name;
  Animal(String name) {this.name = name;}
  
  public void enjoy(){
    System.out.println("叫声......");
  }
 
}

class Cat extends Animal {
  private String eyesColor;
  Cat(String n,String c) {super(n); eyesColor = c;}
  
  public void enjoy() {
    System.out.println("猫叫声......");
  }
  
}

class Dog extends Animal {
  private String furColor;
  Dog(String n,String c) {super(n); furColor = c;}
 
  public void enjoy() {
    System.out.println("狗叫声......");
  }
}

class Lady {
    private String name;
    private Animal pet;
    Lady(String name,Animal pet) {
        this.name = name; this.pet = pet;
    }
    public void myPetEnjoy(){pet.enjoy();}
}

public class Test {
    public static void main(String args[]){
        Cat c = new Cat("catname","blue");
        Dog d = new Dog("dogname","black");
        Bird b = new Bird();
        Lady l1 = new Lady("l1",c);
        Lady l2 = new Lady("l2",d);
        
        l1.myPetEnjoy();
        l2.myPetEnjoy();
    }
}
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值