当前位置:网站首页 > Java基础 > 正文

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 java基础的 多态 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

我是小萌新

   我是小萌新

  • 上一篇: java基础培训价格
  • 下一篇: java基础百度云
  • 版权声明


    相关文章:

  • java基础培训价格2025-04-18 20:34:00
  • 乐字节java基础2025-04-18 20:34:00
  • java web基础demo2025-04-18 20:34:00
  • java 基础项目2025-04-18 20:34:00
  • 有java基础培训2025-04-18 20:34:00
  • java基础百度云2025-04-18 20:34:00
  • java大学基础教程 pdf2025-04-18 20:34:00
  • 编写java基础组件2025-04-18 20:34:00
  • java教科书 基础篇2025-04-18 20:34:00
  • java符号基础意义2025-04-18 20:34:00