Data binding in java oveeriding

I am a beginner for java. I wrote the following code

class SuperA{
  Integer a = 1;
  protected void f(){
    System.out.println("in superA");
  }
}

class Test extends SuperA{
  Integer a = 2;
  protected void f(){
    System.out.println("in test");
  }

  public static void main(String... args) throws Exception{   

    SuperA o = new Test();
    o.f();
    System.out.println("a = "+o.a);
  }
}

Result: in the test

a = 1

I know why this is in test. But it didn’t work out why a=1. I thought it should be a=2.

What is the method of causing differences and data in polymorphism?

+4
source share
3 answers
class SuperA{
  Integer a = 1;

class Test extends SuperA{
  Integer a = 2;

Your class Testhas two independent instance variables named a. They are available as

this.a

and

((SuperA)this).a

This distinguishes them from methods where f(), defined in Test, overrides the value in SuperA, therefore Testdoes not have a version of the superclass.

+3
source

, .. a , oa SuperA , o/p 1 2. . →

+1

I would recommend you do this:

class SuperA {
  protected Integer a = 1;

  protected void f() {
    System.out.println("in superA");
  }
}

class Test extends SuperA {
  private static final Integer DEFAULT_A = 2;

  public Test() {
    super(DEFAULT_A);
  }

  protected void f(){
    System.out.println("in test");
  }
}
0
source

All Articles