Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@Override not supported for Constructors

Tags:

java

I know Constructors are not inheritable in java, we need to use super() - super must be the first statement in Constructors.

But why cant i use @Override annotation?

In example:

public class Foo extends Point2D.Double {
    @Override // The annotation @Override is disallowed for this location
    public Foo(){}
}

If i have a instance of Foo, i never ever can call Point2D.Double.Double() directly! This behave is compleatly like Overriding!

like image 587
Grim Avatar asked Sep 11 '13 09:09

Grim


People also ask

Can you override a constructor?

It does not have a return type and its name is same as the class name. But, a constructor cannot be overridden. If you try to write a super class's constructor in the sub class compiler treats it as a method and expects a return type and generates a compile time error.

What if @override is not used?

If you don't use the annotation, the sub-class method will be treated as a new method in the subclass (rather than the overriding method).

Why we cant override the constructor in Java?

Constructor Overriding is never possible in Java. This is because, Constructor looks like a method but name should be as class name and no return value. Overriding means what we have declared in Super class, that exactly we have to declare in Sub class it is called Overriding.

Can we override a constructor in C++?

Constructors can be overloaded in a similar way as function overloading. Overloaded constructors have the same name (name of the class) but the different number of arguments.


2 Answers

@Override is used when you are overriding a method (not a constructor!), which means that you are creating a method using the same name and parameters as one of the methods from superclass.

There is no constructor called Foo() in your superclass (obviously), because constructors aren't inherited from parent classes, so this is not overriding.

Overriding can be only applied to inherited methods which are not constructors and are not defined as final.

like image 68
Celebes Avatar answered Oct 28 '22 14:10

Celebes


You cannot override a constructor.

Constructors are not inherited.

Yous subclasses constructor is completely different and independent from super class's constructor (language semantically, due to initializations etc it may depend. ).

While you can call super() to call the super class's constructor it's called chaining not overriding.

like image 33
Thihara Avatar answered Oct 28 '22 13:10

Thihara