When you do not have access to instantiate a class through a factory or so, one possible way is to declare an inner private class which extends the class to be instantiated.
For example, we have a class "Vehicle" which is marked abstract and hence cannot be instantiated directly. There is a "VehicleFactory" which is meant for giving an instance of this class.
Now, I want to to create an instance of "Vehicle" class in my class without using VehicleFactory. Here is how:
public class Myclass{
private MyVehicle myVehicle = new MyVehicle();
private class MyVehicle extends Vehicle{
}
public static void main(String args[]){
Myclass myClass = new Myclass();
myClass.myMethod();
}
public void myMethod(){
myVehicle.drive();
}
}
Can you think of some advantage of this kind of usage ?
Subscribe to:
Post Comments (Atom)
0 comments:
Post a Comment