(Translated by https://www.hiragana.jp/)
Inheritance and Constructors in Java - GeeksforGeeks
Open In App

Inheritance and Constructors in Java

Last Updated : 19 Jul, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Constructors in Java are used to initialize the values of the attributes of the object serving the goal to bring Java closer to the real world. We already have a default constructor that is called automatically if no constructor is found in the code. But if we make any constructor say parameterized constructor in order to initialize some attributes then it must write down the default constructor because it now will be no more automatically called.   

Note: In Java, constructor of the base class with no argument gets automatically called in the derived class constructor. 

Example:

Java




// Java Program to Illustrate
// Invocation of Constructor
// Calling Without Usage of
// super Keyword 
 
// Class 1
// Super class
class Base {
 
    // Constructor of super class
    Base()
    {
        // Print statement
        System.out.println(
            "Base Class Constructor Called ");
    }
}
 
// Class 2
// Sub class
class Derived extends Base {
 
    // Constructor of sub class
    Derived()
    {
 
        // Print statement
        System.out.println(
            "Derived Class Constructor Called ");
    }
}
 
// Class 3
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating an object of sub class
        // inside main() method
        Derived d = new Derived();
 
        // Note: Here first super class constructor will be
        // called there after derived(sub class) constructor
        // will be called
    }
}


Output

Base Class Constructor Called 
Derived Class Constructor Called 

Output Explanation: Here first superclass constructor will be called thereafter derived(sub-class) constructor will be called because the constructor call is from top to bottom. And yes if there was any class that our Parent class is extending then the body of that class will be executed thereafter landing up to derived classes. 

But, if we want to call a parameterized constructor of the base class, then we can call it using super(). The point to note is base class constructor call must be the first line in the derived class constructor. 

Implementation: super(_x) is the first line-derived class constructor.

Java




// Java Program to Illustrate Invocation
// of Constructor Calling With Usage
// of super Keyword
 
// Class 1
// Super class
class Base {
    int x;
 
    // Constructor of super class
    Base(int _x) { x = _x; }
}
 
// Class 2
// Sub class
class Derived extends Base {
 
    int y;
 
    // Constructor of sub class
    Derived(int _x, int _y)
    {
 
        // super keyword refers to super class
        super(_x);
        y = _y;
    }
 
    // Method of sub class
    void Display()
    {
        // Print statement
        System.out.println("x = " + x + ", y = " + y);
    }
}
 
// Class 3
// Main class
public class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating object of sub class
        // inside main() method
        Derived d = new Derived(10, 20);
 
        // Invoking method inside main() method
        d.Display();
    }
}


Output

x = 10, y = 20

 



Previous Article
Next Article

Similar Reads

Java - Exception Handling With Constructors in Inheritance
Java provides a mechanism to handle exceptions. To learn about exception handling, you can refer to exceptions in java. In this article, we discuss exception handling with constructors when inheritance is involved. In Java, if the constructor of the parent class throws any checked exception, then the child class constructor can throw the same excep
7 min read
What are Java Records and How to Use them Alongside Constructors and Methods?
As developers and software engineers, our aim is to always design ways to obtain maximum efficiency and if we need to write less code for it, then that's a blessing. In Java, a record is a special type of class declaration aimed at reducing the boilerplate code. Java records were introduced with the intention to be used as a fast way to create data
11 min read
Generic Constructors and Interfaces in Java
Generics make a class, interface and, method, consider all (reference) types that are given dynamically as parameters. This ensures type safety. Generic class parameters are specified in angle brackets “<>” after the class name as of the instance variable. Generic constructors are the same as generic methods. For generic constructors after th
5 min read
Private Constructors and Singleton Classes in Java
Let's first analyze the following question: Can we have private constructors ? As you can easily guess, like any method we can provide access specifier to the constructor. If it's made private, then it can only be accessed inside the class. Do we need such 'private constructors ' ? There are various scenarios where we can use private constructors.
2 min read
Order of execution of Initialization blocks and Constructors in Java
Prerequisite : Static blocks, Initializer block, Constructor In a Java program, operations can be performed on methods, constructors and initialization blocks. Instance Initialization Blocks : IIB are used to initialize instance variables. IIBs are executed before constructors. They run each time when object of the class is created. Initializer blo
4 min read
Properties of Constructors in Java
A constructors in Java is a special method that is used to initialize objects. The constructor is called when an object of a class is created. It can be used to set initial values for object attributes. In Java, a constructor is a block of codes similar to the method. It is called when an instance of the class is created. At the time of calling the
3 min read
Why Constructors are not inherited in Java?
Constructor is a block of code that allows you to create an object of class and has same name as class with no explicit return type. Whenever a class (child class) extends another class (parent class), the sub class inherits state and behavior in the form of variables and methods from its super class but it does not inherit constructor of super cla
2 min read
Java Constructors
Java constructors or constructors in Java is a terminology used to construct something in our programs. A constructor in Java is a special method that is used to initialize objects. The constructor is called when an object of a class is created. It can be used to set initial values for object attributes. What are Constructors in Java? In Java, a Co
8 min read
Output of Java Programs | Set 14 (Constructors)
Prerequisite - Java Constructors 1) What is the output of the following program? [GFGTABS] Java class Helper { private int data; private Helper() { data = 5; } } public class Test { public static void main(String[] args) { Helper help = new Helper(); System.out.println(help.data); } } [/GFGTABS]a) Compilation error b) 5 c) Runtime error d) None of
3 min read
Java Interview Questions on Constructors
Constructors are a fundamental concept in Java and a popular topic in Java interviews. They play an essential role in initializing an object’s state when it is created, making them a key part of object-oriented programming. Interviewers often test candidates on their understanding of different types of constructors, such as no-arg constructors, cop
4 min read
Difference between the Constructors and Methods
Java is a pure OOPS concept based programming language. Hence in Java, all the variables, data and the statements must be present in classes. These classes consist of both constructors and methods. Methods and Constructors are different from each other in a lot of ways. Constructors: Constructors are used to initialize the object's state. Like meth
3 min read
Default Constructors in C++
A constructor without any arguments or with the default value for every argument is said to be the Default constructor. A constructor that has zero parameter list or in other sense, a constructor that accepts no arguments is called a zero-argument constructor or default constructor. If default constructor is not defined in the source code by the pr
4 min read
Constructors in C++
Constructor in C++ is a special method that is invoked automatically at the time an object of a class is created. It is used to initialize the data members of new objects generally. The constructor in C++ has the same name as the class or structure. It constructs the values i.e. provides data for the object which is why it is known as a constructor
7 min read
Java and Multiple Inheritance
Multiple Inheritance is a feature of an object-oriented concept, where a class can inherit properties of more than one parent class. The problem occurs when there exist methods with the same signature in both the superclasses and subclass. On calling the method, the compiler cannot determine which class method to be called and even on calling which
6 min read
Difference between Inheritance and Composition in Java
Inheritance: When we want to create a new class and there is already a class that includes some of the code that we want, we can derive our new class from the existing class. In doing this, we can reuse the fields and methods of the existing class without having to write them ourself. A subclass inherits all the members (fields, methods, and nested
3 min read
Difference between Inheritance and Interface in Java
Java is one of the most popular and widely used programming languages. Java has been one of the most popular programming languages for many years. Java is Object Oriented. However, it is not considered as a pure object-oriented as it provides support for primitive data types (like int, char, etc). In this article, we will understand the difference
3 min read
Illustrate Class Loading and Static Blocks in Java Inheritance
Class loading means reading .class file and store corresponding binary data in Method Area. For each .class file, JVM will store corresponding information in Method Area. Now incorporating inheritance in class loading. In java inheritance, JVM will first load and initialize the parent class and then it loads and initialize the child class. Example
3 min read
Interfaces and Inheritance in Java
A class can extend another class and can implement one and more than one Java interface. Also, this topic has a major influence on the concept of Java and Multiple Inheritance. Note: This Hierarchy will be followed in the same way, we cannot reverse the hierarchy while inheritance in Java. This means that we cannot implement a class from the interf
7 min read
Comparison of Inheritance in C++ and Java
The purpose of inheritance is the same in C++ and Java. Inheritance is used in both languages for reusing code and/or creating an ‘is-a’ relationship. The following examples will demonstrate the differences between Java and C++ that provide support for inheritance. 1) In Java, all classes inherit from the Object class directly or indirectly. Theref
4 min read
Java | Inheritance | Question 1
Output of following Java Program? class Base { public void show() { System.out.println("Base::show() called"); } } class Derived extends Base { public void show() { System.out.println("Derived::show() called"); } } public class Main { public static void main(String[] args) { Base b = new Derived();; b.show(); } } (A) Derived::sh
1 min read
Java | Inheritance | Question 2
class Base { final public void show() { System.out.println("Base::show() called"); } } class Derived extends Base { public void show() { System.out.println("Derived::show() called"); } } class Main { public static void main(String[] args) { Base b = new Derived();; b.show(); } } (A) Base::show() called (B) Derived::show() called
1 min read
Java | Inheritance | Question 3
Java Code class Base { public static void show() { System.out.println("Base::show() called"); } } class Derived extends Base { public static void show() { System.out.println("Derived::show() called"); } } class Main { public static void main(String[] args) { Base b = new Derived(); b.show(); } } (A) Base::show() called (B) Deriv
1 min read
Java | Inheritance | Question 4
Which of the following is true about inheritance in Java? 1) Private methods are final. 2) Protected members are accessible within a package and inherited classes outside the package. 3) Protected methods are final. 4) We cannot override private methods. (A) 1, 2 and 4 (B) Only 1 and 2 (C) 1, 2 and 3 (D) 2, 3 and 4 Answer: (A) Explanation: See http
1 min read
Java | Inheritance | Question 5
Output of following Java program? class Base { public void Print() { System.out.println("Base"); } } class Derived extends Base { public void Print() { System.out.println("Derived"); } } class Main{ public static void DoPrint( Base o ) { o.Print(); } public static void main(String[] args) { Base x = new Base(); Base y = new Deri
1 min read
Java | Inheritance | Question 9
Predict the output of following program. Note that foo() is public in base and private in derived. class Base { public void foo() { System.out.println("Base"); } } class Derived extends Base { private void foo() { System.out.println("Derived"); } } public class Main { public static void main(String args[]) { Base b = new Derived
1 min read
Java | Inheritance | Question 7
Which of the following is true about inheritance in Java. 1) In Java all classes inherit from the Object class directly or indirectly. The Object class is root of all classes. 2) Multiple inheritance is not allowed in Java. 3) Unlike C++, there is nothing like type of inheritance in Java where we can specify whether the inheritance is protected, pu
1 min read
Java | Inheritance | Question 8
Predict the output of following Java Program // filename Main.java class Grandparent { public void Print() { System.out.println("Grandparent's Print()"); } } class Parent extends Grandparent { public void Print() { System.out.println("Parent's Print()"); } } class Child extends Parent { public void Print() { super.super.Print();
1 min read
Java | Inheritance | Question 9
final class Complex { private final double re; private final double im; public Complex(double re, double im) { this.re = re; this.im = im; } public String toString() { return "(" + re + " + " + im + "i)"; } } class Main { public static void main(String args[]) { Complex c = new Complex(10, 15); System.out.println(
1 min read
Output of Java program | Set 23 (Inheritance)
Prerequisite: Inheritance in Java 1) What is the output of the following program? Java Code public class A extends B { public static String sing() { return "fa"; } public static void main(String[] args) { A a = new A(); B b = new A(); System.out.println(a.sing() + " " + b.sing()); } } class B { public static String sing() { retu
3 min read
Resolving Conflicts During Multiple Inheritance in Java
A class can implement multiple interfaces in java, but what if the implemented multiple default interfaces have default methods with the same signatures? Then in the implementing class, which of the default implementations would be invoked from the several parent interfaces. Java 8 designers have been thinking about this conflict and have specified
5 min read
Practice Tags :
three90RightbarBannerImg