Yes, we can declare the main () method as final in Java. The compiler does not throw any error final keyword in a method declaration to indicate that the method cannot be overridden by subclasses If we are using inheritance and we need some methods not to overridden in subclasses then we need to make it final so that those methods can't be overridden by subclasses. We can access final methods in the subclass but we can not override final methods Output:
class ParentClass{
public final void show(Object o) {
System.out.println("ParentClass method");
}
}
class ChildClass extends ParentClass {
public void show(Integer i) {
System.out.println("ChildClass method");
}
}
public class Test {
public static final void main(String[] args) { // declaring main () method with final keyword.
ParentClassb = new ParentClass();
ChildClass d = new ChildClass ();
b.show(new Integer(0));
d.show(new Integer(0));
}
}
ParentClass method
ChildClass method
What is a Class/Static Variables?
How to Create Objects in Java?
Convert given time in String format to seconds
Can we declare the main method as private in Java?
Can we declare the main () method as final in Java?
How to create a table in Java with JDBC Connection?
What is the Difference between Path and ClassPath in java?
Can we overload the main method in Java?
What is the difference between JDK and JRE?
What are the important features of Java 8?
Memory Allocation in Java
What is Instance variable?
How to check Java version?
What is Method Overloading in Java ?
Can we declare a static variable within a method in java?
Can we define a static constructor in Java?