What is the purpose of super() in a class constructor method?
Creating a superclass and subclass with constructors - Java - Stack Overflow
Question about constructor in superclass and subclass
ELI5: Constructors & Inheritance in Java Classes
OK. The idea behind a constructor is to set up an instance of your class. You can think of the parameters of a constructor as "prerequisites" to make an instance.
If you define no constructors in a class, the compiler will generate a zero-argument constructor that does nothing.
So, let's say your class models a Car. Well, what are some things all Cars have? It probably has a top speed, a fuel efficiency, and a number of people it seats. (Trying to keep things simple for example's sake.) Since you don't ever want to create a car without those values, we want them as constructor parameters rather than relying on the user of your class to call all the right set...() methods. With the constructor, the user of the Car class is forced to provide the required parameters whenever they instantiate Cars. You can have multiple constructors that take different parameters, but you can only pick a constructor from the ones that are defined, so if we define one constructor for a Car, you must use that constructor to create them.
So, the car constructor might look like this:
public class Car {
private int topSpeed, passengersSeated;
private Integer milesPerGallon;
public Car (int topSpeed, Integer milesPerGal, int passengers) {
this.topSpeed = topSpeed;
this.milesPerGallon = milesPerGal;
this.passengersSeated = passengers;
}
// start the engine...
public void start(int someVal) { ... }
}
Now, let's say we want to build a Fire Truck. A Fire Truck is just a specialized type of car. We want our FireTruck to have an Engine Number and a hose length, right? So, let's define a FireTruck.
public class FireTruck extends Car {
private int engine, hose;
public FireTruck(int engineNum, int hoseLength) {
this.engine = engineNum;
this.hose = hoseLength;
}
}
Looks good, right? No! Why? Because a Fire Truck is a Car, and a Car must have a topSpeed, a milesPerGal and a passenger count. Our FireTruck has to have those values too, or it's not a Car. We could pass those parameters into our FireTruck constructor, but we can't just assign them to our Car member variables in the FireTruck constructor because they're private. The Car constructor sets those values for us, and it might do other logic we need. So, we'll call the Car constructor from inside our FireTruck constructor, so we can build the part of the FireTruck that is a Car before we add the FireTruck stuff. We use the "super" keyword to reference the base class's constructors and methods.
public class FireTruck extends Car {
private int engineNum, hoseLength;
public FireTruck(int topSpeed, Integer mpg, int passengers, int engine, int hose) {
// Call the base class's constructor.
// Must be the first line in this constructor.
super(topSpeed, mpg, passengers);
// Now we've set up the base Car "inside" our FireTruck.
// Add the rest of our details.
engineNum = engine;
hoseLength = hose;
}
// you can also use "super" to call functions that are in the base class --
// do this when you override a function to add more functionality.
@Override
public void start(int someVal) {
// Radio dispatch and tell them you're leaving!
// Cars don't have to do this but we do
sendDispatch("Engine " + engineNum + " is heading to the fire!");
// Call the start() method of the base class to turn on the engine, like Cars do.
// Unlike super() constructors, super. member methods can be called anywhere in any member method.
// If the super. keyword were omitted, this would become an infinite recursive loop
// because this same method would get called.
super.start(someVal);
// After starting the truck, there could be more steps to do...
startSiren();
addPassenger(dalmatian);
}
}
You can also use subclass constructors to hard-code values. For example, a Tesla Model S is a Car with no miles per gallon, since it's electric. So...
public class Tesla extends Car {
private int volts;
public Tesla (int topSpeed, int passengers, int batteryVolts) {
// no MPG since it's electric
super(topSpeed, null, passengers);
this.volts = batteryVolts;
}
}
You can even call a constructor in the same class, by using the "this" keyword.
public class Car {
private int topSpeed, passengers;
private Integer mpg;
// radio comes standard, so it's 'true' by default; we don't need to set it in every constructor.
private boolean radio = true;
public Car (int topSpeed, Integer mpg, int passengers) {
this.topSpeed = topSpeed;
this.mpg = mpg;
this.passengers = passengers;
// Lots of complicated German engineering goes here...
}
// Some cars might not have a radio; set that in this alternate constructor.
public Car (int topSpeed, Integer mpg, int passengers, boolean satelliteRadio) {
// Don't rewrite all the hard stuff from the other constructor, just call it!
// Like super() constructors, must be the first line in this constructor if you want to use it.
this(topSpeed, mpg, passengers);
// Special stuff in this constructor
this.radio = satelliteRadio;
}
}
More on reddit.com Videos
Would it be accurate to say that the word super makes the class inherit all the methods of its parent class which is Object? Is the line super(); responsible for Java knowing that every instance of my class is also an Object? Does the super(); line do anything else in this case?
Just in case this needs clarification, this is what i'm talking about
public class Product {
int id;
String name;
public Product(int id, String name) {
super();
this.id = id;
this.name = name;
}I guess you want something like this. Be noted, that it is a good idea to separate classes one-per-file in this case, as they are separate entities here. It is a good idea to limit data access to entity fields, as such using encapsulation.
Employee.java:
package tryingoutjava;
public class Employee {
// Protected access because we want it in Manager
protected int employeeId;
protected String employeeName;
public Employee(int employeeId, String employeeName) {
this.employeeId = employeeId;
this.employeeName = employeeName;
}
}
Manager.java:
package tryingoutjava;
public class Manager extends Employee {
private String employeeTitle;
public Manager(String employeeTitle, int employeeId, String employeeName) {
// Use super to invoke Employee constructor
super(employeeId, employeeName);
this.employeeTitle = employeeTitle;
}
// Just create a simple string describing manager
@Override
public String toString() {
return "Manager{" +
"employeeTitle='" + employeeTitle +
"employeeId=" + employeeId +
", employeeName='" + employeeName + '\'' +
'}';
}
}
Application.java:
package tryingoutjava;
public class Application {
// Example of construction plus printing of Manager data
public static void main(String[] args) {
Employee davie = new Employee(1, "Dave The Cable Guy");
Manager tom = new Manager("CFO", 2, "Tomas");
System.out.println(tom.toString());
}
}
Constructors (most often than not) just delegate construction of parent through super invocation. While there are other techniques, like Builder pattern, this is the most basic and understandable approach. There are several other ways to do this, but this should get you started, hope it helps!
Purpose of Constructor
constructor is a method like other method but it is called when instantiate (or create a object from your class) for initialize your object for first use or later use. for example a class like Student must created (instantiated) when we give it name and family name for example. Without them, create a Student is not good because maybe we forget to give it proper name and use it incorrectly. constructor forces us to provide minimum things needed for instantiating objects from classes.
Constructor implementation in inheritance
About inheritance, it is different. When you want to create a Student which is a Human (extends Human) you must first create Human inside your Student and set special feature for your Student like ID which is not for Human (Human has name and etc). so when you create a Student with constructor, the super constructor (for Human) is called too.
What do we do in constructor
as I mentioned, we provide default value for our properties which must set them before creating and using object. (for using them properly) every subclass call super class constructor implicitly with super() but if super class doesn't have any default constructor (constructor with no argument) you must explicitly say super(...) at the first lien of subclass constructor (otherwise compile error)
What is the program steps when using constructor (Advanced)
- super class static constructor and static variable (read by self if you want to know more about things I say here)
- subclass class static constructor and static variable
- super class variable and block constructor
- super class constructors
- sub class variable and block constructor
- sub class constructors
I only mentioned 4 & 6. I try to explain completely. My English is not good. I'm sorry.