java 多态判断非空_Java 多态

这篇博客探讨了Java中类的继承特性,特别是父类属性变量在子类中的继承和覆盖。通过实例展示了如何在子类中声明同名变量并分别使用。内容包括Animal、Dog和Cat类的定义,以及不同对象的输出结果,强调了对象引用名在决定输出值中的作用。

父类的属性变量(例如变量 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.com2年前 (2018-08-30)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值