Override method


class A
{
  int i=10;
  void show()
  {
    System.out.println("class A");
  }
}

class B extends A
{
  int i=5;
  public void show()
  {
    System.out.println("class B");
  }
}
class M
{
  public static void main(String s[])
  {
    A a=new B();
    a.show();
    System.out.println(a.i);
  }
}


OUTPUT= class B
        10

If a class A method is overridden by a class B method, then why not the 'i' variable?

+3
source share
8 answers

Since the variables are not virtual, only methods are used.

+5
source

It is not overwritten, but hidden. On your output, you specifically requested the value ai, not ((B) a) .i.

+5
source

"" . :

a:
    pointer to class A
    int i

b:
    pointer to class B
    int i (from A)
    int i (from B)

i B, Java , . , A i, B i ( i B , A.i B). , i, : , .

A a=new B(); , Java " , A".

, Java ( ). . , , show(), , B. : () B, . .

. Java . , B b = new B();, b.i, , B. A a = new B() Java, A. Java, , , A, i, , , A ( ) b) i ).

, , , Java .

+4

Java ?

, Java : Java ( : a A).

void foo() {
  A a = new B();
  int val = a.i; // compiler uses type A to compute the field offset
}

: " B, , a B? ?". , , .

" ", , "" , :

void foo(A a) {
  int val = a.i;
}

"", foo() , , , , foo() .

+3

Java Java.

, .

, .

, , , .

, ++ #, , Java, .

+2

a - A. B(). a. 10; .

,

public class A()

;

public class A { ... }
-1

Tip. . You can use setters and getters to make sure which data users you use.
Or . You can simply set the values ​​in the constructor instead of declaring the class.

-1
source

Because by default, variables are private. You must declare it "protected", after which it will be correctly inherited.

-3
source

Source: https://habr.com/ru/post/1718168/


All Articles