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 Method Overloading in Java ?
How to Create Objects in Java?
What is the difference between JDK and JRE?
What is Instance variable?
Can we define a static constructor in Java?
Can we declare the main () method as final in Java?
Can we declare the main method as private in Java?
How to create a table in Java with JDBC Connection?
Can we overload the main method in Java?
How to check Java version?
What is a Class/Static Variables?
Convert given time in String format to seconds
What is the Difference between Path and ClassPath in java?
Memory Allocation in Java
Can we declare a static variable within a method in java?
What are the important features of Java 8?