Constructor usages in Java - java

Can anybody explain the differences between these constructors. See this;
public MyClass() {
}
and
public MyClass() {
this();
}
and
public MyClass() {
super();
}

Second is not allowed to be declared in java because you are making recursive call to default constructor only. Also by default constructor has always super() method which is inserted by compiler if not specified explicitly.

public MyClass() { }
declares an empty no-arg constructor. If you declare no constructor for a class, the compiler effectively inserts this conrtsuctor for the class.
public MyClass() { this(); }
will not compile.
public MyClass() { super(); }
is a constructor which invokes the default constructor of the super-class. This will compile only if the super-class has a default constructor, or no constructor (in which case, the compiler inserts a default constructor anyways, as mentioned above). Also, leaving out the super(); call has the same effect.

I think that in the second case you probably meant to write:
public MyClass() {
super(); // not "this();"
}
Either way, your second case is a compilation error. The JLS says this:
"It is a compile-time error for a constructor to directly or indirectly invoke itself through a series of one or more explicit constructor invocations involving this." JLS 8.8.7
In your example, this() is an explicit constructor invocation that directly invokes the same constructor.
Finally, there is no semantic difference between the first and third forms. The first form has an implicit invocation of the no-args constructor of the superclass, and the third for just makes that invocation explicit.
Some people prefer to write the form with an explicit invocation for the sake of readability, but IMO it doesn't really make any difference.

It is very simple
Let me make you understand
first
public MyClass() { }
is simply a default public constructor
But when you write this
public MyClass() { this(); }
that means you are applying constructor chaining. Constructor Chaining is simply calling another constructor of the same class. This must be the first statement of the Constructor. But in your scenario you are passing nothing in this(); that means you are again calling the same constructor which will result in infinite loop. your class may have another constructor like this
public MyClass(int a) { }
then you may have called this
public MyClass(){ this(10); }
the above statement will make you to jump to the constructor receiving the same arguments that you have passed
Now,
public Myclass(){ super(); }
signifies that you are calling the constructor of the super class which is inherited by the class MyClass. the same scenario occurs here, you have passed nothing in the super(); which will call the default constructor of the Super class.

Lets look at the three type of constructor calls one by one.Each one has special purpose associated with them. But the concept is simple and very interesting to explore.
Case 1 :- This is default constructor with no arguments
public class MyClass{
public MyClass(){
}
}
The compiler will automatically supply a no-argument constructor for you if you do not write one.Thus if you write public class MyClass{ } .
This is equivalent to writing
public class MyClass{
MyClass(){ }
}
Points to be noted :-
Compiler automatically provide "super" when you do not use super "as the first line of the constructor". NOTE:- For "super" and "this" when you use in constructors always write them in the first line of your constructor code otherwise compiler will give error.
Even when you do not extend MyClass here compiler will give call to constructor to super Object class which is the root class of every class you create.
Case 2:- The use of "this".
Constructors use "this" to refer to another constructor in the same class with a different parameter list.
public MyClass() {
this();
}
So the above code will give compilation error "Recursive Constructor Invocation" as it is calling the same constructor and will end up in an infinite loop. To make this work you can instead write
public MyClass(String str){
System.out.println("constructor with arg "+ str);
}
public MyClass(){
this("Cons"); // note that "this" has to be at first line otherwise compiler gives error
System.out.println("constructor with no arg");
}
Here you can see the importance of "this" in constructors. It is used to call constructors from another constructor in the same function.
Case 3:- Use of "Super". Super is used to make a call to no-arg constructor of super call. Rest information is mentioned in Case 1 already.
public MyClass() {
super();
}

In the first case the constructor will insert a silent call to no argument constructor of the super-class which I guess in this case will be the Object class. In the second case the this() call will call the no argument constructor of class. It can sometimes cause an error too.

The first is the default empty constructor. It simply does nothing. If you don't have other constructors (with arguments), you don't have to define this sort of constructor at all. It is implicitly made default if no constructors are defined.
The second calls itself which causes a recursive loop, hence is forbidden.
The third calls the default no-args constructor of the super class but does nothing more. The super class is the one that your class extends from, or Object (implicitly extended if you don't specify the extends keyword).

From within a constructor, you can also use the this keyword to call another constructor in the same class. Doing so is called an explicit constructor invocation
http://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html
public class Rectangle {
private int x, y;
private int width, height;
public Rectangle() {
this(0, 0, 0, 0);
}
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;
}
}
But second one leads to recursive constructor invocation and not allowed.

public MyClass() { }
--> this is normal constructor also called default constructor.
public MyClass() {
this();
}
--> You are making constructor recursive. Don't use this way. Well you can make use of this() like :
public MyClass() {
this(1); // always intitalize to 1
}
public MyClass(int i) {
this.i=i;
}

The second one will surely cause an OutOfMemoryError exception due to a stack overflow not compile due to a Recursive constructor invocation error as you're calling the same constructor from itself. Did you mean to write
super();
? In that case both forms are identical.
public MyClass() {
}
Will call the default no-args constructor of the base class implicitly, if it exists.

this() will be used to call MyClass() No-Args Constructor.
Though it will give Recurssion constructor error during Compilation
Eg:
public MyClass{
public MyClass(){
this(5); // Here this(5) will be used to call the MyClass Constructor with
// int value as Parameter
}
public MyClass(int i){
}
}

default constructor doing nothing special. each class in java has it per default until you write your own constructor, then you have to define it by your own again
public A() {}
public A(int value) {}
is the default constructor with a recursive call on it (invalid and shouldnt be used). with this() you call default constructor. for example with this(5) you call a defined constructor which takes an int value as parameter like the example from 1.
public A() { this(5); }
public A(int value) {}
default constructor which calls the default constructor from your super class
abstract class A {
public A() {}
}
class B extends A {
public B() {
/* calls A() */
super();
}

Related

Java: Is there a way to use a method defined in a superclass, along with added functionality in the subclass? [duplicate]

I'm currently learning about class inheritance in my Java course and I don't understand when to use the super() call?
Edit:
I found this example of code where super.variable is used:
class A
{
int k = 10;
}
class Test extends A
{
public void m() {
System.out.println(super.k);
}
}
So I understand that here, you must use super to access the k variable in the super-class. However, in any other case, what does super(); do? On its own?
Calling exactly super() is always redundant. It's explicitly doing what would be implicitly done otherwise. That's because if you omit a call to the super constructor, the no-argument super constructor will be invoked automatically anyway. Not to say that it's bad style; some people like being explicit.
However, where it becomes useful is when the super constructor takes arguments that you want to pass in from the subclass.
public class Animal {
private final String noise;
protected Animal(String noise) {
this.noise = noise;
}
public void makeNoise() {
System.out.println(noise);
}
}
public class Pig extends Animal {
public Pig() {
super("Oink");
}
}
super is used to call the constructor, methods and properties of parent class.
You may also use the super keyword in the sub class when you want to invoke a method from the parent class when you have overridden it in the subclass.
Example:
public class CellPhone {
public void print() {
System.out.println("I'm a cellphone");
}
}
public class TouchPhone extends CellPhone {
#Override
public void print() {
super.print();
System.out.println("I'm a touch screen cellphone");
}
public static void main (strings[] args) {
TouchPhone p = new TouchPhone();
p.print();
}
}
Here, the line super.print() invokes the print() method of the superclass CellPhone. The output will be:
I'm a cellphone
I'm a touch screen cellphone
You would use it as the first line of a subclass constructor to call the constructor of its parent class.
For example:
public class TheSuper{
public TheSuper(){
eatCake();
}
}
public class TheSub extends TheSuper{
public TheSub(){
super();
eatMoreCake();
}
}
Constructing an instance of TheSub would call both eatCake() and eatMoreCake()
When you want the super class constructor to be called - to initialize the fields within it. Take a look at this article for an understanding of when to use it:
http://download.oracle.com/javase/tutorial/java/IandI/super.html
You could use it to call a superclass's method (such as when you are overriding such a method, super.foo() etc) -- this would allow you to keep that functionality and add on to it with whatever else you have in the overriden method.
Super will call your parent method. See: http://leepoint.net/notes-java/oop/constructors/constructor-super.html
You call super() to specifically run a constructor of your superclass. Given that a class can have multiple constructors, you can either call a specific constructor using super() or super(param,param) oder you can let Java handle that and call the standard constructor. Remember that classes that follow a class hierarchy follow the "is-a" relationship.
The first line of your subclass' constructor must be a call to super() to ensure that the constructor of the superclass is called.
I just tried it, commenting super(); does the same thing without commenting it as #Mark Peters said
package javaapplication6;
/**
*
* #author sborusu
*/
public class Super_Test {
Super_Test(){
System.out.println("This is super class, no object is created");
}
}
class Super_sub extends Super_Test{
Super_sub(){
super();
System.out.println("This is sub class, object is created");
}
public static void main(String args[]){
new Super_sub();
}
}
From oracle documentation page:
If your method overrides one of its superclass's methods, you can invoke the overridden method through the use of the keyword super.
You can also use super to refer to a hidden field (although hiding fields is discouraged).
Use of super in constructor of subclasses:
Invocation of a superclass constructor must be the first line in the subclass constructor.
The syntax for calling a superclass constructor is
super();
or:
super(parameter list);
With super(), the superclass no-argument constructor is called. With super(parameter list), the superclass constructor with a matching parameter list is called.
Note: 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.
Related post:
Polymorphism vs Overriding vs Overloading

Constructor of subtype

Consider
class MyClass{
public MyClass(Integer i){}
}
class MyExtendedClass extends MyClass{
public MyExtendedClass(SomeType s){ ... }//Compile error if SomeType!=Integer
public MyExtendedClass(Integer i){
super(i);
...
}
}
Why we cant define constructor of MyExtendedClass with signature different from MyClass's constructor? Why we must call a constructor of superclass firstly?
You can define a constructor with a different signature. But in the constructor of the subclass you have to call the constructor of the base class. The base class needs to initialize itself (e.g. its private members) and there is no other way to do it other than by calling one of its constructors.
Why we cant define constructor of MyExtendedClass with signature different from MyClass's constructor?
You can of course do it. The error you are getting is for a different reason.
Why we must call a constructor of superclass firstly?
Because that is how the objects of your class are initialized. An object's state comprise of all the fields in it's own class, plus all the non-static fields of all the superclasses.
So, when you create an instance, the state should be initialized for all the superclasses and then finally of it's own class. That is why the first statement of a constructor should be super() chaining to the superclass constructor, or this() chain to it's own class constructor.
The reason your code probably failed is, you are trying to call the superclass constructor with string argument. But there is no such constructor currently. The super class has just a single constructor taking an int argument. Also, adding super() would not work too. Because your superclass doesn't have a 0-arg constructor.
Try changing your constructor to:
public MyExtendedClass(SomeType s){
super(0);
}
and it would work. Alternatively, add a 0-argument constructor to your super class, and leave the subclass constructor as it is. It would also work in that case.
Suggested Read:
I wrote a blog post on Object Creation Process
Your constructor can have a different signature. But you must call one of super constructors. This is how Java works, see the Java Language Specification.
Alternative 1: You can call a static method, like following:
public MyExtendedClass(SomeType s){ super(convertToInt(s)); }
private Integer convertToInt(SomeType st){ ... }
Alternative 2: Use composition / delegate instead of inheritance.
class MyExtendedClass [
private MyClass delegate;
public MyExtendedClass(SomeType s){
do what you want
delegate = new MyClass(...);
}
public void doSomething(... params){
delegate.doSomething(params);
}

Constructors and Inheritence

I was wondering how to use a superclass constructor in a subclass but need to instantiate fewer attributes in the subclass. Below are the two classes. I'm not even sure if I'm doing things right currently. In the second class, there's an error that says "Implicit super constructor PropertyDB() is undefined. Must explicitly invoke another constructor." Note that this code is obviously incomplete and there is code that's commented out.
public abstract class PropertyDB {
private int hectares;
private String crop;
private int lotWidth;
private int lotDepth;
private int buildingCoverage;
private int lakeFrontage;
private int numBedrooms;
private int listPrice;
//public abstract int getPricePerArea();
//public abstract int getPricePerBuildingArea();
public PropertyDB(int newHectares, String newCrop, int newLotWidth, int newLotDepth,
int newBuildingCoverage, int newLakeFrontage, int newNumBedrooms, int newListPrice){
hectares = newHectares;
crop = newCrop;
lotWidth = newLotWidth;
lotDepth = newLotDepth;
buildingCoverage = newBuildingCoverage;
lakeFrontage = newLakeFrontage;
numBedrooms = newNumBedrooms;
listPrice = newListPrice;
}
}
public class FarmedLand extends PropertyDB{
public FarmedLand(int newHectares, int newListPrice, String newCorn){
//super(270, 100, "corn");
hectares = newHectares;
listPrice = newListPrice;
corn = newCorn;
}
}
implicit constructor PropertyDB() exists only if you do not define any other constructors, in which case you will have to explicitly define PropertyDB() constructor.
The reason you see this error "Implicit super constructor PropertyDB() is undefined. Must explicitly invoke another constructor." is that in your public FarmedLand(int newHectares, int newListPrice, String newCorn) constructor, super() is automatically called as the first statement, which does not exist in your superclass.
Here's a simplified example:
public class A { }
can be instantiated by using A a = new A() because public A() { } is an implicit constructor of class A.
public class A {
public A(int z) { /* do nothing*/ }
}
can not be instantiated using A a = new A() because by defining an explicit constructor public A(int z) the implicit one is no longer available.
Moving onto constructors and inheritance, from Java Language Specification section 8.8.7:
If a constructor body does not begin with an explicit constructor invocation and the constructor being declared is not part of the primordial class Object, then the constructor body is implicitly assumed by the compiler to begin with a superclass constructor invocation "super();", an invocation of the constructor of its direct superclass that takes no arguments.
So in your case the first statement executed in public FarmedLand(int newHectares, int newListPrice, String newCorn) constructor is an implicit call to super();, which in your case is not defined implicitly (there's already a public PropertyDB(int, String, ...) constructor defined) or explicitly (it's not in the source code)
When you have a derived class which extends a base class, the base class always gets constructed before the derived class. If you don't explicitly specify which constructor to use for the base class (like in your example), Java assumes you meant the parameterless constructor (in your case the PropertyDB() constructor).
But wait - PropertyDB doesn't have a parameterless constructor! So your only option is to use super so the Java compiler knows which constructor to call for the base class. In your case, there's only one constructor to choose from, so you have to use it with all 8 arguments. If you want to use less arguments, you either have to specify "default" values (like pass a 0), or else define more constructors for PropertyDB which take fewer arguments.
The error you're witnessing is due to the fact that the PropertyDB class doesn't have a default (no-arguments) constructor. Either create it in PropertyDB or call the existing superclass constructor PropertyDB(int newHectares, String newCrop, int newLotWidth, int newLotDepth, int newBuildingCoverage, int newLakeFrontage, int newNumBedrooms, int newListPrice) from the FarmedLand constructor using super.
Use super(newHectares, newCorn, 0, 0, 0, 0, newListPrice); instead. 0 is the default value of the int anyway.
Your superclass only has one constructor, so your subclass constructor must call it. There's no way around this: the superclass has (for example) a lotWidth field, so the subclass necessarily has that field, and the superclass initializes that field in its constructor, so it will necessarily be initialized in the subclass.
So, unless you modify the superclass in some way, you're going to have to call super(...) as the very first thing in the subclass constructor, specifying values for all its parameters.

Why default constructor is required in a parent class if it has an argument-ed constructor?

Why default constructor is required(explicitly) in a parent class if it has an argumented constructor
class A {
A(int i){
}
}
class B extends A {
}
class Main {
public static void main(String a[]){
B b_obj = new B();
}
}
This will be an error.
There are two aspects at work here:
If you do specify a constructor explicitly (as in A) the Java compiler will not create a parameterless constructor for you.
If you don't specify a constructor explicitly (as in B) the Java compiler will create a parameterless constructor for you like this:
B()
{
super();
}
(The accessibility depends on the accessibility of the class itself.)
That's trying to call the superclass parameterless constructor - so it has to exist. You have three options:
Provide a parameterless constructor explicitly in A
Provide a parameterless constructor explicitly in B which explicitly calls the base class constructor with an appropriate int argument.
Provide a parameterized constructor in B which calls the base class constructor
Every subclass constructor calls the default constructor of the super class, if the subclass constructor does not explicitly call some other constructor of the super class. So, if your subclass constructor explicitly calls a super class constructor that you provided (with arguments), then there is no need of no arguments constructor in the super class.
So, the following will compile:
class B extends A{
B(int m){
super(m);
}
}
But the following will not compile, unless you explicitly provide no args constructor in the super class:
class B extends A{
int i;
B(int m){
i=m;
}
}
Why default constructor is required(explicitly) in a parent class if it has an argumented constructor
I would say this statement is not always correct. As ideally its not required.
The Rule is : If you are explicitly providing an argument-ed constructer, then the default constructor (non-argumented) is not available to the class.
For Example :
class A {
A(int i){
}
}
class B extends A {
}
So when you write
B obj_b = new B();
It actually calls the implicit constructor provided by java to B, which again calls the super(), which should be ideally A(). But since you have provided argument-ed constructor to A, the default constructor i:e A() is not available to B().
That's the reason you need A() to be specifically declared for B() to call super().
Assuming that you meant to write class B extends A:
Every constructor has to call a superclass constructor; if it does not the parameterless superclass constructor is called implicitly.
If (and only if) a class declares no constructor, the Java compiler gives it a default constructor which takes no parameters and calls the parameterless constructor of the superclass. In your example, A declares a constructor and therefor does not have such a default constructor. Class B does not declare a constructor, but cannot get a default constructor because its superclass does not have a parameterless constructor to call. Since a class must always have a constructor, this is a compiler error.
Why default constructor is required(explicitly) in a parent class if it
has an argumented constructor
Not necessarily!
Now in your class B
class B extends A {
}
you have not provided any constructor in Class B so a default constructor will be placed. Now it is a rule that each constructor must call one of it's super class constructor. In your case the default constructor in Class B will try to call default constructor in class A(it's parent) but as you don't have a default constructor in Class A(as you have explicitly provided a constructor with arguments in class A you will not have a default constructor in Class A ) you will get an error.
What you could possibly do is
Either provide no args constructor in Class A.
A()
{
//no arg default constructor in Class A
}
OR
Explicitly write no args constructor in B and call your super with some default int argument.
B()
{
super(defaultIntValue);
}
Bottom line is that for an object to be created completely constructors of each parent in the inheritance hierarchy must be called. Which ones to call is really your design choice. But in case you don't explicitly provide any java will put default constructor super() call as 1st line of each of your sub class constructors and now if you don't have that in superclass then you will get an error.
There are a few things to be noted when using constructors and how you should declare them in your base class and super class. This can get somewhat confusing solely because there can be many possibilities of the availability or existence of constructors in the super class or base class. I will try to delve into all the possibilities:
If you explicitly define constructors in any class(base class/super class), the Java compiler will not create any other constructor for you in that respective class.
If you don't explicitly define constructors in any class(base class/super class), the Java compiler will create a no-argument constructor for you in that respective class.
If your class is a base class inheriting from a super class and you do not explicitly define constructors in that base class, not only will a no-argument constructor be created for you (like the above point) by the compiler, but it will also implicitly call the no-argument constructor from the super class.
class A
{
A()
{
super();
}
}
Now if you do not explicity type super(), (or super(parameters)), the compiler will put in the super() for you in your code.
If super() is being called (explicitly or implicitly by the compiler) , the compiler will expect your superclass to have a constructor without parameters. If it does not find any constructor in your superclass without parameters, it will give you a compiler error.
Similary if super(parameters) is called, the compiler will expect your superclass to have a constructor with parameters(number and type of parameters should match). If it does not find such a constructor in your superclass, it will give you a compiler error. ( Super(parameters) can never be called implicitly by the compiler. It has to be explicitly put in your code if one is required.)
We can summarize a few things from the above rules
If your superclass only has a constructor with parameters and has no no-argument constructor, you must have an explicit super(parameters) statement in your constructor. This is because if you do not do that a super() statement will be implicitly put in your code and since your superclass does not have a no-argument constructor, it will show a compiler error.
If your superclass has a constructor with parameters and another no-argument constructor, it is not necessary to have an explicit super(parameters) statement in your constructor. This is because a super() statement will be implicitly put in your code by the compiler and since your superclass has a no-argument constructor, it will work fine.
If your superclass only has a no-argument constructor you can refer to the point above as it is the same thing.
Another thing to be noted is if your superclass has a private constructor, that will create an error when you compile your subclass. That is because if you don't write a constructor in your subclass it will call the superclass constructor and the implicit super() will try to look for a no-argument constructor in the superclass but will not find one.
Say this compiled, what would you expect it to print?
class A{
A(int i){
System.out.println("A.i= "+i);
}
}
class B extends A {
public static void main(String... args) {
new B();
}
}
When A is constructed a value for i has to be passed, however the compiler doesn't know what it should be so you have specify it explicitly in a constructor (any constructor, it doesn't have to be a default one)
Of course its an error if written like this it's not JAVA.
If you would have use JAVA syntax it wouldn't be an error.
Class A and B knows nothing about each other if in separate files/packages.
Class A doesn't need a default constructor at all it works fine with only a parameter constructor.
If B extends A you simple use a call to super(int a) in B's constructor and everything is fine.
for constructors not calling a super(empty/or not) extending a super class the compiler will add a call to super().
For further reading look at Using the Keyword super
I would guess that its because when you have an empty parameter list the super variable can't be instantiated. With empty parameter list I mean the implicit super() the compiler could add if the super class had a nonparametric constructor.
For example if you type:
int a;
System.out.print(a);
You will get an error with what I think is the same logic error.
When we have parameter constructor. we explicit bound to consumer by design. he can not create object of that class without parameter. some time we need to force user to provide value. object should be created only by providing parameter(default value).
class Asset
{
private int id;
public Asset(int id)
{
this.id = id;
}
}
class Program
{
static void Main(string[] args)
{
/* Gives Error - User can not create object.
* Design bound
*/
Asset asset1 = new Asset();/* Error */
}
}
Even child class can not create. hence it is behavior of good design.
When extending a class, the default superclass constructor is automatically added.
public class SuperClass {
}
public class SubClass extends SuperClass {
public SubClass(String s, Product... someProducts) {
//super(); <-- Java automatically adds the default super constructor
}
}
If you've overloaded your super class constructor, however, this takes the place of the default and invoking super() will thus cause a compile error as it is no longer available. You must then explicitly add in the overloaded constructor or create a no-parameter constructor. See below for examples:
public class SuperClass {
public SuperClass(String s, int x) {
// some code
}
}
public class SubClass extends SuperClass {
public SubClass(String s, Product... someProducts) {
super("some string", 1);
}
}
OR...
public class SuperClass {
public SuperClass() {
// can be left empty.
}
}
public class SubClass extends SuperClass {
public SubClass(String s, Product... someProducts) {
//super(); <-- Java automatically adds the no-parameter super constructor
}
}
Because if you want to block creation of objects without any data in it, this is one good way.

When do I use super()?

I'm currently learning about class inheritance in my Java course and I don't understand when to use the super() call?
Edit:
I found this example of code where super.variable is used:
class A
{
int k = 10;
}
class Test extends A
{
public void m() {
System.out.println(super.k);
}
}
So I understand that here, you must use super to access the k variable in the super-class. However, in any other case, what does super(); do? On its own?
Calling exactly super() is always redundant. It's explicitly doing what would be implicitly done otherwise. That's because if you omit a call to the super constructor, the no-argument super constructor will be invoked automatically anyway. Not to say that it's bad style; some people like being explicit.
However, where it becomes useful is when the super constructor takes arguments that you want to pass in from the subclass.
public class Animal {
private final String noise;
protected Animal(String noise) {
this.noise = noise;
}
public void makeNoise() {
System.out.println(noise);
}
}
public class Pig extends Animal {
public Pig() {
super("Oink");
}
}
super is used to call the constructor, methods and properties of parent class.
You may also use the super keyword in the sub class when you want to invoke a method from the parent class when you have overridden it in the subclass.
Example:
public class CellPhone {
public void print() {
System.out.println("I'm a cellphone");
}
}
public class TouchPhone extends CellPhone {
#Override
public void print() {
super.print();
System.out.println("I'm a touch screen cellphone");
}
public static void main (strings[] args) {
TouchPhone p = new TouchPhone();
p.print();
}
}
Here, the line super.print() invokes the print() method of the superclass CellPhone. The output will be:
I'm a cellphone
I'm a touch screen cellphone
You would use it as the first line of a subclass constructor to call the constructor of its parent class.
For example:
public class TheSuper{
public TheSuper(){
eatCake();
}
}
public class TheSub extends TheSuper{
public TheSub(){
super();
eatMoreCake();
}
}
Constructing an instance of TheSub would call both eatCake() and eatMoreCake()
When you want the super class constructor to be called - to initialize the fields within it. Take a look at this article for an understanding of when to use it:
http://download.oracle.com/javase/tutorial/java/IandI/super.html
You could use it to call a superclass's method (such as when you are overriding such a method, super.foo() etc) -- this would allow you to keep that functionality and add on to it with whatever else you have in the overriden method.
Super will call your parent method. See: http://leepoint.net/notes-java/oop/constructors/constructor-super.html
You call super() to specifically run a constructor of your superclass. Given that a class can have multiple constructors, you can either call a specific constructor using super() or super(param,param) oder you can let Java handle that and call the standard constructor. Remember that classes that follow a class hierarchy follow the "is-a" relationship.
The first line of your subclass' constructor must be a call to super() to ensure that the constructor of the superclass is called.
I just tried it, commenting super(); does the same thing without commenting it as #Mark Peters said
package javaapplication6;
/**
*
* #author sborusu
*/
public class Super_Test {
Super_Test(){
System.out.println("This is super class, no object is created");
}
}
class Super_sub extends Super_Test{
Super_sub(){
super();
System.out.println("This is sub class, object is created");
}
public static void main(String args[]){
new Super_sub();
}
}
From oracle documentation page:
If your method overrides one of its superclass's methods, you can invoke the overridden method through the use of the keyword super.
You can also use super to refer to a hidden field (although hiding fields is discouraged).
Use of super in constructor of subclasses:
Invocation of a superclass constructor must be the first line in the subclass constructor.
The syntax for calling a superclass constructor is
super();
or:
super(parameter list);
With super(), the superclass no-argument constructor is called. With super(parameter list), the superclass constructor with a matching parameter list is called.
Note: 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.
Related post:
Polymorphism vs Overriding vs Overloading

Categories