覆盖Java中的Vs类变量的方法重写 [英] method overriding Vs class variable overriding in java
问题描述
我只是尝试一些示例代码来检查Java中的类变量重写行为.下面是代码:
I was just trying some sample code for checking class variable overriding behavior in Java. Below is the code:
class A{
int i=0;
void sayHi(){
System.out.println("Hi From A");
}
}
class B extends A{
int i=2;
void sayHi(){
System.out.println("Hi From B");
}
}
public class HelloWorld {
public static void main(String[] args) {
A a= new B();
System.out.println("i->"+a.i); // this prints 0, which is from A
System.out.println("i->"+((B)a).i); // this prints 2, which is from B
a.sayHi(); // method from B gets called since object is of type B
}
}
我无法理解下面这两行的情况
I am not able to understand whats happening at these two lines below
System.out.println("i->"+a.i); // this prints 0, which is from A
System.out.println("i->"+((B)a).i); // this prints 2, which is from B
即使对象的类型为B
,为什么a.i
也打印0
?为何将它投射到B
之后打印2
?
Why does a.i
print 0
even if the object is of type B
? And why does it print 2
after casting it to B
?
推荐答案
i
不是方法-它是数据成员.数据成员不会覆盖,它们会隐藏.因此,即使您的实例是B
,它也有两个数据成员-A
中的i
和B
中的i
.当您通过A
引用进行引用时,您将获得前者;而当您使用B
引用(例如,通过显式转换它)时,您将获得后者.
i
is not a method - it's a data member. Data members don't override, they hide. So even though your instance is a B
, it has two data members - i
from A
and i
from B
. When you reference it through an A
reference you will get the former and when you use a B
reference (e.g., by explicitly casting it), you'll get the latter.
实例方法的行为有所不同.不管引用的类型如何,由于实例是一个B
实例,因此您将获得多态行为并打印出字符串"Hi From B"
.
Instance methods, on the other hand, behave differently. Regardless of the the type of the reference, since the instance is a B
instance, you'll get the polymorphic behavior and get the string "Hi From B"
printed.
这篇关于覆盖Java中的Vs类变量的方法重写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!