How can I override the “calculate()” method in subclasses?
While engaging with the Java-based project I created a superclass by using the method which is known as “calculate()” which can perform internal calculations. Now I have extended this particular superclass to various subclasses. Explain to me if it is possible to override the “calculate()” method in the subclasses or not, if not is there any alternative approach available?
In the context of Java programming language, private methods cannot be overridden in a subclass as these are not visible outside the class in which they are declared. Hence, they are not accessible to subclass and when you try to override them it gives the result in a error of compilation.
Here is the example given to showcase the concept:-
Class Parent {
Private void display() {
System.out.println(“Parent’s display method”);
}
Public void callDisplay() {
Display(); // Accessing within the same class
}
}
Class Child extends Parent {
Private void display() {
System.out.println(“Child’s display method”);
}
Public void callDisplay() {
Display(); // This method hides the superclass’s display method
Super.callDisplay(); // Accessing superclass’s display method
}
}
Public class Main {
Public static void main(String[] args) {
Child child = new Child();
Child.callDisplay();
}
}
However, there is one method available by which the private method can be overridden. It has a similar outcome and would not violate the encapsulation. This method is known as a package-private method in the superclass. Unlike above, this method is visible to the superclass within the same package.
Here is the example given by using the protected method:-
// Superclass in package ‘example’
Package example;
Class Parent {
Void display() { // package-private access level
System.out.println(“Parent’s display method”);
}
Void callDisplay() {
Display(); // Accessing within the same package
}
}
// Subclass in the same package ‘example’
Package example;
Class Child extends Parent {
Void display() {
System.out.println(“Child’s display method”);
}
Void callDisplay() {
Display(); // This method hides the superclass’s display method
Super.callDisplay(); // Accessing superclass’s display method
}
}
// Main class in the same package ‘example’
Package example;
Public class Main {
Public static void main(String[] args) {
Child child = new Child();
Child.callDisplay();
}
}