Use constructor overload from within class constructor [duplicate] - java
Is it possible to call a constructor from another (within the same class, not from a subclass)? If yes how? And what could be the best way to call another constructor (if there are several ways to do it)?
Yes, it is possible:
public class Foo {
private int x;
public Foo() {
this(1);
}
public Foo(int x) {
this.x = x;
}
}
To chain to a particular superclass constructor instead of one in the same class, use super instead of this. Note that you can only chain to one constructor, and it has to be the first statement in your constructor body.
See also this related question, which is about C# but where the same principles apply.
Using this(args). The preferred pattern is to work from the smallest constructor to the largest.
public class Cons {
public Cons() {
// A no arguments constructor that sends default values to the largest
this(madeUpArg1Value,madeUpArg2Value,madeUpArg3Value);
}
public Cons(int arg1, int arg2) {
// An example of a partial constructor that uses the passed in arguments
// and sends a hidden default value to the largest
this(arg1,arg2, madeUpArg3Value);
}
// Largest constructor that does the work
public Cons(int arg1, int arg2, int arg3) {
this.arg1 = arg1;
this.arg2 = arg2;
this.arg3 = arg3;
}
}
You can also use a more recently advocated approach of valueOf or just "of":
public class Cons {
public static Cons newCons(int arg1,...) {
// This function is commonly called valueOf, like Integer.valueOf(..)
// More recently called "of", like EnumSet.of(..)
Cons c = new Cons(...);
c.setArg1(....);
return c;
}
}
To call a super class, use super(someValue). The call to super must be the first call in the constructor or you will get a compiler error.
[Note: I just want to add one aspect, which I did not see in the other answers: how to overcome limitations of the requirement that this() has to be on the first line).]
In Java another constructor of the same class can be called from a constructor via this(). Note however that this has to be on the first line.
public class MyClass {
public MyClass(double argument1, double argument2) {
this(argument1, argument2, 0.0);
}
public MyClass(double argument1, double argument2, double argument3) {
this.argument1 = argument1;
this.argument2 = argument2;
this.argument3 = argument3;
}
}
That this has to appear on the first line looks like a big limitation, but you can construct the arguments of other constructors via static methods. For example:
public class MyClass {
public MyClass(double argument1, double argument2) {
this(argument1, argument2, getDefaultArg3(argument1, argument2));
}
public MyClass(double argument1, double argument2, double argument3) {
this.argument1 = argument1;
this.argument2 = argument2;
this.argument3 = argument3;
}
private static double getDefaultArg3(double argument1, double argument2) {
double argument3 = 0;
// Calculate argument3 here if you like.
return argument3;
}
}
When I need to call another constructor from inside the code (not on the first line), I usually use a helper method like this:
class MyClass {
int field;
MyClass() {
init(0);
}
MyClass(int value) {
if (value<0) {
init(0);
}
else {
init(value);
}
}
void init(int x) {
field = x;
}
}
But most often I try to do it the other way around by calling the more complex constructors from the simpler ones on the first line, to the extent possible. For the above example
class MyClass {
int field;
MyClass(int value) {
if (value<0)
field = 0;
else
field = value;
}
MyClass() {
this(0);
}
}
Within a constructor, you can use the this keyword to invoke another constructor in the same class. Doing so is called an explicit constructor invocation.
Here's another Rectangle class, with a different implementation from the one in the Objects section.
public class Rectangle {
private int x, y;
private int width, height;
public Rectangle() {
this(1, 1);
}
public Rectangle(int width, int height) {
this( 0,0,width, height);
}
public Rectangle(int x, int y, int width, int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
}
This class contains a set of constructors. Each constructor initializes some or all of the rectangle's member variables.
As everybody already have said, you use this(…), which is called an explicit constructor invocation.
However, keep in mind that within such an explicit constructor invocation statement you may not refer to
any instance variables or
any instance methods or
any inner classes declared in this class or any superclass, or
this or
super.
As stated in JLS (§8.8.7.1).
Yes, any number of constructors can be present in a class and they can be called by another constructor using this() [Please do not confuse this() constructor call with this keyword]. this() or this(args) should be the first line in the constructor.
Example:
Class Test {
Test() {
this(10); // calls the constructor with integer args, Test(int a)
}
Test(int a) {
this(10.5); // call the constructor with double arg, Test(double a)
}
Test(double a) {
System.out.println("I am a double arg constructor");
}
}
This is known as constructor overloading.
Please note that for constructor, only overloading concept is applicable and not inheritance or overriding.
Using this keyword we can call one constructor in another constructor within same class.
Example :-
public class Example {
private String name;
public Example() {
this("Mahesh");
}
public Example(String name) {
this.name = name;
}
}
Yes it is possible to call one constructor from another. But there is a rule to it. If a call is made from one constructor to another, then
that new constructor call must be the first statement in the current constructor
public class Product {
private int productId;
private String productName;
private double productPrice;
private String category;
public Product(int id, String name) {
this(id,name,1.0);
}
public Product(int id, String name, double price) {
this(id,name,price,"DEFAULT");
}
public Product(int id,String name,double price, String category){
this.productId=id;
this.productName=name;
this.productPrice=price;
this.category=category;
}
}
So, something like below will not work.
public Product(int id, String name, double price) {
System.out.println("Calling constructor with price");
this(id,name,price,"DEFAULT");
}
Also, in the case of inheritance, when sub-class's object is created, the super class constructor is first called.
public class SuperClass {
public SuperClass() {
System.out.println("Inside super class constructor");
}
}
public class SubClass extends SuperClass {
public SubClass () {
//Even if we do not add, Java adds the call to super class's constructor like
// super();
System.out.println("Inside sub class constructor");
}
}
Thus, in this case also another constructor call is first declared before any other statements.
I will tell you an easy way
There are two types of constructors:
Default constructor
Parameterized constructor
I will explain in one Example
class ConstructorDemo
{
ConstructorDemo()//Default Constructor
{
System.out.println("D.constructor ");
}
ConstructorDemo(int k)//Parameterized constructor
{
this();//-------------(1)
System.out.println("P.Constructor ="+k);
}
public static void main(String[] args)
{
//this(); error because "must be first statement in constructor
new ConstructorDemo();//-------(2)
ConstructorDemo g=new ConstructorDemo(3);---(3)
}
}
In the above example I showed 3 types of calling
this() call to this must be first statement in constructor
This is Name less Object. this automatically calls the default constructor.
3.This calls the Parameterized constructor.
Note:
this must be the first statement in the constructor.
You can a constructor from another constructor of same class by using "this" keyword.
Example -
class This1
{
This1()
{
this("Hello");
System.out.println("Default constructor..");
}
This1(int a)
{
this();
System.out.println("int as arg constructor..");
}
This1(String s)
{
System.out.println("string as arg constructor..");
}
public static void main(String args[])
{
new This1(100);
}
}
Output -
string as arg constructor..
Default constructor..
int as arg constructor..
Calling constructor from another constructor
class MyConstructorDemo extends ConstructorDemo
{
MyConstructorDemo()
{
this("calling another constructor");
}
MyConstructorDemo(String arg)
{
System.out.print("This is passed String by another constructor :"+arg);
}
}
Also you can call parent constructor by using super() call
There are design patterns that cover the need for complex construction - if it can't be done succinctly, create a factory method or a factory class.
With the latest java and the addition of lambdas, it is easy to create a constructor which can accept any initialization code you desire.
class LambdaInitedClass {
public LamdaInitedClass(Consumer<LambdaInitedClass> init) {
init.accept(this);
}
}
Call it with...
new LambdaInitedClass(l -> { // init l any way you want });
Pretty simple
public class SomeClass{
private int number;
private String someString;
public SomeClass(){
number = 0;
someString = new String();
}
public SomeClass(int number){
this(); //set the class to 0
this.setNumber(number);
}
public SomeClass(int number, String someString){
this(number); //call public SomeClass( int number )
this.setString(someString);
}
public void setNumber(int number){
this.number = number;
}
public void setString(String someString){
this.someString = someString;
}
//.... add some accessors
}
now here is some small extra credit:
public SomeOtherClass extends SomeClass {
public SomeOtherClass(int number, String someString){
super(number, someString); //calls public SomeClass(int number, String someString)
}
//.... Some other code.
}
Hope this helps.
Yes it is possible to call one constructor from another with use of this()
class Example{
private int a = 1;
Example(){
this(5); //here another constructor called based on constructor argument
System.out.println("number a is "+a);
}
Example(int b){
System.out.println("number b is "+b);
}
You can call another constructor via the this(...) keyword (when you need to call a constructor from the same class) or the super(...) keyword
(when you need to call a constructor from a superclass).
However, such a call must be the first statement of your constructor. To overcome this limitation, use this answer.
The keyword this can be used to call a constructor from a constructor, when writing several constructor for a class, there are times when you'd like to call one constructor from another to avoid duplicate code.
Bellow is a link that I explain other topic about constructor and getters() and setters() and I used a class with two constructors. I hope the explanations and examples help you.
Setter methods or constructors
I know there are so many examples of this question but what I found I am putting here to share my Idea. there are two ways to chain constructor. In Same class you can use this keyword. in Inheritance, you need to use super keyword.
import java.util.*;
import java.lang.*;
class Test
{
public static void main(String args[])
{
Dog d = new Dog(); // Both Calling Same Constructor of Parent Class i.e. 0 args Constructor.
Dog cs = new Dog("Bite"); // Both Calling Same Constructor of Parent Class i.e. 0 args Constructor.
// You need to Explicitly tell the java compiler to use Argument constructor so you need to use "super" key word
System.out.println("------------------------------");
Cat c = new Cat();
Cat caty = new Cat("10");
System.out.println("------------------------------");
// Self s = new Self();
Self ss = new Self("self");
}
}
class Animal
{
String i;
public Animal()
{
i = "10";
System.out.println("Animal Constructor :" +i);
}
public Animal(String h)
{
i = "20";
System.out.println("Animal Constructor Habit :"+ i);
}
}
class Dog extends Animal
{
public Dog()
{
System.out.println("Dog Constructor");
}
public Dog(String h)
{
System.out.println("Dog Constructor with habit");
}
}
class Cat extends Animal
{
public Cat()
{
System.out.println("Cat Constructor");
}
public Cat(String i)
{
super(i); // Calling Super Class Paremetrize Constructor.
System.out.println("Cat Constructor with habit");
}
}
class Self
{
public Self()
{
System.out.println("Self Constructor");
}
public Self(String h)
{
this(); // Explicitly calling 0 args constructor.
System.out.println("Slef Constructor with value");
}
}
It is called Telescoping Constructor anti-pattern or constructor chaining. Yes, you can definitely do. I see many examples above and I want to add by saying that if you know that you need only two or three constructor, it might be ok. But if you need more, please try to use different design pattern like Builder pattern. As for example:
public Omar(){};
public Omar(a){};
public Omar(a,b){};
public Omar(a,b,c){};
public Omar(a,b,c,d){};
...
You may need more. Builder pattern would be a great solution in this case. Here is an article, it might be helpful
https://medium.com/#modestofiguereo/design-patterns-2-the-builder-pattern-and-the-telescoping-constructor-anti-pattern-60a33de7522e
Yes, you can call constructors from another constructor. For example:
public class Animal {
private int animalType;
public Animal() {
this(1); //here this(1) internally make call to Animal(1);
}
public Animal(int animalType) {
this.animalType = animalType;
}
}
you can also read in details from
Constructor Chaining in Java
Originally from an anser by Mirko Klemm, slightly modified to address the question:
Just for completeness: There is also the Instance initialization block that gets executed always and before any other constructor is called. It consists simply of a block of statements "{ ... }" somewhere in the body of your class definition. You can even have more than one. You can't call them, but they're like "shared constructor" code if you want to reuse some code across constructors, similar to calling methods.
So in your case
{
System.out.println("this is shared constructor code executed before the constructor");
field1 = 3;
}
There is also a "static" version of this to initialize static members: "static { ... }"
I prefer this way:
class User {
private long id;
private String username;
private int imageRes;
public User() {
init(defaultID,defaultUsername,defaultRes);
}
public User(String username) {
init(defaultID,username, defaultRes());
}
public User(String username, int imageRes) {
init(defaultID,username, imageRes);
}
public User(long id, String username, int imageRes) {
init(id,username, imageRes);
}
private void init(long id, String username, int imageRes) {
this.id=id;
this.username = username;
this.imageRes = imageRes;
}
}
Related
Prevent super-constructor instantiation if a subclass constructor parameter is illegal
Is it possible to prevent the instantiation of super constructor if a parameter of subclass constructor is illegal? I know that super should be the first instruction in the subclass constructor, but what happens if I throw an exception? Is the "super" object created anyway? Example: The subclass must not create the object if y < 10. But if super comes before Y's control, is an object still created? public class SuperClass(){ public SuperClass(String x) { ... } } public class SubClass extends SuperClass{ private int subY; public SubClass(int y){ super(); if(y<10){ this.subY = y; }else{ throw new IllegalArgumentException("Error: y must be <10"); } } } I read this, but it is not the case of a subclass Preventing instantiation of a class if argument to constructor is illegal?
One option is to use a factory method, which lets you do something and then have the constructor run: public class subClass extends mySuperClass { private subClass(int y) { // <-- Note: Now private super(/* ... args ... */); this.y = y; } public static subClass create(int y) { if (y >= 10) { throw new IllegalArgumentException("Shame! Shame!"); } return new subClass(y); } } Now, you'd create objects by writing subClass.create(arg); rather than new subClass(arg); A second option would be to replace the int parameter with a parameter of a custom type representing what you want. This gives more fine-grained control and makes clear that the argument isn't an int per se, but rather some sort of limited value. public class subClass extends mySuperClass { public static final class SpecialInt { private final int value; SpecialInt(int val) { if (val < 10) { throw new IllegalArgumentException("That int is Not Special."); } value = val; } } public subClass(SpecialInt y) { super(/* ... args ... */); this.y = y.value; } } I like this option because it makes clear that there's a restricted type of items that can be given to the constructor, though it does add a bit more syntax (new subClass(new subClass.SpecialInt(137)) versus newSubclass(137)). A final, hacky, "not great but it'll work" option would be to add in static method that checks the argument to the subclass constructor and, in the normal case, returns the proper argument to the superclass constructor. However, if the argument is invalid, the helper throws an exception. This assumes that the superclass constructor takes at least one argument and won't work otherwise. public class subClass extends mySuperClass { private static final String argCheck(int y) { if (y >= 10) { throw new IllegalArgumentException("You have committed a Programming Sin."); } return /* whatever you would normally send to the superclass. */; } public subClass(int y) { super(argCheck(y)); // Check y before invoking the superclass ctor this.y = y; } }
Beginner Q: optional arguments in Java
I'm totally new to Java, as in, I started yesterday. I've got a class that I'd like to have two constructors for: one without arguments, and one with. Supposedly this should be simple: overload the constructor by writing two methods: public class sortList { public int ncell, npart, cell_n, index, Xref; // constructor(s): public void sortList() { initLists( 1, 1 ); } public void sortList( int ncell_in, int npart_in ) { initLists( ncell_in, npart_in ); } private void initLists( int ncell_in, int npart_in ) { /* DO STUFF */ } } When I call this from my main() though: sortList mySL = new sortList( 5, 6 ); ... java complains: myDSMC.java:5: error: constructor sortList in class sortList cannot be applied to given types; sortList mySL = new sortList( 5, 6 ); ^ required: no arguments found: int,int reason: actual and formal argument lists differ in length 1 error (For the curious, I am just translating a super-simple DSMC code from C++...). What silly thing am I missing? Thanks. -Peter
This are not constructors, they are regular methods : public void sortList() {...} public void sortList( int ncell_in, int npart_in ) {...} Change them to constructors by removing the return type : public sortList() {...} public sortList( int ncell_in, int npart_in ) {...} Since you didn't declare any constructors in your sortList class (you just declared two regular methods having the same name as the class), only the default parameter-less constructor was available.
Constructors in Java have no return type and have name the same as the name of the class. The all methods in java have return type (void - if nothing to return). You don't have to provide any constructors for your class, but you must be careful when doing this. The compiler automatically provides a no-argument, default constructor for any class without constructors. This default constructor will call the no-argument constructor of the superclass. In this situation, the compiler will complain if the superclass doesn't have a no-argument constructor so you must verify that it does. If your class has no explicit superclass, then it has an implicit superclass of Object, which does have a no-argument constructor. Example of constructor and methods: // for this class default no-args constructor implicitly created public class Test1 { int id; // regular method public int getId() { return id; } // regular method public int test1() { return 1; } } public class Test2 { int id; // no-args constructor public Test2() { } // overloaded constructor public Test2(int id) { this.id = id; } // regular method public int getId() { return id; } // regular method public void test2() { System.out.println("1"); } } All defined constructors implicitly call super();. So Test2 constructor actually looks like this: public Test2(int id) { super(); this.id = id; }
Initialising Variables in java
How would I initialise the string name and the instance variable named right in the superclass to true from the HighRights class? So if high is an instance of HighRights then high.getSecret(); should return the secret is 42 public class SecurityRights { private boolean right; private boolean canreadSecret; String SECRET="the secret is 42"; public SecurityRights(boolean r) { right =r; if (r) canreadSecret=true; else canreadSecret=false; } boolean getRight(){ return right; } boolean canReadSecret(){ return canreadSecret; } String getSecret(){ if (canreadSecret) return SECRET; else return "access denied"; } } public class HighRights extends SecurityRights { private String name; public HighRights(String n){ } public String getName(){ return name; } public static void main(String[] a){ HighRights s= new HighRights("Lisa"); System.out.print(s.getName() +" "+s.getSecret()); } }
You call the Parent's constructor by calling super(). So in your case super(booleanValue); Usually, this would be placed in the first line of your child constructor. You could also change the privacy level from private to protected, and then you would be able to access it in all child objects.
You can either make a method just like you did when calling getSecret() and intialize and boolean and string. OR you can use the super methods. Here is some more info. You would pretty much be making a constructor for the class, but since an instance of the class is never really created only a Child of that instance, you need to use the super command to make constructors.
The inherited class would have the following implementation:- class HighRights extends SecurityRights { private String name; public HighRights(boolean r,String n){ super(r); this.name = n; } public String getName(){ return name; } public static void main(String[] a){ HighRights s= new HighRights(false,"Lisa"); System.out.print(s.getName() +" "+s.getSecret()); } } In this implementation, the super keyword is used. super keyword is used when you need to call the superclass's constructor from the constructor of the subclass. Since you needed to access the right variable of SecurityRights from the constructor of HighRights, you could access it by using the super keyword. More information can be found at oracle's manual. Also, you gave an argument in the constructor of SecurityRights but you didn't assign it to any variable. Please avoid these mistakes.
Inheriting java constructors
I have a super class 'BuildingMaterial' and loads of subclasses, i.e. Stone, Wood, Clay, etc. All subclasses behave similarly: 1 int field that stores the amount of a building material in units. They can be constructed parameterless or with an int. I already know that ALL subclasses of BuildingMaterial will have these two constructors, how do I avoid coding them into every single class? Here's an example of what I don't want to do in every class: public final class Stone extends BuildingMaterial { private int amount; //constructors public Stone() { amount = 0; } public Stone(int i) { amount = i; } //methods public int getAmount() { return amount; } }
Sadly, the answer is you can't. This is a limitation of the Java language. Each class needs its own constructors—you can't simply inherit them from a parent class. The only constructor the Java compiler will generate for you is the default constructor (no arguments), and it only generates that if you don't specify any constructors at all. The best you can do here is to refactor your code so amount is in the superclass: public abstract class BuildingMaterial { private int amount; //constructors public BuildingMaterial() { this(0); } public BuildingMaterial(int i) { amount = i; } //methods public int getAmount() { return amount; } } And then make use of super calls to delegate the superclass's constructor in your subclasses: public final class Stone extends BuildingMaterial { //constructors public Stone() { super(); } public Stone(int i) { super(i); } } Note that I changed the body of your no-argument constructor from amount=0; to this(0);. I personally think this is better style because, if you decide to add other initialization code to your constructor body, you only have to add it to the 1-argument constructor, and the zero-argument constructor will just delegate all the work to it.
You have to use inheritance public abstract class BuildingMaterial { private int amount; //constructors public BuildingMaterial() { amount = 0; } public BuildingMaterial(int i) { amount = i; } //methods public int getAmount() { return amount; } } public class Stone extends BuildingMaterial { public Stone() { super(); } public Stone(int i) { super(i); } } This way all subclasses of BuildingMaterial can give access to amount through getters and setters. You may have amount declared as protected so you wont need getters or setters to access that field inside subclasses.
use super keyword to reduce your code but the super is to be the first line inside the constructor public class Stone extends BuildingMaterial { public Stone() { super(); } public Stone(int i) { super(i); } }
If all classes has the attribute amount, then that attribute can be inherited from parent. Define amount in your parent class BuildingMaterial and then call the parent constructor from your child classes constructors using super to set the amount value.
Its unclear what you want to avoid in your question... assuming you are talking about avoiding writing multiple constructors in all the subclass. I believe its not possible to do so. below post of defining BuildingMeterial constructor and calling the super() from baseClass will be the best solution to use.
super() in Java
Is super() used to call the parent constructor? Please explain super().
super() calls the parent constructor with no arguments. It can be used also with arguments. I.e. super(argument1) and it will call the constructor that accepts 1 parameter of the type of argument1 (if exists). Also it can be used to call methods from the parent. I.e. super.aMethod() More info and tutorial here
Some facts: super() is used to call the immediate parent. super() can be used with instance members, i.e., instance variables and instance methods. super() can be used within a constructor to call the constructor of the parent class. OK, now let’s practically implement these points of super(). Check out the difference between program 1 and 2. Here, program 2 proofs our first statement of super() in Java. Program 1 class Base { int a = 100; } class Sup1 extends Base { int a = 200; void Show() { System.out.println(a); System.out.println(a); } public static void main(String[] args) { new Sup1().Show(); } } Output: 200 200 Now check out program 2 and try to figure out the main difference. Program 2 class Base { int a = 100; } class Sup2 extends Base { int a = 200; void Show() { System.out.println(super.a); System.out.println(a); } public static void main(String[] args) { new Sup2().Show(); } } Output: 100 200 In program 1, the output was only of the derived class. It couldn't print the variable of neither the base class nor the parent class. But in program 2, we used super() with variable a while printing its output, and instead of printing the value of variable a of the derived class, it printed the value of variable a of the base class. So it proves that super() is used to call the immediate parent. OK, now check out the difference between program 3 and program 4. Program 3 class Base { int a = 100; void Show() { System.out.println(a); } } class Sup3 extends Base { int a = 200; void Show() { System.out.println(a); } public static void Main(String[] args) { new Sup3().Show(); } } Output: 200 Here the output is 200. When we called Show(), the Show() function of the derived class was called. But what should we do if we want to call the Show() function of the parent class? Check out program 4 for the solution. Program 4 class Base { int a = 100; void Show() { System.out.println(a); } } class Sup4 extends Base { int a = 200; void Show() { super.Show(); System.out.println(a); } public static void Main(String[] args) { new Sup4().Show(); } } Output: 100 200 Here we are getting two outputs, 100 and 200. When the Show() function of the derived class is invoked, it first calls the Show() function of the parent class, because inside the Show() function of the derived class, we called the Show() function of the parent class by putting the super keyword before the function name.
Source article: Java: Calling super() Yes. super(...) will invoke the constructor of the super-class. Illustration: Stand alone example: class Animal { public Animal(String arg) { System.out.println("Constructing an animal: " + arg); } } class Dog extends Animal { public Dog() { super("From Dog constructor"); System.out.println("Constructing a dog."); } } public class Test { public static void main(String[] a) { new Dog(); } } Prints: Constructing an animal: From Dog constructor Constructing a dog.
Is super() is used to call the parent constructor? Yes. Pls explain about Super(). super() is a special use of the super keyword where you call a parameterless parent constructor. In general, the super keyword can be used to call overridden methods, access hidden fields or invoke a superclass's constructor. Here's the official tutorial
Calling the no-arguments super constructor is just a waste of screen space and programmer time. The compiler generates exactly the same code, whether you write it or not. class Explicit() { Explicit() { super(); } } class Implicit { Implicit() { } }
Yes, super() (lowercase) calls a constructor of the parent class. You can include arguments: super(foo, bar) There is also a super keyword, that you can use in methods to invoke a method of the superclass A quick google for "Java super" results in this
That is correct. Super is used to call the parent constructor. So suppose you have a code block like so class A{ int n; public A(int x){ n = x; } } class B extends A{ int m; public B(int x, int y){ super(x); m = y; } } Then you can assign a value to the member variable n.
I have seen all the answers. But everyone forgot to mention one very important point: super() should be called or used in the first line of the constructor.
Just super(); alone will call the default constructor, if it exists of a class's superclass. But you must explicitly write the default constructor yourself. If you don't a Java will generate one for you with no implementations, save super(); , referring to the universal Superclass Object, and you can't call it in a subclass. public class Alien{ public Alien(){ //Default constructor is written out by user /** Implementation not shown…**/ } } public class WeirdAlien extends Alien{ public WeirdAlien(){ super(); //calls the default constructor in Alien. } }
For example, in selenium automation, you have a PageObject which can use its parent's constructor like this: public class DeveloperSteps extends ScenarioSteps { public DeveloperSteps(Pages pages) { super(pages); }........
I would like to share with codes whatever I understood. The super keyword in java is a reference variable that is used to refer parent class objects. It is majorly used in the following contexts:- 1. Use of super with variables: class Vehicle { int maxSpeed = 120; } /* sub class Car extending vehicle */ class Car extends Vehicle { int maxSpeed = 180; void display() { /* print maxSpeed of base class (vehicle) */ System.out.println("Maximum Speed: " + super.maxSpeed); } } /* Driver program to test */ class Test { public static void main(String[] args) { Car small = new Car(); small.display(); } } Output:- Maximum Speed: 120 Use of super with methods: /* Base class Person */ class Person { void message() { System.out.println("This is person class"); } } /* Subclass Student */ class Student extends Person { void message() { System.out.println("This is student class"); } // Note that display() is only in Student class void display() { // will invoke or call current class message() method message(); // will invoke or call parent class message() method super.message(); } } /* Driver program to test */ class Test { public static void main(String args[]) { Student s = new Student(); // calling display() of Student s.display(); } } Output:- This is student class This is person class 3. Use of super with constructors: class Person { Person() { System.out.println("Person class Constructor"); } } /* subclass Student extending the Person class */ class Student extends Person { Student() { // invoke or call parent class constructor super(); System.out.println("Student class Constructor"); } } /* Driver program to test*/ class Test { public static void main(String[] args) { Student s = new Student(); } } Output:- Person class Constructor Student class Constructor
What can we use SUPER for? Accessing Superclass Members If your method overrides some of its superclass's methods, you can invoke the overridden method through the use of the keyword super like super.methodName(); Invoking Superclass Constructors If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass. If the super class does not have a no-argument constructor, you will get a compile-time error. Look at the code below: class Creature { public Creature() { system.out.println("Creature non argument constructor."); } } class Animal extends Creature { public Animal (String name) { System.out.println("Animal one argument constructor"); } public Animal (Stirng name,int age) { this(name); system.out.println("Animal two arguments constructor"); } } class Wolf extends Animal { public Wolf() { super("tigerwang",33); system.out.println("Wolf non argument constructor"); } public static void main(string[] args) { new Wolf(); } } When creating an object,the JVM always first execute the constructor in the class of the top layer in the inheritance tree.And then all the way down the inheritance tree.The reason why this is possible to happen is that the Java compiler automatically inserts a call to the no-argument constructor of the superclass.If there's no non-argument constructor in the superclass and the subclass doesn't explicitly say which of the constructor is to be executed in the superclass,you'll get a compile-time error. In the above code,if we want to create a Wolf object successfully,the constructor of the class has to be executed.And during that process,the two-argu-constructor in the Animal class is invoked.Simultaneously,it explicitly invokes the one-argu-constructor in the same class and the one-argu-constructor implicitly invokes the non-argu-constructor in the Creature class and the non-argu-constructor again implicitly invokes the empty constructor in the Object class.
Constructors In a constructor, you can use it without a dot to call another constructor. super calls a constructor in the superclass; this calls a constructor in this class : public MyClass(int a) { this(a, 5); // Here, I call another one of this class's constructors. } public MyClass(int a, int b) { super(a, b); // Then, I call one of the superclass's constructors. } super is useful if the superclass needs to initialize itself. this is useful to allow you to write all the hard initialization code only once in one of the constructors and to call it from all the other, much easier-to-write constructors. Methods In any method, you can use it with a dot to call another method. super.method() calls a method in the superclass; this.method() calls a method in this class : public String toString() { int hp = this.hitpoints(); // Calls the hitpoints method in this class // for this object. String name = super.name(); // Calls the name method in the superclass // for this object. return "[" + name + ": " + hp + " HP]"; } super is useful in a certain scenario: if your class has the same method as your superclass, Java will assume you want the one in your class; super allows you to ask for the superclass's method instead. this is useful only as a way to make your code more readable.
The super keyword can be used to call the superclass constructor and to refer to a member of the superclass When you call super() with the right arguments, we actually call the constructor Box, which initializes variables width, height and depth, referred to it by using the values of the corresponding parameters. You only remains to initialize its value added weight. If necessary, you can do now class variables Box as private. Put down in the fields of the Box class private modifier and make sure that you can access them without any problems. At the superclass can be several overloaded versions constructors, so you can call the method super() with different parameters. The program will perform the constructor that matches the specified arguments. public class Box { int width; int height; int depth; Box(int w, int h, int d) { width = w; height = h; depth = d; } public static void main(String[] args){ HeavyBox heavy = new HeavyBox(12, 32, 23, 13); } } class HeavyBox extends Box { int weight; HeavyBox(int w, int h, int d, int m) { //call the superclass constructor super(w, h, d); weight = m; } }
super is a keyword. It is used inside a sub-class method definition to call a method defined in the superclass. Private methods of the superclass cannot be called. Only public and protected methods can be called by the super keyword. It is also used by class constructors to invoke constructors of its parent class. Check here for further explanation.
As stated, inside the default constructor there is an implicit super() called on the first line of the constructor. This super() automatically calls a chain of constructors starting at the top of the class hierarchy and moves down the hierarchy . If there were more than two classes in the class hierarchy of the program, the top class default constructor would get called first. Here is an example of this: class A { A() { System.out.println("Constructor A"); } } class B extends A{ public B() { System.out.println("Constructor B"); } } class C extends B{ public C() { System.out.println("Constructor C"); } public static void main(String[] args) { C c1 = new C(); } } The above would output: Constructor A Constructor B Constructor C
The super keyword in Java is a reference variable that is used to refer to the immediate parent class object. Usage of Java super Keyword super can be used to refer to the immediate parent class instance variable. super can be used to invoke the immediate parent class method. super() can be used to invoke immediate parent class constructor.
There are a couple of other uses. Referencing a default method of an inherited interface: import java.util.Collection; import java.util.stream.Stream; public interface SkipFirstCollection<E> extends Collection<E> { #Override default Stream<E> stream() { return Collection.super.stream().skip(1); } } There is also a rarely used case where a qualified super is used to provide an outer instance to the superclass constructor when instantiating a static subclass: public class OuterInstance { public static class ClassA { final String name; public ClassA(String name) { this.name = name; } public class ClassB { public String getAName() { return ClassA.this.name; } } } public static class ClassC extends ClassA.ClassB { public ClassC(ClassA a) { a.super(); } } public static void main(String[] args) { final ClassA a = new ClassA("jeff"); final ClassC c = new ClassC(a); System.out.println(c.getAName()); } } Then: $ javac OuterInstance.java && java OuterInstance jeff