In this program there is no need for a super to reach the superclass's constructor:
class Base{
Base(){
System.out.println("Base");
}
}
public class test2 extends Base{
test2() {
//super();
System.out.print("test2");
}
public static void main(String argv[]){
test2 c = new test2();
}
}
But this program needs super and gives an error at quest1 constructor saying
constructor quest can't be applied to given types: required int, found no arguments
class Quest {
Quest(int y){
System.out.print("A:"+y);
}
}
class Quest1 extends Quest {
Quest1(int x){
//super(x+1);
System.out.print("B:"+x);
}
}
class Test {
public static void main(String argv[]){
Quest1 q = new Quest1(5);
}
}
JLS 8.8.7. Constructor Body
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 implicitly begins with a superclass constructor invocation "super();", an invocation of the constructor of its direct superclass that takes no arguments.
In
class Base {
Base() {
}
}
public class test2 extends Base {
test2() {
//super();
System.out.print("test2");
}
}
The commented out line is added automatically and since the superclass's no-argument constructor is defined, there is no error.
In the case of
class Quest {
Quest(int y) {
System.out.print("A:"+y);
}
}
class Quest1 extends Quest {
Quest1(int x) {
//super(x+1);
System.out.print("B:"+x);
}
}
The implicit call super() is trying to invoke an undefined constructor in the superclass, which causes the error
Implicit super constructor Quest() is undefined. Must explicitly invoke another constructor.
Uncommenting your explicit constructor call replaces the implicit call and thus the problem is resolved. Alternatively, define a no-argument constructor in the superclass.
You need a call to super() if and only if there's no default constructor (accepting no arguments) for your parent class.
In all other cases (where a constructor with zero arguments exists) you don#t have to code it. It's implicitly called anyway.
These Rules apply:
if your parent class has no constructor at all, it has the default constructor, which takes no arguments -> no need for super();
you parent class declares a constructor with no arguments -> no need for super()
your class has a constructor with arguments but no constructor without arguments -> you need to call one of the defined constructors with mathching arguments via super()
If you create a constructor in super class the you should call the super class constructor (Ex : super()) before the sub class constructor gets call.
Related
We use super() to call the constructor of parent class.
we know that every method have:
some prototype (i.e. modifier returnType methodName (arguments){}),
Its own definition, and
In which class it is present.
So, I want to know only that in which class super() is present and what its prototype.
class ParentClass
{
ParentClass()
{
System.out.println("parent class constructor");
}
}
public class ChildClass extends ParentClass
{
ChildClass()
{
super();
}
public static void main(String[] a)
{
ChildClass cc = new ChildClass();
}
}
Output parent class constructor
super() is not present in our class and Object class then how constructor internally call the super()?
super() is not present in our class and Object class then how constructor internally call the super()?
Consider super() to be more of keyword. It is not a method name.
In other words: it doesn't denote a method named super. It denotes (for example) a constructor from the super class.
In your example, that call to super simply "points" to that ParentClass() constructor.
See here or there for more details.
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 superclass does not have a no-argument constructor, you will get a compile-time error. Object does have such a constructor, so if Object is the only superclass, there is no problem.
Either you write super() or not write in constructor of subclass, implicitly there is super() invoked to call superclass default constructor , you might think that a whole chain of constructors called, all the way back to the constructor of Object. This, in fact, is the case. It is called constructor chaining.
/* superclass Person */
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
I have two class :-
import java.lang.*;
class A {
public A(int number) {
System.out.println("HI I AM INSIDE PARENT CONSTRUCTOR");
}
}
class B extends A {
public static void main(String[] args) {
A obj = new A(10);
}
}
Error:- Implicit super constructor A() is undefined for default constructor. Must define an explicit constructor.
The problem is that you have no constructor declared in B, so the compiler is supplying the default constructor, which in effect looks like this:
B() {
super();
}
Since A has no constructor accepting zero parameters, B can't be compiled. You'll need to add a constructor to B that calls super(int), or you'll need to add a zero-parameters constructor to A.
Principle
A subclass constructor has to invoke the parent constructor.
By default, a no arg constructor is generated by the compiler if you don't declare one.
Important detail : this generated constructor invokes the parent constructor with a no arg invocation.
Your case
You don't declare a constructor in B.
So a default no arg constructor of B is generated :
This constructor is :
B(){
super();
}
but it cannot invoke the parent constructor as it declares one parameter :
public A(int number)
So the compiler emits this error :
Implicit super constructor A() is undefined for default constructor.
Must define an explicit constructor.
To solve your problem, declare a constructor in the subclass that invokes explicitly the parent constructor with the expected argument :
public B(int number) {
super(number);
}
I think you're missing the default constructor in your A class.
See this answer for further explanation.
You have given your own constructor for A having arguments of int. now you need to add a constructor on your own to the class B as well.
public B(int number) {
super(number);
}
When you don't define a constructor in Java, you get an implicit default constructor. When you define a constructor, then the default constructor is not there anymore. So, when you have something like:
Class A {
}
this is equivalent to:
Class A {
A() {
super();
}
}
In your case, class B is calling the default constructor of A, but because A already defined another constructor, the default constructor is then not there anymore, unless you define it explicitly.
Add constructor B(int):
import java.lang.*;
class A {
public A(int number) {
System.out.println("HI I AM INSIDE PARENT CONSTRUCTOR");
}
}
class B extends A {
public B(int number) {
super(number);
}
public static void main(String[] args) {
A obj = new A(10);
}
}
Add:
public B(int number) {
super(number);
}
Cause you have defined a constructor with arguments in parent class,so the compiler won't call the default constructor without arguments.In order to instance parent class before subclass initializing,you have to call parent's explicit constructor in subclass.
I'm very new in Java, and about to ask a fundamental question. Hope you guys could help me. Supposed I have a base classe Super and a derived class Sub, which inheritances from class Super as follows:
public class TestSuperSub {
public static void main(String[] args) {
Super ou = new Sub(5,10);
}
}
class Super {
Super() {
System.out.println("Super()");
}
Super(int x, int y) {
System.out.println("Super(int, int)");
}
}
class Sub extends Super {
public Sub(int x, int y) {
System.out.println("Sub(int, int)");
}
}
The output is
Super()
Sub(int, int)
I understand, that ou calls Sub::Sub(int,int) and therefore, Sub(int, int) is printed. But why is Super() printed, since Super::Super() hasn't never been called?
Could someone please explain it to me.
Thanks a lot!
Cheers
By default, Java will call the no-arg constructor of a super class unless you explicitly call another constructor. If you want to call Super(int, int), you must call it explicitly:
public Sub(int x, int y) {
super(x, y);
System.out.println("Sub(int, int)");
}
But why is Super() printed, since Super::Super() hasn't never been called?
It has, because your Sub constructor is implicitly calling it. It's as if you'd written:
public Sub(int x, int y) {
super();
System.out.println("Sub(int, int)");
}
From section 8.8.7 of the JLS:
The first statement of a constructor body may be an explicit invocation of another constructor of the same class or of the direct superclass (§8.8.7.1).
...
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.
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 implicitly begins with a superclass constructor invocation "super();", an invocation of the constructor of its direct superclass that takes no arguments.
If you want to call a different superclass constructor, you need to do that implicitly. When you call a subclass constructor, that will always work its way up through the inheritance hierarchy, executing the body of the superclass constructor before the subclass constructor... indeed, even field initializers in the subclass are only run after the superclass constructor.
Its the very basic fundamental concept in Java. Its the magic of super keyword and constructor chaining.
Go through these links. Hope this would help you understand the concept.
http://docstore.mik.ua/orelly/java-ent/jnut/ch03_04.htm
http://docs.oracle.com/javase/tutorial/java/IandI/super.html
By Default in constructor of sub class
the first line is call base class default constructor (implicitly) if no constructor is mentioned that is **
super();
**
if you write
super(x,y);
then other constructor will be called
Note : First line of constructor is to call base class constructor.
if there is no super class then Object class's constructor is called
When you instantiate a class, all the superclass hierarchy must also be instantiated and it will be done so through the null constructors automatically available for each class.
The following code
public class Superclassing {
public static void main(String[] args) {
new C();
}
Superclassing() { System.out.println("super"); }
}
class A extends Superclassing {
A() { System.out.println("A"); }
}
class B extends A {
B() { System.out.println("B"); }
}
class C extends B {
C() { System.out.println("C"); }
}
outputs
super
A
B
C
It is done so by design as mentioned in Skeet's answer and also here (oddly, it is mentioned before it is explained in 8.8.7):
JLS 8.8.3. Constructor Modifiers
The lack of native constructors is an arbitrary language design choice
that makes it easy for an implementation of the Java Virtual Machine
to verify that superclass constructors are always properly invoked
during object creation.
(emphasis mine.)
class A{
A(){
System.out.println("no-arg constructor in A");
}
A(int a){
System.out.println("parameterized constructor in A");
}
}
class B extends A{
B(){
System.out.println("no-arg constructor in B");
}
B(int b){
//by default during compilation super() keyword will be added in first line of this constructor
System.out.println("paramterized constructor in B");
}
}
public class TestDemo {
public static void main(String[] args) {
B aVar = new B(10);
aVar = new B();
}
}
Output:
// output for first object i.e, new B(10)
no-arg constructor in A
paramterized constructor in B
//output for second object i.e, new B()
no-arg constructor in A
no-arg constructor in B
A super() keyword will be add by default by the compiler during compilation depending on the Object that u create in main method.
I've run this code
public class Redimix extends Concrete{
Redimix(){
System.out.println("r ");
}
public static void main(String[] args) {
new Redimix();
}
}
class Concrete extends Sand{
Concrete() { System.out.print("c "); }
private Concrete(String s) { }
}
abstract class Sand{
Sand(){
System.out.print("s ");
}
}
and it printed out s c r but what I was expecting is that only r my question what is the logical explanation for this?
if a parent base class is an abstract class that has a constructor and then we create another class then extend it to the base class (In our Case Concrete extends Sand) and we then create another class then extend it to the concrete class name (In our case redimix) will all constructors from the hierarchy will be called?(from top to bottom)
A constructor of the superclass is always called as the first action of a constructor.
If you do not explicitly invoke a constructor of the superclass, the default constructor (the "no args" one) is implicitly invoked.
That is correct. The parent object's constructor is always called before the childs. This ensures that the object is in a valid state and that the object that has extended another class can always know what state the object is in.
Here is the code that you provided, after the compiler has inserted the implicit constructor calls in on your behave. Note that super(); is always called first.
public class Redimix extends Concrete{
Redimix(){
super();
System.out.println("r ");
}
public static void main(String[] args) {
new Redimix();
}
}
class Concrete extends Sand{
Concrete() { super(); System.out.print("c "); }
private Concrete(String s) { }
}
abstract class Sand{
Sand(){
super(); // invoking the constructor for java.lang.Object
System.out.print("s ");
}
}
In each constructor, parent constructor is also called.
In every constructor, first statement is always super() which is calling super class constructor except for Object class
You need to understand constructor chaining for this. When you make a call to any constructor all the super class constructors are invoked first. In you constructor definition, if you dont have one compiler will add a no argument call to super class constructor something like this : super();
This is because, all the class in the hierarchy must be build before you actual class, because your class is dependent on its super class.
This class to the super class constructor should always be the first statement in your constructor definition because they must be build before this concerned class. So Object class constructor is always the first to be executed.
I always thought that constructors aren't inherited, but look at this code:
class Parent {
Parent() {
System.out.println("S1");
}
}
class Child extends Parent {
Child() {
System.out.println("S2");
}
}
public class Test5 {
public static void main(String[] args) {
Child child = new Child();
}
}
//RESULT:
//S1
//S2
It shows that Child inherited constructor. Why there is S1 on result? Is there any possibility to create 2 constructors without parameters and have only Child constructor on result without base constructor (only S2)?
Whatever you are seeing here is called as constructor chaining. Now What is Constructor Chaining:
Constructor chaining occurs through the use of inheritance. A subclass
constructor method's first task is to call its superclass' constructor
method. This ensures that the creation of the subclass object starts
with the initialization of the classes above it in the inheritance
chain.
There could be any number of classes in an inheritance chain. Every
constructor method will call up the chain until the class at the top
has been reached and initialized. Then each subsequent class below is
initialized as the chain winds back down to the original subclass.
This process is called constructor chaining.(Source)
That's what happening in your program. When you compile your program , your Child is compiled to this way by javac:
class Child extends Parent
{
Child()
{
super();//automatically inserted here in .class file of Child
System.out.println("S2");
}
}
And your Parent class is converted to following:
Parent()
{
super();//Constructor of Object class
System.out.println("S1");
}
That's why your output is showing as:
S1 //output from constructor of super class Parent
S2 //output from constructor of child Class Child
Java doc says :
A subclass inherits all the members (fields, methods, and nested
classes) from its superclass. Constructors are not members, so they
are not inherited by subclasses, but the constructor of the superclass
can be invoked from the subclass.
If you don't declare a constructor of any type, a default is added.
If you don't call any other constructor in the first line of your subclass, a call to super() is made.
You write:
It shows that Child inherited constructor.
Constructors can not be inherited. Classes can be inherited, so Child does not inherit any constructor. Child inherits class Parent. Parent inherits class Object. When you call the Child constructor, automatically an Object constructor is called and then a Parent constructor, before the code of the Child constructor is run.
This why you get this result:
S1
S2
Constructor are not inherited.
Super class constructor are not inherited in derived class.
Is there any possibility to create 2 constructors without parameters and have only Child constructor on result without base constructor.
No, Its not possible In Java every derived class constructor call super class constructor. If you not add it call no argument constructor.
public SuperClass() {
...
}
public DerivedClass() {
//Compiler here call no argument constructor of Super class.
}
A constructor will always call its superclass constructor unless an explicit constructor has been defined. From the Java Language Specification:
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 implicitly begins with a superclass constructor invocation "super();", an invocation of the constructor of its direct superclass that takes no arguments.
If superclass doesn’t have default constructor, then subclass also needs to have an explicit constructor defined. Else it will throw compile time exception. In the subclass constructor, call to superclass constructor is mandatory in this case and it should be the first statement in the subclass constructor.
public class HelloWorld{
private static class A {
A(String x) {
System.out.println(x);
}
}
private static class B extends A {
}
public static void main(String []args){
B b = new B();
System.out.println("Hello World");
}
}
Output:
/*
error: constructor A in class A cannot be applied to given types;
private static class B extends A {
^
required: String
found: no arguments
reason: actual and formal argument lists differ in length
1 error
*/
So what it means is constructors are never inherited
Hence, what happens here is class B's argument less constructor tries to call class A's argument less contructor, But it didn't find that hence gives it gives error.
If we add argument less constructor in class A, then this program will work properly.