Java 多态

父类的属性变量(例如变量 int a)可以被继承,同时在子类中也会同时继承该变量(super.int a,继承的变量),子类中也可以再次声明一个同名(可以同类型)的变量(double a,自己声明的同名变量),两者可以同时存在。在输出时候根据对象的引用名输出,例如:

class Animal{

public int age; //此处在Animal中定义类型为int,名为age的变量。

public void move(){

System.out.println("动物总是不安分");

}

}

class Dog extends Animal{

public double age; //此处在Dog中定义新类型double,名为age的变量。当然int尝试也可以。

public void move(){

age =10;

System.out.println("狗跑的很快");

}

}

class Cat extends Animal{

public void move(){

super.age = 3; //此处继承age,并赋值为3.且该类中未重新定义变量。

System.out.println("猫跳的很高");

}

}

public class DuiXiang03{

public static void main(String args[]){

Animal a = new Animal(); // Animal 对象

Animal b = new Dog(); // Dog 对象

Animal c =new Cat(); //Cat 对象

Dog d= new Dog();

Cat e= new Cat();

a.move();//执行 Animal 类的方法

b.move();//执行 Dog 类的方法

c.move();//执行 Cat 类的方法

d.move();//执行Dog 类的方法

e.move();//执行 Cat 类的方法

Object aValue = a.age;

Object bValue = b.age; // b.age有两个age值,一个是自定义的age值,一个是继承的age值

Object cValue = c.age;

Object dValue = d.age; // d.age有两个age值,一个是自定义的age值,一个是继承的age值

Object eValue =e.age;

System.out.println("The type of "+a.age+" is "+(aValue instanceof Double ? "double" : (aValue instanceof Integer ? "int" : ""))); // Animal 类中的 age 未被赋值

System.out.println("The type of "+b.age+" is "+(bValue instanceof Double ? "double" : (bValue instanceof Integer ? "int" : ""))); // b.age有两个age值,输出取引用名为Animal的int类型值

System.out.println("The type of "+c.age+" is "+(cValue instanceof Double ? "double" : (cValue instanceof Integer ? "int" : ""))); // c.age只有一个age值,是super所继承的Animal中的age值,再被赋值为3

System.out.println("The type of "+d.age+" is "+(dValue instanceof Double ? "double" : (dValue instanceof Integer ? "int" : ""))); // d.age有两个age值,输出取引用名为Dog的double类型值

System.out.println("The type of "+e.age+" is "+(eValue instanceof Double ? "double" : (eValue instanceof Integer ? "int" : ""))); // c.age只有一个age值,是super所继承的Animal中的age值,再被赋值为3

}

}

输出的结果为:

动物总是不安分

狗跑的很快

猫跳的很高

狗跑的很快

猫跳的很高

The type of 0 is int

The type of 0 is int

The type of 3 is int

The type of 10.0 is double

The type of 3 is int

我是小萌新 我是小萌新

239***9370@qq.com

7年前 (2018-08-30)