How can I get data fields from subclass not superclass?

I have a superclass named TestSuper

public class TestSuper {
  int a = 0;
}

      

and I have 2 subclasses named TestSub

and TestSub2

that extendTestSuper

public class TestSub extends TestSuper{
   int a=1;
}

public class TestSub2 extends TestSuper{
   int a=2;
}

      

in my main class i created a method that takes a type TestSuper

and returns its value, and in main i display it on the console

public class Main {
public static void main(String[] args){

    System.out.println(test(new TestSub())+" "+test(new TestSub2()));
}
public static int test(TestSuper b){
    return b.a;
}
}

      

but the output is "0 0" instead of "1 2", what should I do?

+3


source to share


4 answers


You need to provide a link to say which one you want.

public static int test(TestSuper b){
    return b instanceof TestSub ? ((TestSub) b).a :
           b instanceof TestSub2 ? ((TestSub2) b).a :
           b.a;
}

      



If it sounds overly complicated, it is. You should use polymorphism instead.

public class TestSuper {
    int a = 0;
    public int getA() { return a; }
}

public class TestSub extends TestSuper {
    int a = 1;
    public int getA() { return a; }
}

public class TestSub2 extends TestSuper {
    int a = 2;
    public int getA() { return a; }
}

public static int test(TestSuper b) {
    return b.getA();
}

      

+3


source


First to understand the difference between hiding and overriding: https://docs.oracle.com/javase/tutorial/java/IandI/override.html



Then create a getter method in the base class, which you can override in your subclass.

0


source


You can peek into the theory behind this and then do the only sensible thing to do is forget to write code like this.

In good OOP, you consider your fields to be part of your "secret" internal implementation. You are not using subclass fields in the superclass context. Period.

You are even very conservative about creating a protected field in a superclass and using it in subclasses.

0


source


When you call the test method like this:

test(new TestSub())+" "+test(new TestSub2())

      

You are using upstream. Upcasting decouples interface and implementation for an object. But to separate interface and implementation and achieve true implementation in polymorphism, you must use polymorphic structures. Instance variables are not polymorphic. Because of this, you are actually calling a variable that is in the class TestSuper

.

Only instance methods are polymorphic.

0


source







All Articles