English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

- Can a constructor in Java be marked FINAL?
- If not, why?

Thanks for your help.

2006-07-11 13:04:27 · 4 answers · asked by Oblivious 1 in Computers & Internet Software

4 answers

The final keword on a method means that it cannot be overridden in a subclass. However, in the case of constructors that is meaningless, since constructors are not inherited by subclasses.

Check with this:

A.java
---------------------
public class A {

public A( int whatever ) { }
}
---------------------

B.java
---------------------
public class B extends A {

public B() { super(1); }
}
---------------------

Tester.java
---------------------
public class Tester {

public static void main( String[] args ) {

A tryA = new A(5);
B tryB = new B();
B tryB2 = new B(5);
}

}
---------------------


When you compile Tester.java you should get a syntax error on the third line. That is because the class B did not inherit the "int" constructor from class A. Constructors are like private methods in this way. A Constructor is usable only in the context of the class that declares it. Subclasses may refer to the superclass constructors with the super keyword, but they may not treat them as if they were inherited methods.

Since a constructor (or private method) cannot be inherited by a subclass, it is meaningless to talk about overriding a constructor (or private method). There is nothing usable in the subclass to override. If there is no override behavior for constructors (or private methods), there is no need for the final keyword, which prevents subclasses from overriding.

So basically the reason that you cannot make a constructor (or private method) final is that the final keyword is meaningless for constructors (and private methods).

2006-07-14 10:44:11 · answer #1 · answered by BalRog 5 · 1 0

i think that depends because if you have it made to become a FINAL then it would work? get it? but usually it wouldnt work because its suppose to initialize

2006-07-11 20:07:51 · answer #2 · answered by Danny 2 · 0 1

yes
bt meaning less

2006-07-16 03:17:37 · answer #3 · answered by ihoston 3 · 0 1

no, you need destructor

2006-07-11 20:07:41 · answer #4 · answered by Anonymous · 0 1

fedest.com, questions and answers