Question

In: Computer Science

How to identify when to use super() in constructor for java language in a easy way?

How to identify when to use super() in constructor for java language in a easy way?

Solutions

Expert Solution

-------------------- I Used Online Java Compiler --------------------

The super keyword mainly refers to the objects of parent class.

Inorder to use super keyword you need to know the Inheritance concept.

Your question is "when to use super() in constructor for java language"

I mainly use super keyword for two reasons
1. To get parent class variables and methods from child class.
2. To reuse as well as reduce repeatation code

In java, If we are using inheritance concept between two or more classes then by default with or without specifying super(); will execute parent class default constructor, NOT parameterised constructor.

I will demostrate now,

CASE 1:

In the below example, Inside main method I created only the object of AnotherChild class even though the two parent class default constructor is called.

CASE 2:

POINT TO REMEMBER is that after compiled, Compiler knows the hierarchy of all parent and child classes. And execution order goes like parent class to child class, Parent class constructor is called first then its child then it's child ...likewise.

In the above example, AnotherChild class object is calling it's parameterised constructor ("John Wick"),
So inside AnotherChild parameterised constructor I am calling super(name); , So it call it's parent class parameterised constructor, In this case Child(String name) constructor is called and before it enter into child class its parent class default constructor is called.

So that is the reason output come like this

Parent Class Constructor
Child Class Constructor : John Wick

I can demonstrate use of super() keyword using further more example,

Consider Person class which contain variables id and name and one parameterised constructor which store the values to id and name. Here "this" keyword is used to distinguish between parameters and it's class variables. In this case both parameters name and class variable names are same.

Employee class inherits Person class, So person class variables and methods can be accessable by child class.
Employee class contains one variable salary, one method and one parameterised constructor.

Create one object of Employee class and use parameterised constructor to pass the employee details and then display.

Inside Employee parameterised constructor, I am calling super(id,name) which initialise the id and name in the Person class which can also be used from Employee class.

The above example is very simple, The real use comes when so many COMMON variables and methods come into picture. I hope you got the idea.

------------------ CODE ------------------

class Person
{
int id;
String name;
  
Person (int id, String name)
{
this.id = id;
this.name = name;
}
  
}

class Employee extends Person
{
float salary;

Employee (int id, String name, float salary)
{
//Reusing parent parameterised constructor using super(parameter , parameter)
//id and name is passing to the parent class variable
super (id, name);      
//Only salary is specifying here but still we get all the variables(id,name) of parent class
//because of inheritance
this.salary = salary;
}
  
void Display ()
{
//Even though id and name is not specified in this class, we can use these variables from parent class
//If child class Employee also specified id and name
//then we need to use
//super.id and super.name instead of just printing id and name
//System.out.println ("Employee ID : "+super.id);
//System.out.println ("Employee Name : "+super.name);
System.out.println ("Employee ID : "+id);
System.out.println ("Employee Name : "+name);
System.out.println ("Employee Salary : "+salary);
}
  
}

public class Main
{
public static void main (String[]args)
{
//Calling the parameterised constructor
Employee emp = new Employee(1001, "John Wick", 60000f);
//Display the values
emp.Display();
}
}

Please check the below explanations also:

We can use the parent class variable or method from child class using super keyword.

In other case, If parent and child class have same variable name, then use of super keyword is to distinguish which variable belong to parent class and child class

-------------------- CODE --------------------

class Parent
{
int noOfBabies = 10;
}

//Child class inherit parent class using extends keyword
class Child extends Parent
{
int noOfBabies = 4;
void Print()
{
System.out.println("Number of Babies : " + noOfBabies);
System.out.println("Number of Babies : " + super.noOfBabies);
}
}

public class Main
{
   public static void main(String[] args)
   {
       Child child = new Child();
child.Print();
   }
}

Below screenshot demonstrate the parent class and child class METHOD can be distinguishable using super keyword.

-------------------- CODE --------------------

class Parent
{
int noOfBabies = 10;
void Print()
{
System.out.println("Number of Babies : " + noOfBabies);
}
}

//Child class inherit parent class using extends keyword
class Child extends Parent
{
int noOfBabies = 4;
void Print()
{
System.out.println("Number of Babies : " + noOfBabies);
}
  
void DisplayAll()
{
//Calling child class method
Print();
//Calling parent class method using super
super.Print();
}
}

public class Main
{
   public static void main(String[] args)
   {
       Child child = new Child();
child.DisplayAll();
   }
}


Related Solutions

Please use java language in an easy way and comment as much as you can! Thanks...
Please use java language in an easy way and comment as much as you can! Thanks 1. A driver class with a main method, which creates instances of various objects (two of each subclass) and adds them as items to an ArrayList named "inventory". A foreach loop should loop through the ArrayList and call the use() method of each item. Define the ArrayList in a way that it only holds elements of the GameItem class and its subclasses. Make proper...
Please use java language in an easy way and comment as much as you can! Thanks...
Please use java language in an easy way and comment as much as you can! Thanks (Write a code question) Write a generic method called "findMin" that takes an array of Comparable objects as a parameter. (Use proper syntax, so that no type checking warnings are generated by the compiler.) The method should search the array and return the index of the smallest value. (Analysis of Algorithms question) Determine the growth function and time complexity (in Big-Oh notation) of the...
Please use java language in an easy way and comment as much as you can! Thanks...
Please use java language in an easy way and comment as much as you can! Thanks (Write a code question) Write a generic method called "findMin" that takes an array of String objects as a parameter. (Use proper syntax, so that no type checking warnings are generated by the compiler.) The method should search the array and return the index of the smallest value.
In general Describe when, where, and how is super keyword used in a constructor.
In general Describe when, where, and how is super keyword used in a constructor.
JAVA: *USING INHERITANCE *USING SUPER IN TH CONSTRUCTOR *USING SUPER IN THE METHOD *METHOD OVERRIDING Create...
JAVA: *USING INHERITANCE *USING SUPER IN TH CONSTRUCTOR *USING SUPER IN THE METHOD *METHOD OVERRIDING Create an application with 5 classes: 1.) Vehicle 2.) Car 3.) Bus 4.) Truck 5.) Tester Following characteristics should be used: make, weight, height, length, maxSpeed, numberDoors, maxPassengers, isCpnvertable, numberSeats, maxWeightLoad, numberAxels **Class Vehicle: should have a constructor that initializes all of it's data **Classes Car, Bus, Truck: will have constructors that resuse their parents constructors and provide additional code for initalizing their specific data...
When using language in small group, it is desirable to use specific and concrete language. Identify...
When using language in small group, it is desirable to use specific and concrete language. Identify ambiguous language that may cause your group to suffer a miscommunication. How can your language choice lead to a breakdown of communication? What are the characteristics of a specific type of listening that will help to avoid a breakdown of communication?
Language: Java or C (NO OTHER LANGUAGE) Do NOT use Java library implementations of the data...
Language: Java or C (NO OTHER LANGUAGE) Do NOT use Java library implementations of the data structures (queues, lists, STs, hashtables etc.) Have a unit test implemented in main(). And comment every code. Show examples from the executions. Assume that the edges defined by the vertex pairs in the data base are one-way. Question: Write a program that can answer if there is a path between any to vertices. For the vertex pairs use this as your input example: AL...
Language: Java or C (NO OTHER LANGUAGE) Do NOT use Java library implementations of the data...
Language: Java or C (NO OTHER LANGUAGE) Do NOT use Java library implementations of the data structures (queues, lists, STs, hashtables etc.) Have a unit test implemented in main(). And comment every code. Show examples from the executions. Assume that the edges defined by the vertex pairs are two-way. Question: First step: write a program based on DFS which can answer questions of the type: "Find the a path from X to Y" Which should result in a list of...
Language: Java or C (NO OTHER LANGUAGE) Do NOT use Java library implementations of the data...
Language: Java or C (NO OTHER LANGUAGE) Do NOT use Java library implementations of the data structures (queues, lists, STs, hashtables etc.) Have a unit test implemented in main(). And comment every code. Show examples from the executions. Question: First step: write a program based on DFS which can answer questions of the type: "Find the a path from X to Y" Which should result in a list of vertices traversed from X to Y if there is a path....
When doing Machine Learning and Deep Learning (AI) research which language is better to use Java...
When doing Machine Learning and Deep Learning (AI) research which language is better to use Java or Python? When would you use Java and when would you use Python?
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT