Java的变量不遵循多态和覆盖
Java的变量不遵循多态性。覆盖仅适用于方法而不适用于变量。在Java,如果子类和父类都有一个同名的变量,子类的变量会隐藏父类的变量,即使它们的类型不同。这个概念被称为变量隐藏。在方法覆盖的情况下,覆盖方法完全取代了继承的方法,但在变量隐藏中,子类隐藏了继承的变量而不是替换它们,这基本上意味着 Child 类的对象包含两个变量,但 Child 的变量隐藏了 Parent 的变量。
因此,当我们尝试访问 Child 类中的变量时,它将从子类中访问。如果我们试图访问 Parent 和 Child 类之外的变量,那么实例变量将从引用类型中选择。
例子
Java
// Java Program Illustrating Instance variables
// Can not be Overridden
// Class 1
// Parent class
// Helper class
class Parent {
// Declaring instance variable by name `a`
int a = 10;
public void print()
{
System.out.println("inside B superclass");
}
}
// Class 2
// Child class
// Helper class
class Child extends Parent {
// Hiding Parent class's variable `a` by defining a
// variable in child class with same name.
int a = 20;
// Method defined inside child class
public void print()
{
// Print statement
System.out.println("inside C subclass");
}
}
// Main class
public class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating a Parent class object
// Reference Parent
Parent obj = new Child();
// Calling print() method over object created
obj.print();
// Printing superclass variable value 10
System.out.println(obj.a);
// Creating a Child class object
// Reference Child
Child obj2 = new Child();
// Printing childclass variable value 20
System.out.println(obj2.a);
}
}
输出
inside C subclass
10
20
Conclusion:
Variables in Java do not follow polymorphism and overriding. If we are trying to access the variable outside of Parent and Child class, then the instance variable is chosen from the reference type.