0

The superclass:

public class Modem {

Modem(){
    System.out.println("The Modem Constructor");
}

Modem(String entry){
    System.out.println("The " +entry);
 }
}

The subclass:

public class CableModem extends Modem {
    
    CableModem(String entry){
        System.out.println("The " + entry);
    }
    
    CableModem(){
        System.out.println("The CableModem Constructor");
    }
}

Main class:

public class Main {

    public static void main(String[] args) {
        CableModem cMod = new CableModem();
        Modem mod = new Modem();
   }

}

The output that i get:

The Modem Constructor

The CableModem Constructor

The Modem Constructor

So when I create an object of the subclas, both its and the supperclass constructors are being called. Why is this happening, and how can I prevent it from happening?

FlickIt
  • 71
  • 1
  • 7
  • 3
    Does this answer your question? [Why is constructor of super class invoked when we declare the object of sub class? (Java)](https://stackoverflow.com/questions/7173019/why-is-constructor-of-super-class-invoked-when-we-declare-the-object-of-sub-clas) – kasptom Oct 17 '20 at 10:00
  • `CableModem extends Modem` so it is normal the super class constructor is also called (and contructor of grand mother class if supper class inherits a class itself etc), this is one of the consequences of the inheritance – bruno Oct 17 '20 at 10:00
  • when a class has a superclass a superclass constructor will allways be called. You can determine wich superclass constructor will be called by using super() in the subclass constructor; based on the parameter signature from super() a superclass constructor will be called. – Tom Oct 17 '20 at 10:08
  • An object of a subclass is also an object of a superclass. For example, a cable modem is a modem, and a table is a furniture. If a superclass has some members, which need to be initialized (for example, `ModemState state;` needs to be initialized to `offState`), that initialization is done by a constructor: `state = offState;`. When you create your `CableModem` object it must have the same initialization done – otherwise the base-class methods will not work properly. Hence the base class constructor must be – and implicitly is – executed just before the derivative class constructor. – CiaPan Oct 17 '20 at 10:10
  • Thank y'all for the help, I apreaciate it! – FlickIt Oct 17 '20 at 11:02

0 Answers0