简体   繁体   English

方法覆盖java中的Vs类变量重写

[英]method overriding Vs class variable overriding in java

I was just trying some sample code for checking class variable overriding behavior in Java. 我只是尝试了一些示例代码来检查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

Why does ai print 0 even if the object is of type B ? 为什么即使对象是B类, ai也会打印0 And why does it print 2 after casting it to B ? 为什么在将它投射到B后打印2

i is not a method - it's a data member. i不是一个方法 - 它是一个数据成员。 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 . 所以,即使你的实例是B ,它有两个数据成员- iAiB When you reference it through an A reference you will get the former and when you use a B reference (eg, by explicitly casting it), you'll get the latter. 当你通过A引用引用它时,你会得到前者,当你使用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. 无论引用的类型如何,因为实例是B实例,您将获得多态行为并打印字符串"Hi From B"

Even though A is initialized as new B(), the variable is an A. if you say 即使A被初始化为新的B(),如果你说,变量是A.

B a = new B();

you won't have that problem. 你不会有这个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM