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

Why can't constructors be final in Java?

PHPz
PHPzforward
2023-08-20 19:01:221457browse

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();
   }
}

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

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete