Java 中父类和子类具有相同的数据成员
父类可以持有对父对象和子对象的引用。如果父类变量持有子类的引用,并且该值在两个类中都存在,通常,该引用属于父类变量。这是由于 Java 中的运行时多态特性。
示例
以下是一个示例:
class Demo_base {
int value = 1000;
Demo_base() {
System.out.println("This is the base class constructor");
}
}
class Demo_inherits extends Demo_base {
int value = 10;
Demo_inherits() {
System.out.println("This is the inherited class constructor");
}
}
public class Demo {
public static void main(String[] args) {
Demo_inherits my_inherited_obj = new Demo_inherits();
System.out.println("In the main class, inherited class object has been created");
System.out.println("Reference of inherited class type :" + my_inherited_obj.value);
Demo_base my_obj = my_inherited_obj;
System.out.println("In the main class, parent class object has been created");
System.out.println("Reference of base class type : " + my_obj.value);
}
}输出
This is the base class constructor This is the inherited class constructor In the main class, inherited class object has been created Reference of inherited class type :10 In the main class, parent class object has been created Reference of base class type : 1000
解释
一个名为“Demo_base”的类包含一个整数值和一个打印相关消息的构造函数。另一个名为“Demo_inherits”的类成为父类“Demo_base”的子类。这意味着“Demo_inherits”类扩展到基类“Demo_base”。
在这个类中,为同一个变量定义了另一个值,并且定义了子类的构造函数,其中包含要在屏幕上打印的相关消息。一个名为 Demo 的类包含 main 函数,在该函数中,创建了子类的实例,并在屏幕上打印了其关联的整数值。通过创建实例并访问其关联的值并在屏幕上打印它,对父类也执行了类似的过程。
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP