Java - Multiple decorators do not work - java

I'm currently experimenting with decorators. I created a Tank class and two decorators: DoubleGunTank (shoots more powerfully) and FasterTank (drives faster). Here they are:
public class Tank {
public int shoot() {
return 100;
}
public int drive() {
return 10;
}
}
public class FasterTank extends Tank {
protected Tank fTank;
public FasterTank(Tank tank) {
fTank = tank;
}
public int drive() {
return fTank.drive() * 2;
}
}
public class DoubleGunTank extends Tank {
protected Tank fTank;
public DoubleGunTank(Tank tank) {
fTank = tank;
}
public int shoot() {
return fTank.shoot() * 2;
}
}
What I'm trying to do is decorate one tank with both double gun and the super speed. So I do it like this:
Tank czolg = new Tank();
czolg = new FasterTank(czolg);
czolg = new DoubleGunTank(czolg);
System.out.println("Shoot: "+czolg.shoot());
System.out.println("Drive: "+czolg.drive());
But the result is:
Shoot: 200
Drive: 10
It seems that only one decorator activates both methods from the DoubleGunTank class. So my question is: how do I get the tank to shoot more powerfully and drive faster at the same time?

All your decorators need to override all decorated object's methods:
class FasterTank extends Tank {
protected Tank fTank;
public FasterTank(Tank tank) {
fTank = tank;
}
public int drive() {
return fTank.drive() * 2;
}
//crucial!
public int shoot() {
return fTank.shoot();
}
}
class DoubleGunTank extends Tank {
protected Tank fTank;
public DoubleGunTank(Tank tank) {
fTank = tank;
}
public int shoot() {
return fTank.shoot() * 2;
}
//crucial!
public int drive() {
return fTank.drive();
}
}
Here's why: when you have:
Tank czolg = new DoubleGunTank(new FasterTank(new Tank()));
and you call czolg.drive() it actually calls a method of DoubleGunTank class - which is inherited without any change from Tank. So instead of using decorated method of target fTank you are calling untouched method of DoubleGunTank.
Note that you can avoid such issues by using Tank interface - which will force you to always decorate all methods. Also if your target Tank class has some state or performs some operations in constructor, each decorator (inheriting from it) will have this state duplicated and will call the same code in constructor.
UPDATE (suggested by OP himself):
Alternatively you can use abstract TankDecorator class as below:
abstract class TankDecorator extends Tank {
protected final Tank fTank;
protected TankDecorator(Tank fTank) {
this.fTank = fTank;
}
#Override
public int shoot() {
return fTank.shoot();
}
#Override
public int drive() {
return fTank.drive();
}
}
class FasterTank extends TankDecorator {
public FasterTank(Tank tank) {
super(tank);
}
public int drive() {
return fTank.drive() * 2;
}
}
class DoubleGunTank extends TankDecorator {
public DoubleGunTank(Tank tank) {
super(tank);
}
public int shoot() {
return fTank.shoot() * 2;
}
}
I run across this issue when using cglib proxies in spring - also exploiting decorator pattern by inheriting from my class. The base class constructor is called twice. See: CGLIB proxy method calls constructor twice? and Spring AOP creates extra bean.

Not quite sure about the Decorator pattern but czlog.drive() invokes Tank.drive() because DoubleGunTank does not override it.
You need to override every method in the superclass and delegate it to the contained fTank for this to work like you want it to.

I've found that when you're using the Decorator pattern with concrete classes, this is a common issue. That's why i tend to decorate interfaces, however, if you need to decorate concrete classes, it's usually helpful to have a base class for this:
public class DecoratedTank extends Tank {
private Tank delegate;
public DecoratedTank(Tank delegate) {
this.delegate = delegate;
}
#Override
public int shoot() {
return delegate.shoot();
}
#Override
public int drive() {
return delegate.drive();
}
}
Then to do your double gun tank:
public class DoubleGunTank extends DecoratedTank {
public DoubleGunTank(Tank delegate) {
super(delegate);
}
#Override
public int shoot() {
return 2 * super.shoot();
}
}

Related

There is no available constructor in the superclass (Java)

I have one super class, which called game that. It looks like this:
import java.util.ArrayList;
public class Game {
private ArrayList<Enemy> enemies = new ArrayList<Enemy>();
private ArrayList<Tower> towers = new ArrayList<Tower>();
private int corridorLength;
private int currentPosition = 0;
public Game(int corridorLength){
this.corridorLength = corridorLength;
}
public void addTower(int damage,int timeStep){
this.towers.add(new Tower(damage,timeStep)); // Add tower with
current position corrdor length
}
public void addEnemy(int health, int speed){
this.enemies.add(new Enemy(health,speed));
}
public void advance(){
this.currentPosition = this.currentPosition + 1;
if(this.currentPosition == this.corridorLength){
System.out.println("Game Over");
}
}
public void printDamage(){
System.out.println(this.towers.get(this.currentPosition));
}
}
The main focus is on the public void addTower(int, int)
So, I have a subclass called Tower:
public class Tower extends Game {
public Tower(int damage, int timeStep){
super.addTower(damage,timeStep);
}
public void getDamage(){
super.printDamage();
}
}
And subclass of the Tower subclass called Catapult:
public class Catapult extends Tower {
public Catapult(){
super(5,3);
}
}
I am new to Java and can't see what am I doing wrong here. Why do I need a default constructor for the Tower in the Game?
You need to explicitly declare default constructor in Game class.
public Game (){}
Since, Object instantiation chained to Object class during that, it will call its super class constructor. You have explicitly declared arg-constructor in Game, so default constructor won't be added automatically.

Decorator pattern with varying contract

In the decorator pattern, I'm confused about how to use a decorator method. I have learned that the decorator pattern is used to add functions to base-class. But I could call only the outermost decorator's method, so how should I use inner-decorator's method, if it not mentioned in interface. I'm not good at English, so I write code to demonstrate my question.
public class OrderSystem {
public static void main(String[] args) {
Pancakes pancakes = new MixedPancakes();
pancakes = new Ham(pancakes);
((Ham) pancakes).hamState(); // call hamState
pancakes = new Egg(pancakes);
((Egg) pancakes).eggState();
// i can't call hamState() there because it not belong to Egg
Pancakes pancakes1 = new Ham(new Egg(new FlourPancakes()));
// similarly, i can't use eggState() there.
System.out.println("订单:" + pancakes1.getDescription());
System.out.println("价格:" + pancakes1.cost());
}
}
interface Pancakes {
public abstract String getDescription();
public abstract int cost();
}
abstract class Seasoning implements Pancakes {
#Override
public abstract String getDescription();
}
class Ham extends Seasoning {
Pancakes pancakes;
public Ham(Pancakes pancakes) {
this.pancakes = pancakes;
}
#Override
public int cost() {
return pancakes.cost() + 2;
}
#Override
public String getDescription() {
return pancakes.getDescription() + "+火腿";
}
public void hamState() {
System.out.println("火腿切碎");
}
}
class Egg extends Seasoning {
Pancakes pancakes;
public Egg(Pancakes pancakes) {
this.pancakes = pancakes;
}
#Override
public int cost() {
return pancakes.cost() + 1;
}
#Override
public String getDescription() {
return pancakes.getDescription() + "+鸡蛋";
}
public void eggState() {
System.out.println("鸡蛋打碎");
}
}
class MixedPancakes implements Pancakes {
#Override
public String getDescription() {
return "五谷杂粮煎饼";
}
#Override
public int cost() {
return 6;
}
}
class FlourPancakes implements Pancakes {
#Override
public String getDescription() {
return "白面煎饼";
}
#Override
public int cost() {
return 5;
}
}
As I asked in annotation, when a decorator was wrapped with another, only the method that declared in interface (like cost() and getDescription()) will work, and the other method won't be called anymore. I thought if I create a soldier, if I use a gun decorate he will be shoot()--the gun's function. If I decorate him with sword tomorrow, he will not only could shoot() but also cut()--the sword's function. Can I achieve it with decorator pattern?
I'm sorry for any misunderstandings and thanks for your help.
As people mentioned in comments in your question, the decorator pattern is not used exactly like that.
Using your soldier example, the decorator would work like this:
public abstract class Soldier {
public abstract void attack();
}
public abstract class SoldierDecorator extends Soldier {
protected Soldier soldier;
public SoldierDecorator(Soldier soldier) {
this.soldier = soldier;
}
#Override
public abstract void attack();
}
and then
public class SoldierWithGun extends SoldierDecorator {
public SoldierWithGun(Soldier soldier) {
super(soldier);
}
#Override
public void attack() {
soldier.attack();
shootWithTheGun();
}
private void shootWithTheGun() {
System.out.println("Shooting with the gun...");
}
}
public class SoldierWithSword extends SoldierDecorator {
public SoldierWithSword(Soldier soldier) {
super(soldier);
}
#Override
public void attack() {
soldier.attack();
cutWithSword();
}
private void cutWithSword() {
System.out.println("Cutting with the sword...");
}
}
Passing your soldier from decorator to decorator would enhance their attack;
Now to add behavior/methods, you can use plain old inheritance.
You could add behavior by extending classes, BaseSoldier can walk but SoldierWithGun extends BaseSoldier, adds a method to shoot besides walking.
You can use interfaces to ensure that certain functionalities are available in classes that implement them.
It is not exactly "decorating" as you want, but I think this is the way to go for what you want to do.

Constructor to interface/abstract class using Java generics

Please notice the updates, my question was not clearly formulated. Sorry for that.
Let us assume we have the following code:
class Foo extends/implements AnAbstractClass/AnInterface { /* to make sure the constructor with int as input is implemented */
Foo(int magicInt) { magicInt + 1; /* do some fancy calculations */ }
}
class Bar extends/implements AnAbstractClass/AnInterface { /* to make sure the constructor with int as input is implemented */
Bar(int magicInt) { magicInt + 2; /* do some fancy calculations */ }
}
class Factory<T extends/implements AnAbstractClass/AnInterface> {
int magicInt = 0;
T createNewObject() {
return new T(magicInt) // obviously, this is not working (*), see below
}
}
/* how it should work */
Factory<Foo> factory = new Factory<Foo>();
factory.createNewObject() // => Foo with magicInt = 1
Factory<Bar> factory = new Factory<Bar>();
factory.createNewObject() // => Bar with magicInt = 2
At position (*) I don't know what to do. How can I make sure, that the constructor with a signature like this ...(int magicInt) is implemented? I cannot define
a constructor with a certain signature in an interface
interface AnInterface {
AnInterface(int magicInt);
}
an abstract class enforcing a certain constructor
abstract class AnAbstractClass {
abstract AnAbstractClass(int magicInt);
}
and this is obviously missing the requirement of an implemented constructor in the subclasses:
abstract class AnAbstractClass {
AnAbstractClass(int magicInt) {}
}
a static method within an interface or abstract class, which can be overridden for each implementation of AnInterface or AnAbstractClass (I think of a factory pattern)
What is the way to go?
I really don't see your idea working.
I feel it breaks the concept of the Factory pattern, which really aims at having a method responsible for creating instances of a single class see ref.
I would rather:
have one method in your factory class for each type of object you want to construct
and possibly instead of having the specific behaviour in constructors, have one common constructor in a parent abstract class and one abstract method that does the fancy computation (but that's really style preference).
Which would result in something along the lines of:
abstract class AbstractSample {
private int magicInt;
public AbstractSample(int magicInt) {
this.magicInt = magicInt;
}
protected int getMagicInt() {
return magicInt;
}
public abstract int fancyComputation();
}
public class Foo extends AbstractSample {
public Foo(int magicInt) {
super(magicInt)
}
public int fancyComputation() {
return getMagicInt() + 1;
}
}
public class Bar extends AbstractSample {
public Bar(int magicInt) {
super(magicInt)
}
public int fancyComputation() {
return getMagicInt() + 2;
}
}
public class SampleFactory {
private int magicInt = 0;
public Foo createNewFoo() {
return new Foo(magicInt);
}
public Bar createNewBar() {
return new Bar(magicInt);
}
}
Answer to the previous version of the question might be deleted if the updated answer satisfies the OP
It's definitely weird to have classes that both extend Sample and implement SampleFactory...
I would rather have something along the lines of:
class Sample {
protected Sample() { /* ... */ }
}
interface SampleFactory<T extends Sample> {
T createSample(final int i);
}
class AccelerationSample extends Sample {
public AccelerationSample(final int i) { /* do some fancy int calculations*/ }
}
class OrientationSample extends Sample {
private OrientationSample (final int i) { /* do some fancy int calculations*/ }
}
abstract class SampleSource<T extends Sample> {
int magicInt;
SampleFactory<T> sampleFactory;
T getCurrentSample() {
return sampleFactory.createSample(magicInt);
}
}
class AccelerationSampleSource extends SampleSource<AccelerationSample> {
SampleFactory<AccelerationSample> sampleFactory = new SampleFactory<> {
public AccelerationSample createSample(final int i) {
return new AccelerationSample(i);
}
}
}
class OrientationSampleSource extends SampleSource<OrientationSample> {
SampleFactory<OrientationSample> sampleFactory = new SampleFactory<> {
public OrientationSample createSample(final int i) {
return new OrientationSample(i);
}
}
}
It would be cleaner still to use named factories, such as
public AccelerationSampleFactory implements SampleFactory<AccelerationSample> {
public AccelerationSample createSample(final int i) {
return new AccelerationSample(i);
}
}
Which you could then use as
class AccelerationSampleSource extends SampleSource<AccelerationSample> {
SampleFactory<AccelerationSample> sampleFactory = new AccelerationSampleFactory();
}
It sounds like you're really looking for a solution to how to write a generic factory method without a bunch of if/else blocks and without writing one in each class. As such, consider using reflection as in the following code:
interface Interface {
}
class Foo implements Interface {
Foo(int magicInt) { magicInt = magicInt + 1; /* do some fancy calculations */ }
}
class Bar implements Interface {
Bar(int magicInt) { magicInt = magicInt + 2; /* do some fancy calculations */ }
}
class Factory<T extends Interface> {
int magicInt = 0;
public T createNewObject(Class<T> typeToMake) {
try {
T t = createNewObjectWithReflection(typeToMake);
return t;
} catch (Exception e) {
throw new RuntimeException("Construction failed!", e);
}
}
private T createNewObjectWithReflection(Class<T> typeToMake) throws Exception {
// find the constructor of type to make with a single int argument
Constructor<T> magicIntConstructor = typeToMake.getDeclaredConstructor(Integer.TYPE);
// call the constructor with the value of magicInt
T t = magicIntConstructor.newInstance(magicInt);
return t;
}
}
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
Factory<Foo> fooFactory = new Factory<Foo>();
Foo foo = fooFactory.createNewObject(Foo.class);
System.out.println(foo);
Factory<Bar> barFactory = new Factory<Bar>();
Bar bar = barFactory.createNewObject(Bar.class);
System.out.println(bar);
}
}
You can run the demo at IDEOne here.
As you have noted, none of the 3 ideas in the question are supported (a constructor with a certain signature in an interface, an abstract class enforcing a certain constructor, or a static method within an interface or abstract class)
However, you can define an interface (or abstract class) that is a Factory for the type that you ultimately want.
public interface AnInterface {
int fancyComputation();
}
public interface IFooBarFactory<T extends AnInterface> {
T create(int magicNumber);
}
IFooBarFactory has 2 concrete implementations
public class BarFactory implements IFooBarFactory<Bar> {
public Bar create(int magicNumber) {
return new Bar(magicNumber);
}
}
public class FooFactory implements IFooBarFactory<Foo> {
public Foo create(int magicNumber) {
return new Foo(magicNumber);
}
}
Then use the strategy pattern (https://en.wikipedia.org/wiki/Strategy_pattern) to retrieve the correct factory. Then use this factory, which has a known interface, to manufacture your object with the correct value (and any additional values that are required to manufacture an object).
FooBarFactory fooBarFactory = new FooBarFactory();
IFooBarFactory<T> factory = fooBarFactory.createFactory(typeOfAnInterface);
T impl = factory.create(magicNumber);
With the conrete implementations
public class Bar implements AnInterface {
private final int magicInt;
public Bar(int magicInt) {
this.magicInt = magicInt;
}
public int fancyComputation() {
return magicInt + 2;
}
}
public class Foo implements AnInterface {
private final int magicInt;
public Foo(int magicInt) {
this.magicInt = magicInt;
}
public int fancyComputation() {
return magicInt + 1;
}
}
the following code:
public static void main(String ... parameters) {
test(Foo.class);
test(Bar.class);
}
private static <T extends AnInterface> void test(Class<T> typeOfAnInterface) {
T impl = createImplForAnInterface(typeOfAnInterface, 10);
System.out.println(typeOfAnInterface.getName() + " produced " + impl.fancyComputation());
}
private static <T extends AnInterface> T createImplForAnInterface(Class<T> typeOfAnInterface, int magicNumber) {
FooBarFactory fooBarFactory = new FooBarFactory();
IFooBarFactory<T> factory = fooBarFactory.createFactory(typeOfAnInterface);
T impl = factory.create(magicNumber);
return impl;
}
prints
Foo produced 11
Bar produced 12
This provides a number of benefits over a solution with introspection or static factories. The caller does not need to know how to manufacture any of the objects, nor is the caller required to know or care when method is the "correct" method to use in order to retrieve the correct type. All callers simply call the one public/known component, which returns the "correct" factory. This makes your callers cleaner because they are no longer tightly coupled to the concrete implementations of AnInterface for the types FooBar. They only need to be concerned with "I need an implementation of AnInterface, which consumes (or processes) this type." I know that this means you have two "factory" classes. One to retrieve the correct factory, and the other which is actually responsible for creating the concrete types Foo and Bar. However, you hide this implementation detail from the callers through an additional layer of abstraction (see the createImplForAnInterface method).
This approach will be particularly beneficial if you are generally using some form of dependency injection. My recommendation with correspond exactly to Guice's assisted inject (https://github.com/google/guice/wiki/AssistedInject) or a similar idea in Spring (Is it possible and how to do Assisted Injection in Spring?).
This means that you need to have several factory classes (or dependency injection binding rules for Guice) but each of these classes are small, simple, and easy to maintain. Then you write a small test that retrieves all classes that implement AnInterface and you verify that your component which implements the strategy-pattern has covered all cases (through reflection - I would use the Reflections class in org.reflections:reflections). This gives you a usable code-abstraction that simplifies the use of these objects by reducing redundant code, loosening a tight coupling of components, and not sacrificing polymorphism.

Is this a good implementation of interfaces?

I got this question about the best practice to using interfaces. Please, look at this code:
These are the interfaces:
public interface Vehicle {
public int getAcceleration();
}
public interface Flying extends Vehicle {
public int getAltitude();
public void up(int seconds);
public void down(int seconds);
}
public interface Runner extends Vehicle {
public int getSpeed();
public void accelerate(int seconds);
public void decelerate(int seconds);
}
This would be the implementation for the interface Runner:
public class RunnerImplementation implements Runner {
Vehicle vehicle;
int speed;
public RunnerImplementation(Vehicle v) {
vehicle = v;
}
#Override
public int getAcceleration() {
return vehicle.getAcceleration();
}
#Override
public int getSpeed() {
return speed;
}
#Override
public void accelerate(int seconds) {
speed += seconds * getAcceleration();
}
#Override
public void decelerate(int seconds) {
speed -= seconds * getAcceleration();
}
}
This would be the implementation for the interface Flying:
public class FlyingImplementation implements Flying {
Vehicle vehicle;
int altitude;
public FlyingImplementation(Vehicle v) {
vehicle = v;
}
#Override
public int getAcceleration() {
return vehicle.getAcceleration();
}
#Override
public int getAltitude() {
return altitude;
}
#Override
public void up(int seconds) {
altitude += seconds * getAcceleration();
}
#Override
public void down(int seconds) {
altitude -= seconds * getAcceleration();
}
}
And this would be the result, the FlyingCar class:
public class FlyingCar extends BaseVehicle implements Flying, Runner {
Flying flying = null;
Runner runner = null;
public FlyingCar() {
flying = new FlyingImplementation(this);
runner = new RunnerImplementation(this);
}
#Override
public int getSpeed() {
return runner.getSpeed();
}
#Override
public void accelerate(int seconds) {
runner.accelerate(seconds);
}
#Override
public void decelerate(int seconds) {
runner.decelerate(seconds);
}
#Override
public int getAltitude() {
return flying.getAltitude();
}
#Override
public void up(int seconds) {
flying.up(seconds);
}
#Override
public void down(int seconds) {
flying.down(seconds);
}
}
As you can see:
I implemented each interface creating the classes RunnerImplementation and FlyingImplementation.
Each implementation needs to know the current object to know its acceleration, I'm passing an Vehicle object as parameter to the constuctors.
I defined Runner and Flying as extensions from Vehicle, because I want to show that they are related semantically, but this force me to implementing twice the method getAcceleration(). It's easy for one method, but if Vehicle had 100 methods, I have a problem... My first thought is that neither Runner nor Flying should to extend from Vehicle, but I will lose the semantic relation.
My questions:
Is a good practice to implement the interfaces as I did it with RunnerImplementation and FlyingImplementation to be used in the class FlyingCar?
Is there a better way to implement this?
TIA,
I would just make FLyingCar implement Flying and Runner since it will also implement Vehicle (both interfaces extend it). I don't see the point of implementing interfaces just to use implementations as base classes for other classes (unless you will have large number of different object types).

Calling method from abstract class

I have the following abstract class
public abstract class ReturnAgentFromTab extends BasePage{
#Persist("session")
public abstract Agent getAgent();
public abstract void setAgent(Agent agent);
#InjectObject("spring:agentApplicationModeResolver")
public abstract AgentApplicationModeResolver getAgentApplicationModeResolver();
.... more #InjectObject()
public void nextPage(IRequestCycle cycle) {
setApplicationModeUsingAgentStatus(getAgent());
AgentSearchNavigationManager navManager = getAgentSearchNavigationManagerFactory().getAgentSearchNavigationManager();
FlowStage stage = getFlowStage();
if (stage == null) {
setApplicationModeUsingAgentStatus(getAgent());
stage = getUserDefaultFlowStageService().getDefaultFlowStage(UserHolder.getUser(), getVisitClass().getApplicationMode());
}
Class nextPageClass = navManager.getNextPage(getUserDefaultFlowStageService());
String nextPageQualifier = getUserDefaultFlowStageService().getPageQualifier(getAgent(), nextPageClass, getVisitClass().getApplicationMode());
IPage nextPage = getPageUtils().getPage(nextPageClass, nextPageQualifier);
if ((getFlowStage() instanceof PSDFlowStage)) {
nextPageQualifier = getFlowStage().getValue();
}
nextPage = getPageUtils().getPage(nextPageClass, nextPageQualifier);
if (navManager instanceof NameBasedAgentSearchNavigationManager && nextPageClass != SignOffStatusPage.class) {
NameBasedAgentSearchNavigationManager nameBasedNavManager = (NameBasedAgentSearchNavigationManager) navManager;
String nextPageName = nameBasedNavManager.getNextPageName(stage);
if (!nextPageName.equals(nextPageClass.getSimpleName())) {
nextPage = getPageUtils().getPage(nextPageName, nextPageQualifier);
}
}
if (isNextPageActivateAgentGeneral(nextPage)) {
initialisePageLink(nextPageClass, nextPage);
}
((WuamsBasePage) nextPage).init(getAgent().getAgentId());
getPageUtils().navigateTo(nextPage);
}
private void setApplicationModeUsingAgentStatus(Agent agent) {
getVisitClass().setApplicationMode(getHomeLinksFactory().getRegionHomeLinksService().getApplicationMode(agent));
}
private boolean isNextPageActivateAgentGeneral(IPage nextPage) {
return nextPage instanceof ActiveAgentGeneralPage;
}
private void initialisePageLink(Class nextPageClass, IPage nextPage) {
if (getVisitClass().getPageLink() == null) {
getVisitClass().setPageLink(PageLinkUtil.getPageLinkMessageKeyFromPageClass(nextPageClass,
getUserDefaultFlowStageService().getDefaultFlowStage(UserHolder.getUser(), getVisitClass().getApplicationMode()).getValue()));
}
}
}
What I want to do is call my nextPage(cycle) from another class that is abstract and extends ReturnAgentFromTab, but when I try
public abstract class DoSomethingWithAgent extends ReturnAgentFromTab {
#Persist("session")
public abstract ReturnAgentFromTab getReturnAgentFromTab();
public abstract void setReturnAgentFromTab(ReturnAgentFromTab returnAgentFromTab);
....
getReturnAgentFromTab().nextPage(cycle);
I get a null pointer exception, I know this is because I am not actually setting ReturnAgentFromTab anywhere but I do not understand how to set it using abstract classes. Can anybody help?
If ye need more code just ask
The point of abstract classes is to simply not implement certain things, such as providing certain objects. The method getReturnAgentFromTab() is a perfect example: the class itself does not care where that object comes from because that is the sole responsibility of the subclass. So extend that class, write that method, and all of a sudden the base class does its thing.
well, you cant intialize abstract class, the only way is to make some other concrete class extend your abstract class, and call the non abstract method with the concrate classes instance.
abstarct class ABS1 {
//abstract methods
//concreate method
public void concMethod() {
}
}
public class ABS1Impl extends ABS1 {
//implement all the abstract methods
}
public abstract class ABS2 {
ABS1 abs = new ABSImpl();
abs.concMethod //
}

Categories