Reputation: 884
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 :)
Upvotes: 19
Views: 14429
Reputation: 1942
You can't hide it if it is extended, but you can override.
if you want your API user to not use the method I suggest a override and just throw this exception:
UnsupportedOperationException
but looking at what you wrote, you should consider making Date a field in your class, not extend the class.
Upvotes: 12
Reputation: 49
Override the method and make it static, it will hide the method of super class
Upvotes: 0
Reputation: 649
Not possible.
If what you want was possible, then inherintence would be broken. Suddenly, when you use a certain IS-A type of Date
, you would not be able to call any Date
type methods. This is wrong on several levels. For example, it breaks the Liskov Substitution Principle.
Upvotes: 7
Reputation: 51721
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.
Upvotes: 40
Reputation: 54722
you can use Delegation instead
public class NewDate{
Date d;
NewDate(){
d = new Date();
}
methodsYouWantToChange(){
// new implementation
}
methodsYouDontWantToChange(){
d.methodsYouDontWantToChange();
}
newMethods(){
// new implementation
}
}
Upvotes: 5