0

I'm a Java beginner and I can't understand when I should create an instance of the superclass or subclass. I'm studying some tutorials online and I found a few times something like the following code:

package test;

class ABC{
   public void myMethod(){
    System.out.println("Overridden Method");
   }
}
public class test extends ABC{

   @Override
   public void myMethod(){
    System.out.println("Overriding Method");
   }

   public static void main(String args[]){
    ABC obj = new test();
    obj.myMethod();
   }
}

Why I should use ABC obj = new test(); instead of test = new test();? If I need a new ABC object wouldn't it make sense to just use ABC obj = new ABC();?

Thank you, sorry for the noobie question.

devamat
  • 2,293
  • 6
  • 27
  • 50
  • I do that all the time. `List myList = new ArrayList<>();`. What kind of list is used does not matter for me later. If I find out that a `LinkedList` would be better, then it's easy to switch for me. I only have to change one single thing. And I can be sure that my code will still work as before, because I only use the `List` interface and nothing special that `ArrayList` or `LinkedList` might offer. – Johannes Kuhn Jul 08 '18 at 06:12

2 Answers2

1

Let me give you an example here, say your parent class ABC has static method or an instance variable

class ABC{
int a;
static void display(){
 System.out.println("Parent ABC");
}

Now you have ABC abc = new test();. with reference abc, you can access public void myMethod() of child class test and static method static void display() of class ABC. Also, you can use instance variable a of class ABCwith reference abc. Remember Static Method, Instance variables, Static variables are always invoked upon the Type of reference (in this case type is ABC). Whereas, instance methods are always invoked upon the type of Object we are referencing to (in this case we are referencing to test class Object).

Ankit Pandoh
  • 548
  • 5
  • 14
0

When a class is being extended from another, it becomes a child class of the parent(extended class).

A parent reference can hold a child while a child reference can always hold an instance of it self.

test t = new test();
ABC abc = new test();

are both valid. And for the question why, it may come in handy to overcome some situations.

Read more about the Polymorphism concept in object oriented programming.

Roshana Pitigala
  • 8,437
  • 8
  • 49
  • 80