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.
Please use Java language in an easy way with comments! Thanks! Create a calculator that uses...
Please use Java language in an easy way with comments! Thanks! Create a calculator that uses an array of buttons for numbers from 0-9, the . for decimals, and for operators +, -, * ,/ and = as well as a JTextfield that displays the current value or the result. Use ActionListeners and LayoutManagers appropriately. The example below shows how to determine which button has been clicked. ActionListener actionListener = new ActionListener() { public void actionPerformed(ActionEvent actionEvent) { System.out.println(actionEvent.getActionCommand()); }...
Please use java language in an easy way with comments! Expand your below program, so it...
Please use java language in an easy way with comments! Expand your below program, so it can include cursed items (weapons that break, armor that causes more damage when worn). In order to do that, write an interface called "CursedItem". Then create subclasses of the armor, and weapon class that implement the CursedItem interface : CursedWeapon: using a random number generator, there is a 4 in 10 chance that the weapon breaks during combat. CursedArmor: this item amplifies the damage...
Please use Java language in an easy way with comments! Thanks! Write a static method called...
Please use Java language in an easy way with comments! Thanks! Write a static method called "evaluate" that takes a string as a parameter. The string will contain a postfix expression, consisting only of integer operands and the arithmetic operators +, -, *, and / (representing addition, subtraction, multiplication, and division respectively). All operations should be performed as integer operations. You may assume that the input string contains a properly-formed postfix expression. The method should return the integer that the...
Please use Java language in an easy way with comments! Thanks! Write a static method called...
Please use Java language in an easy way with comments! Thanks! Write a static method called "evaluate" that takes a string as a parameter. The string will contain a postfix expression, consisting only of integer operands and the arithmetic operators +, -, *, and / (representing addition, subtraction, multiplication, and division respectively). All operations should be performed as integer operations. You may assume that the input string contains a properly-formed postfix expression. The method should return the integer that the...
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.
IN JAVA Inheritance Using super in the constructor Using super in the method Method overriding Write...
IN JAVA Inheritance Using super in the constructor Using super in the method Method overriding Write an application with five classes Vehicle, Car, Bus, Truck, and Tester class with main method in it. The following characteristics should be used: make, weight, height, length, maxSpeed, numberDoors, maxPassenges, isConvertable, numberSeats, maxWeightLoad, and numberAxels. Characteristics that are applicable to all vehicles should be instance variables in the Vehicle class. The others should be in the class(s) where they belong. Class vehicle should have...
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...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT