Home > Java > javaTutorial > Why can't constructors be final in Java?

Why can't constructors be final in Java?

PHPz
Release: 2023-08-20 19:01:22
forward
1488 people have browsed it

Why cant constructors be final in Java?

Whenever you declare a method as final, you cannot override it. That is, you cannot provide a subclass with an implementation of a superclass's final method.

In other words, the purpose of declaring a method as final is to prevent the method from being modified from the outside (subclasses).

In inheritance, when you extend a class, the subclass inherits all members of the superclass except the constructor.

In other words, constructors cannot be inherited in Java, therefore you cannot override constructors.

Therefore, it makes no sense to add final in front of the constructor. Therefore, Java does not allow the use of final keyword before a constructor.

If you try to declare the constructor as final, a compile-time error will be generated, prompting "modifier final not allowed here".

Example

In the following Java program, the Student class has a constructor that is declared final.

Demo

public class Student {
   public final String name;
   public final int age;
   public final Student() {
      this.name = "Raju";
      this.age = 20;
   }
   public void display() {
      System.out.println("Name of the Student: "+this.name );
      System.out.println("Age of the Student: "+this.age );
   }
   public static void main(String args[]) {
      new Student().display();
   }
}
Copy after login

Compile Time Error

While compiling, the above program generates the following error.

Student.java:6: error: modifier final not allowed here
   public final Student(){
                ^
1 error
Copy after login

The above is the detailed content of Why can't constructors be final in Java?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template