user16401
user16401

Reputation: 193

Using super() in constructor

If we, in our program, have just one class, without extending any class. For example

public class Point {
    int x, y;
}

Compiler creates default constructor and call the super() method acording to this http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.8.9

public class Point {
    int x, y;
    public Point() { 
    super(); 
    }
}

Q: As i understand super(); is calling default constructor of super class, but in this case we do not have a super class, so what is super() calling in that case?

Upvotes: 0

Views: 279

Answers (7)

Arcturus
Arcturus

Reputation: 27065

The default contructor is Object, which all Java objects inherit from

Upvotes: 1

Aniket Thakur
Aniket Thakur

Reputation: 69035

Each class in Java implicitly extends Object Class. So you can always call super() from the constructor of any class.

Again in Object class there is no explicit constructor. Compiler creates a default one and the default constructor of the Object class creates the object itself.

Upvotes: 0

Andrew Martin
Andrew Martin

Reputation: 5761

You do have a super class. All classes in Java automatically extend java.lang.Object, regardless of whether you specify it or not.

See here: http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html

To take one snippet from that link:

All classes have at least one constructor. If a class does not explicitly declare any, the Java compiler automatically provides a no-argument constructor, called the default constructor. This default constructor calls the class parent's no-argument constructor, or the Object constructor if the class has no other parent. If the parent has no constructor (Object does have one), the compiler will reject the program.

Upvotes: 4

Ruchira Gayan Ranaweera
Ruchira Gayan Ranaweera

Reputation: 35587

Object is the super type of all in java. Super() it will call Object class.

Upvotes: 0

NiziL
NiziL

Reputation: 5140

All java classes extend from Object

Upvotes: 5

Ravi.Kumar
Ravi.Kumar

Reputation: 767

All Java Classes extends from Object, so if you are not extending any class, by super you are calling constructor of Object class.

Upvotes: 0

gefei
gefei

Reputation: 19856

In java, every class has a super class. If none is explicitly given, then it's Object

Upvotes: 0

Related Questions