1

I've started java recently and this is what is bothering me.

consider this code.

class Superclass{
void print(){
System.out.print("hi");
}
}

class Subclass extends Superclass{
void Print(){
System.out.print("HI");
}
}

class RandomTestDrive{
public static void main(String[] args){
Superclass a = new Subclass();
a.print();
}
}

so my question here is, why would anyone declare their reference variable as superclass and object as subclass.

since you cannot use the methods of subclass from a reference variable variable that is of type superclass, why do it in the first place?

why not just make the reference variable of the same type as the object?

aditya rawat
  • 154
  • 10
  • 1
    Please format your code properly. You need the superclass-references in cases where you do not know the concrete sub-class, e.g. when deploying [Inversion of Control](https://en.wikipedia.org/wiki/Inversion_of_control) and/or [Dependency Injection](https://en.wikipedia.org/wiki/Dependency_injection). – Turing85 Dec 30 '17 at 19:31
  • So, that means it is not "NECESSARY" to do it. Only when you are dealing with special cases? – aditya rawat Dec 30 '17 at 19:39
  • Most things are not necessary, e.g. you can forego all OO-approaches and write pure structured code. In most circumstances you as programmer have to choose the right tool for the job and for the aforementioned techniques, it is suitable to work with super-type references. – Turing85 Dec 30 '17 at 19:42
  • As a programmer you have a lot of power to decide what kind of code you write. – Kayaman Dec 30 '17 at 19:42
  • I realize that but my doubt still isn't clear. subclasses inherits the members of their superclass. BUT WHAT IF WE HAD A REFERENCE VARIABLE OF TYPE SUPERCLASS AND OBJECT OF SUBCLASS. WHAT GOOD WOULD THAT DO IF YOU CAN ONLY USE THE METHODS OF SUPERCLASS? – aditya rawat Dec 30 '17 at 19:47

0 Answers0