A-SM A-SM - 1 year ago 91
Java Question

How to completely hide superclass method in Java

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.

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 :)

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download