2

I would like to understand why is it happening like that and what is the use of the advantage following phenomenon: I use Superclass to initialize a subclass object, why will the object have the attributes of the subclass and but the methods of the superclass?

See the code to understand what I really mean:

class SuperClass {
public String s = "'This is the superclass'";
public String method() {
return s;
    }
}
class SubClass extends SuperClass {
public String s = "'This is the subclass'";
public String method() {
return s;
    }
}

public class SubClassTest {
public static void main(String[] args) {
SuperClass sc = new SuperClass();
System.out.println("Superclass s:  " + sc.s + " bzw. method: " + sc.method());
SubClass subc = new SubClass();
System.out.println("SubClass s:  " + subc.s + " bzw. method: " + subc.method());
SuperClass x = subc;
System.out.println("x s: " + x.s + " bzw. method: " + x.method());
    }
}

The output is the following:

Superclass s:  'This is the superclass' bzw. method: 'This is the superclass'
SubClass s:  'This is the subclass' bzw. method: 'This is the subclass'
x s: 'This is the superclass' bzw. method: 'This is the subclass'
Cœur
  • 37,241
  • 25
  • 195
  • 267
ArminB
  • 35
  • 1
  • 8
  • 1
    This can help probably? https://stackoverflow.com/questions/427756/overriding-a-super-classs-instance-variables – Ramkumar Venkataraman Mar 21 '18 at 06:22
  • `SuperClass x = new SubClass();` creates a reference variable of type `SuperClass` and this variable points to a `SubClass` object. This reference variable can see both `inherited and overridden methods` in `SubClass`. It won't be able to access any other method in `SubClass`. And `variables` are not inherited and that's the reason why it prints the `SubClass String`. – Mathews Mathai Mar 21 '18 at 06:40

1 Answers1

0

As Ramkumar says this link might help you

you can not override the structure of a class which is already defined, you can override the behavior. Variables of a class are not polymorphic in nature.

Tushar Deshpande
  • 448
  • 2
  • 9
  • 28