Recently I'm thinking about making my own Date library. And I'm finding a problem here, here it is:
How do I hide a superclass method in subclass? So it won't be detected in subclass.
Example: I have a class that extends to Date, and another class that extends to the previous class. In my new subclass, it detects all the methods from Date, like getDate etc. What I want is that in my subclass all the methods from Date are undetected, not throwing an exception, but completely undetected.
Thanks in advance :)
Method hiding can be defined as, "if a subclass defines a static method with the same signature as a static method in the super class, in such a case, the method in the subclass hides the one in the superclass." The mechanism is known as method hiding. It happens because static methods are resolved at compile time.
Method hiding may happen in any hierarchy structure in java. When a child class defines a static method with the same signature as a static method in the parent class, then the child's method hides the one in the parent class. To learn more about the static keyword, this write-up is a good place to start.
In method hiding, you can hide the implementation of the methods of a base class from the derived class using the new keyword. Or in other words, in method hiding, you can redefine the method of the base class in the derived class by using the new keyword.
It depends on the type of Superclass, if it's an Abstract class you must override all your method. For concrete class, you only have to override what is required.
Favour Composition over Inheritance here.
Instead of inheriting a Date have it as a member field inside your MyDate class.
public class MyDate {
private Date dt = new Date();
// no getDate() available
public long getTime() {
return date.getTime();
}
}
You get complete control over the Date API that's visible to your subclasses (without the need to throw any exceptions) but this approach is more practical when the methods you want to hide outnumber the ones you want to remain accessible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With