Amazon Interview Question
SDE1sCountry: India
Interview Type: In-Person
There are several clarifications need to be asked for:
1. Is the constructor(s) of the Base class private?
2. Are the methods public static ?
3. Is the class an abstract class?
4. If the class is concrete and public and default constructor is publicly available, there is NO way you can hide its public methods.
Overriding base class method with weaker access level is not allowed in Java and .Net.
Vice-versa is still possible (unless the access modifier is not private, even though you can create a method with same name it is not overriding in true sense).
A typical scenario where this seems to be required is encapsulating 3rd Party APIs.
{class Base {
protected void display(){
System.out.println("Display in base class");
}
}
class Derived1 extends Base {
@Override
protected void display() {
try {
super.getClass().getMethod("display", null).setAccessible(false);
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
}
public class ClassMethodTest {
/*
* Base class is given you need to stop
* exposing the base class methods without
* touching the base class at all.
*/
public static void main(String[] args) {
Base der = new Derived1();
der.display();
}
}}
{class Base {
protected void display(){
System.out.println("Display in base class");
}
}
class Derived1 extends Base {
@Override
protected void display() {
try {
super.getClass().getMethod("display", null).setAccessible(false);
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
}
public class ClassMethodTest {
/*
* Base class is given you need to stop
* exposing the base class methods without
* touching the base class at all.
*/
public static void main(String[] args) {
Base der = new Derived1();
der.display();
}
}}
Base class creates contract with sub classes, because of it, you can't hide base class methods.
You may try this variants:
1) override base class method. smth like :
2) create interface for sub class, like
and make other code work with ISubClass
- GK June 07, 2014