Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to completely hide superclass method in Java

Tags:

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.

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

like image 746
A-SM Avatar asked May 31 '13 21:05

A-SM


People also ask

How do I hide a superclass method?

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.

How method hiding can be done in Java?

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.

How do you hide a method?

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.

Can all superclass methods be overridden?

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.


1 Answers

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.

like image 181
Ravi K Thapliyal Avatar answered Oct 16 '22 04:10

Ravi K Thapliyal