Day04.a(对象类型的转换,多态)

时间:2023-03-09 03:51:03
Day04.a(对象类型的转换,多态)

对象类型的转换

  Dog dog = new Dog();

  通常情况下,对象(new Dog())类型和引用(dog)类型是相同的,当引用类型和对象类型不一致时,就需要类型转换。

  向上转型:将较具体的类转换为较抽象的类。(子类对象-> 父类对象)即把子类对象赋值给父类类型的变量。安全

    这样可以做到在父类中定义一个方法完成各个子类的功能,使同一份代码无差别运用到不同类型之上。这是多态机制的基本思想。

  向下转型:将较抽象的类转换为较具体的类。(父类对象 -> 子类对象)但是如果将父类对象直接赋予子类,会出现编译器错误。所以必须使用显示类型转换,向编译器指明将父类对象转换为哪一种类型的子类对象。 不安全

  使用操作符instanceof判断父类对象是否为子类对象的实例,返回值为boolean类型。

方法重载

  方法重载是为了让方法名相同而形参不同的构造方法同时存在

  不定长参数方法: 返回值 方法名(参数数据类型 ... 参数名称)

    int add(int ... a) 这个不定长参数a是一个数组,编译器将int...a看成int[]a。

多态

  多态可以使程序具有良好的扩展性,并对所有类对象进行通用的处理

  Java中多态性表现:

    方法的重载和重写

    可以用父类的引用指向子类的具体实现,而且可以随时更换为其它子类的具体实现。

//创建一个Animal类1 public class Animal {
         String name;
         public void say() {
              System.out.println("I am an animal.");
       }
 }
建立一个Dog类继承Animal类,并重写say()方法

1 public class Dog extends Animal {
        public void say() {
            System.out.println("I am a dog.");
    }
        public void yell() {
            System.out.println("Bowl,Bowl,Bowl.")
    }
 }
建立Cat类继承Animal类,重写say()方法

1  public class Cat extends Animal {
          public void say() {
              System.out.println("I am a Cat .");
       }
          public void yell() {
              System.out.println("Meow, Meow, Meow.")
       }
 }
public class Text {
       public static void main(String[] args) {
            Dog dog = new Dog();
            dog.say();
            dog.yell();
            Cat cat = new Cat();
            cat.say();
            cat.yell();
       }
}

输出:I am a dog.Bowl, Bowl, Bowl.I am a cat.Meow, Meow, Meow
 public class Text2 {
     public static void main(String[] args) {
         Animal dog = new Dog(); //向上类型转换,使用父类的引用指向子类对象
         dog.say();
         dog.yell();   //报错。The method yell() is undefined for the type Animal,因为dog引用是Animal类型,使用强制类型转换修正((Dog) dog).yell();
         Animal cat = new Cat();
         cat.say();
         cat.yell();    //报错。
     }
 }
 public class Text3 {
     //创建静态方法doSomething方法(在main方法中可以直接调用),使用instanceof关键字,解决Text2中的错误
     public static void doSomething(Animal animal) {
         animal.say();
         if (animal instanceof Dog) {
             ((Dog) animal).yell();
         } else if (animal instanceof Cat) {
             ((Cat) animal).yell();
         }
     }

     public static void main(String[] args) {
         doSomething(new Dog());  //直接创建对象后调用静态方法
         doSomething(new Cat());
     }
 }
输出:I am a dog.Bowl, Bowl, Bowl.I am a cat.Meow, Meow, Meow