I'm trying to check if class A that is extending class B is instance of certain interface.
Basically here is my setup:
public class House
{
(variables)
public House(variables) {...}
}
public class Kitchen extends House implements IFurniture
{
(variables)
public Kitchen(variables)
{
super(variables);
}
}
public class Bathroom extends House implements IWalls
and so on...
And I have a method where I'm getting a casted, House version of Kitchen and Bathroom.
I basically want to do this:
public boolean hasFurniture(House house)
{
if (house instanceof IFurniture){return true;}
}
Do I need to use house.getClass().getInterfaces() and would that even work considering that the argument has been casted?
The problem is that I'm writing a mod for a game and I can't edit games classes. Only only Kitchen, Bathroom and hasFurniture can be edited in this case.
Also ignore my class names, they are just example names so that you don't confuse Classes accidentally.
You're wasting the benefits of polymorphism. You don't want to use an interface with instanceof to check if an object has a property. implements and extends mean IS-A, not HAS-A. You clearly want the latter. Do it like this instead:
public interface IFurniture {
public boolean hasFurniture();
}
public class House implements IFurniture
{
(variables)
public House(variables) {...}
#Override
public boolean hasFurniture() {
return false;
}
}
public class Kitchen extends House
{
(variables)
public Kitchen(variables)
{
super(variables);
}
#Override
public boolean hasFurniture() {
return true;
}
}
EDIT: Also, Eran is right to point out that this hierarchy doesn't make a huge amount of sense in the first place -- but that's a larger issue.
Let's work with a more understandable class hierarchy.
You're thinking about the instanceof issue like this:
public class Person{
public void die(){
System.out.println(this + " died");
}
public void pushOffCliff(){
if(this instanceof Flyable)
Flyable f = (Flyable)this;
f.fly();
else
die();
}
}
public interface Flyable{
public void fly();
}
public class Superhero extends Person implements Flyable{
public void fly(){
System.out.println("Up, up, and away!");
}
}
When it makes much more sense to use the class extension and overriding system like Patrick does in his answer, like below. People (that are truly just people and not superheroes) don't fly. When pushed off a cliff, they should die. So the person class shouldn't deal with the "what if I'm not truly a person, I'm actually an ...." possibility; let the sub classes deal with that.
public class Person{
public void die(){
System.out.println(this + " died");
}
public void pushOffCliff(){
die();
}
}
public interface Flyable{
public void fly();
}
public class Superhero extends Person implements Flyable{
public void fly(){
System.out.println("Up, up, and away!");
}
#Override
public void pushOffCliff(){
fly();
}
}
I just solved it, thanks to Eran.
My problem was that I was casting a wrong element.
In this case I was casting ItemStack (Item with additional data) instead of Item.
By adding just .getItem() I have hopefully solved the problem.
Thank you for helping, have a nice day!
Related
I'm working with students in my Java class on a simple Zork-like environment in which the player goes from location to location encountering items. The items should have dynamic behaviors, so that a book is readable until you burn it, or a duck can fly until it flies too long and tires out. And so on.
The students and I have grokked the basic Strategy pattern (I'm adapting from Head First Design Patterns, and leaving out boilerplate):
public class Duck {
String name;
Int health;
FlyBehavior flyBehavior;
public void performFly() {
flyBehavior.fly();
}
public void setFlyBehavior(FlyBehavior f) {
flyBehavior = f;
}
}
public interface FlyBehavior {
public void fly();
}
public class FlyGracefully implements FlyBehavior {
public void fly() {
System.out.println("I fly so gracefully!");
}
}
public class TooTiredToFly implements FlyBehavior {
public void fly() {
System.out.println("I'm too tired to fly.");
}
}
Sparing the details of the main method, this lets us switch different flying behaviors into our Duck. This is easy because it returns a void and prints to sysout.
But what if we need the behavior to interact with the state of the Duck? Let's say that:
When the duck becomes too tired to fly, its name changes to "Exhausted Duck." Other behaviors can change its name, too.
When the duck is attacked (gonna happen), its health goes down. When its health is too low, its flyBehavior switches out to the TooTiredToFly behavior.
But I'm assuming that dynamic behaviors, at least in this pattern, have no access to the state of the object they're in.
Is there a general strategy for creating dynamic behaviors that interact with the state of the object they're in? I would like to teach something comprehensible, so put yourself in the mind of intermediate-level high school programmers.
Based on my comment above, something along these lines...
// Creating an interface for flyable things e.g. Duck, Airplane, etc.
// You don't have to do this. You could just pass your Duck
// object instead and call its methods directly.
public interface Flyable {
void performFly();
}
public class Duck implements Flyable {
// All your Duck stuff as above in here.
}
public abstract class FlyBehavior {
private Flyable parent;
public FlyBehavior(Flyable parent) {
this.parent = parent;
}
public abstract void fly();
protected Flyable getParent() {
return this.parent;
}
}
public class FlyGracefullyBehavior extends FlyBehavior {
public FlyGracefullyBehavior(Flyable parent) {
super(parent);
}
#Override
public void fly() {
// Now you can get access to the original parent here.
Flyable parent = this.getParent();
}
}
public class TooTiredToFlyBehavior extends FlyBehavior {
public TooTiredToFlyBehavior(Flyable parent) {
super(parent);
}
#Override
public void fly() {
// Now you can get access to the original parent here.
Flyable parent = this.getParent();
}
}
Or, you could simply pass parent state in the fly method of your FlyBehavior classes i.e. behavior.fly(state); It's up to you :)
Here's a basic example of using the Strategy pattern as you have described. I'm trying to keep it as simple as possible so some best practices were ignored (e.g. declaring constants) so you can focus on the Strategy design and not be overwhelmed with information.
public interface Animal
{
public String getName();
public void attacked(int health);
}
public interface Bird extends Animal
{
public void fly();
}
public class Duck implements Bird
{
private Int health = 100;
private DuckBehavior state = new HealthyDuck();
public getName()
{
return state.getName();
}
public void fly()
{
state.fly();
}
public void attacked(int hitpoints)
{
health = health - hitpoints;
if (health < 50) {
state = new HurtDuck();
} else if (health < 0) {
state = new DeadDuck();
}
}
}
interface DuckBehavior
{
public getName();
public void fly();
}
public class HealthyDuck implements DuckBehavior
{
public getName()
{
return "Healthy Duck";
}
public void fly()
{
System.out.println("I fly so gracefully!");
}
}
public class HurtDuck implements DuckBehavior
{
public getName()
{
return "Hurt Duck";
}
public void fly()
{
System.out.println("I'm too tired to fly.");
}
}
public class DeadDuck implements DuckBehavior
{
public getName()
{
return "Dead Duck";
}
public void fly()
{
System.out.println("I'm too dead to fly.");
}
}
Lets add a new interface in the design as below
Flyable.java
public interface Flyable{
public void modifyTargetName(String newName);
}
Lets Modify the FlyBehavior.java and its implementation classes. Lets define a method public void setFlyableTarget( Flyable target ) in it.
FlyBehavior.java
public interface FlyBehavior {
public void fly();
public void setFlyableTarget( Flyable target );
}
FlyGracefully.java
public class FlyGracefully implements FlyBehavior {
public void fly() {
System.out.println("I fly so gracefully!");
}
public void setFlyableTarget( Flyable target ){
target.modifyTargetName("GraceFul Flyer");
}
}
TooTiredToFly.java
public class TooTiredToFly implements FlyBehavior {
public void fly() {
System.out.println("I'm too tired to fly.");
}
public void setFlyableTarget( Flyable target ){
target.modifyTargetName("TiredFlyer");
}
}
Duck.java let it implement Flyable.java
public class Duck implements Flyable{
String name;
Int health;
FlyBehavior flyBehavior;
public void modifyTargetName(String newName){
this.name = newName;
}
public void performFly() {
flyBehavior.fly();
}
public void setFlyBehavior(FlyBehavior f) {
flyBehavior = f;
f.setFlyableTarget(this);
}
}
The good thing here is we do not expose concrete implementation and hence code remains unit testable and good for adaptation to changes. It adheres to the DIP : Dependency Inversion Principle as well.
One general point I'd like to make: Don't modify internal behavior of an object, it's rude. I mean, there should not be a setFlyBehavior() method, that is an internal attribute of the Duck.
Also, think about who is responsible for what. Once a Duck is constructed, you can ask a Duck to fly, and you can make the Duck take Damage. How those things change the Duck is none of our business at that point.
On a more practical note, this is how that might look:
public interface Being {
boolean isDamaged();
}
public interface FlyingBehavior {
void fly();
}
public class GracefulFlyingBehavior implements FlyingBehavior {
...
}
public class TiredFlyingBehavior implements FlyingBehavior {
...
}
public class BirdFlyingBehavior implements FlyingBehavior {
private int tiredness;
...
public BirdFlyingBehavior(Being bird) {
...
}
#Override
public void fly() {
if (bird.isDamaged() || isTired()) {
tiredFlying.fly();
} else {
gracefulFlying.fly();
tiredness++; // Or whatever...
}
}
}
The point is, that the behavior itself should be responsible for deciding whether the flying can take place. It is after all the "strategy" for flying, so this logic needs to be there.
Then you can construct a duck something like this:
public Duck(String name, ... ) {
...
this.flyBehavior = new BirdFlyingBehavior(this);
}
or something similar. The point here is that once that strategy is set, it should stay internal to the Duck, there should be no way to modify that directly anymore.
Of course there might be additional features (you might want to move "tiredness" to the general "health" of a being), but the concepts should not change. Objects should hide their internal state, this requires "responsibilities" to be at the right place.
A subclass has a relationship that is described as IS-A with it base class, but a base class does not share this kind of relationship with it subclass. I was wandering what kind of relationship an interface have with it implementing class since an object of that class can be passed to interface object and the interface object can only access methods defined it concrete Interface.
public class main {
public static void main(String[]args){
Nigeria ng = new Nigeria(){};
//Interface object can accept Nigerias object which is not posible in Inheritance
Continent continent = ng;
//prints Country is in Africa
continent.Africa();
//continent.language(); will not compile language is not in the interface
//Print Democratic thought this should print Undefined since it is inialied with default.
continent.Goverment();
}
}
interface Continent{
public void Africa();
default void Goverment(){
System.out.println("Undefined");
}
}
class Nigeria implements Continent{
#Override
public void Africa(){
System.out.println("Country is in Africa");
}
public void language(){
System.out.println("Official Language is English");
}
public void Goverment(){
System.out.println("Democratic");
}
}
If you are looking for English-language analogues, an Interface is not an "Is a..." nor "Has a..." relationship, but more an "Is...".
An Interface is not about the class that uses it.
It's about the consumer that asks for it.
If you wanted to see it as anything, you could see it as an adjective.
"He is Responsible".
Well, what does he do?
He finishes tasks; he takes ownership of his mistakes; he makes them right.
Is he a pilot, is he a surgeon, is he a doctor?
Is he a child, a father, a greatGrandfather?
Do you care?
I need a responsible person, to help me do this job.
Does ResponsiblePerson inherit from PoliceOfficer? Does Lawyer inherit from ResponsiblePerson, because I'm sure there can be irresponsible lawyers.
class Lawyer extends Person { }
class ResponsibleLawyer extends Lawyer implements ResponsibleEntity { }
class NeedyPerson extends Person {
public void acceptHelp (ResponsibleEntity somebody) {
try {
somebody.attemptTask( someTask );
} catch (TaskCompletionError err) {
somebody.takeOwnership(err);
somebody.fixMistake(err);
}
}
}
Can corporations be Responsible too?
Perhaps we don't see it too often, but it's theoretically possible:
class LawFirm extends CorporateEntity { }
class BetterLawFirm extends LawFirm implements ResponsibleEntity { }
Can somebody be a responsible corporate body? Well, so long as that corporate body does all of the same things that the responsible person would otherwise do, sure.
In another example, you might have a Switchable interface.
Looking at that name, you could surmise that the thing you're being given has a switch which can be poked.
So what methods might it have?
on( )
off( )
toggle( )
isOn( )
sounds like a useful set to have.
What benefit is there to having an interface like this?
Well, now I know that I can deal with a switch, and its lineage doesn't matter.
If all I want is a class which takes a switch and does something with it, why do I need to create dozens of classes, just to accept my dozens of things with switches?
Or override methods into the dirt to do the same.
class SwitchThrower {
public void throwSwitch (CoffeeMaker coffeeMaker) { coffeeMaker.on(); }
public void throwSwitch (LightSwitch lightSwitch) { lightSwitch.on(); }
public void throwSwitch (GhostTrap ghostTrap) { ghostTrap.on(); }
public void throwSwitch (TheHeat theHeat) { theHeat.on(); }
public void throwSwitch (CarIgnition ignition) { ignition.on(); }
}
...
why not just:
class SwitchThrower {
public void throwSwitch (Switchable switch) { switch.on(); }
}
class LightSwitch implements Switchable {
private boolean currentlyOn;
public LightSwitch (boolean initiallyOn) {
currentlyOn = initiallyOn;
}
public LightSwitch () {
currentlyOn = false;
}
public boolean on () {
currentlyOn = true;
return currentlyOn;
}
public boolean off () {
currentlyOn = false;
return currentlyOn;
}
public boolean toggle (boolean forceOn) {
boolean state;
if (forceOn == true) {
state = on();
} else {
state = off();
}
return state;
}
public boolean toggle () {
boolean state;
if (isOn() == true) {
state = off();
} else {
state = on();
}
return state;
}
public boolean isOn () {
return currentlyOn;
}
}
...et cetera
As you can see, aside from describing a basic feature-set of the implementer, interfaces are not about the class at all, but rather the consumer.
An even more awesome implementation of this, in different languages, is _Traits_.
Traits are typically like Interfaces, but they have default behaviour associated with them.
Looking at my Switchable and my LightSwitch, you could imagine that practically all classes with this switch would have the same methods, with the same method behaviour...
...so why would I rewrite all of those methods over again, if I'm already going through the trouble of defining the signature in the interface?
Why couldn't I just add default behaviour in there, and have it apply to the implementer, unless a method is overridden?
Well, that's what Traits / Mix-Ins allow.
The relationship is only the "contract" that the class is getting to implement the methods the interface is offering.
That is how java can separate WHAT objects can do (Interface) and HOW the inherited class will do it.
I am working on an Android project and i am facing this situation.
I have 2 class :
class A extends B
{
openDoor(){
//impl
}
closeDoor(){
//impl
}
}
class X extends Y{
openDoor(){
//impl
}
closeDoor(){
//impl
}
}
Now if you observe the are two methods common in both the classes openDoor() and closeDoor()
what is the best way to avoid duplicate methods?
My Approach
class ContainingDuplicateMethods{
openDoor(){
//impl
}
closeDoor(){
//impl
}
}
}
Create a object of ContainingDuplicateMethods in both the class and call the methods, which we call it as Strategy Pattern,but is this the best solution? why because in large projects we cannot follow this approach and people say it not GOOD PRACTICE, in that case what approach do i need to follow ?
Please note that class A and X are already extending other classes and also i dont want to use static because - Static members are loaded into memory when the program execution starts and will be in memory until the program is terminated, say my code runs continuously for days or weeks and keeps on creating many number of objects using the static references so there might be a chance that we could run out of memory.
"Favour composition over inheritance" is a useful thing to remember.
Have a Door class with open and close. Include a Door as a member of both A and B.
Voila, job done.
So A.getDoor().close(). B.getDoor().open() etc.
If you need a common interface for both A and B (so you can use either somewhere) then create
interface HasDoor {
Door getDoor();
}
Now A and B can extend any class you like and implement HasDoor. Any class requiring a door can accept a HasDoor (or just directly accept the Door object) and call open, close, etc.
No duplicated code, full flexibility.
If you need your Door to call methods back in A and B then create the Door class as abstract and implement it in A and B as an anonymous inner class. The abstract methods will be called from Door and then you can do whatever processing is needed in A and B when those methods are called.
For example class A becomes:
class A implements HasDoor {
private Door door = new Door() {
#override void notifyDoorChanged(boolean closed) {
// The door is telling us its been opened or closed
}
}
#override
public Door getDoor() {
return door;
}
}
Where door is:
public abstract class Door {
boolean closed;
abstract notifyDoorChanged();
public void close() {
closed = true;
notifyDoorChanged(closed);
}
// etc
}
Note that this is similar to the strategy pattern - but its not quite the same. The Strategy pattern has one master object and then you plug in multiple strategies (i.e. different forms of Door). This has one Door and multiple other objects using the same type of Door, although you could extend it to use the Strategy pattern and have multiple door implementations very easily.
This is the implementation of the answer posted by Tim B.
It is a very flexible approach to go with. It is following the principles of object oriented reuse :
Identify that varies and separate them from what stays the same.
Program to an interface , not an implementation.
Favor object composition over inheritance.
public class Main {
public static void main(String[] args) {
X x = new X();
A a = new A();
x.getDoor().open();
x.getDoor().close();
a.getDoor().open();
a.getDoor().close();
}
}
interface HasDoor {
Door getDoor();
}
interface Door {
public void open();
public void close();
}
class A extends B implements HasDoor {
Door d;
#Override
public Door getDoor() {
Door door = new Door() {
public void open() {
System.out.println("Open A's Door");
}
public void close() {
System.out.println("Close A's Door");
}
};
return door;
}
}
class X extends Y implements HasDoor{
Door d;
#Override
public Door getDoor() {
Door door = new Door() {
public void open() {
System.out.println("Open X's Door");
}
public void close() {
System.out.println("Close X's Door");
}
};
return door;
}
}
class B {}
class Y {}
If you do not want to use HasDoor interface, you can declare constructors inside the class X and class A that initializes the Door instance.
Example ;
class X extends Y {
Door d;
public X() {
d = new Door() {
public void open() {
System.out.println("Open X's Door");
}
public void close() {
System.out.println("Close X's Door");
}
};
}
}
so here your class a and class a has to follow same functions.
that is both classes have same functions.
since the classes already extended another class we can use interface
interface door
{
openDoor(){
}
closeDoor(){
}
}
both class a and x can implement the door interface.
A class can implement any number of interfaces but can extend only one class.
if implementation of class door is same we can do like this
class Door
{
openDoor(){
impl//
}
closeDoor(){
impl//
}
}
class A extends b
{
Door d=new Door();
d.opendoor();
d.closeDorr();
}
Yes, create an abstract class which contains the common code. Have this abstract class implement an interface which contains the necessary methods.
Have both other classes extend the abstract class.
I think you should create an interface with methods openDoor() and closeDoor(). After that inherit classes A and X from this interface and implement methods.
If methods implementation are similar then you can create utility class with static methods.
public interface YourInterface{
public void openDoor();
public void closeDoor();
}
public abstract class YourAbstractClass implements YourInterface{
public abstract void openDoor();
public abstract void closeDoor();
}
public class YourClass extends YourAbstractClass{
#Override
public void openDoor();
public void closeDoor();
}
public class YourSubClass extends YourClass{
//you can just call super methods here
super.openDoor();
super.closeDoor();
}
I have the following system in Java:
public class Human {
public void drown(Animal animal) {
if (animal instanceOf Fish) {
return;
} else {
animal.die();
}
}
}
public abstract class LandAnimal extends Animal{...}
public class Tiger extends LandAnimal{...}
public abstract class Fish extends Animal {...}
public class Trout extends Fish {...}
I have thought of adding a method
public abstract boolean drownable() {...}
in class Animal but I don't have access to the code of Animal class.
As I know the use of instanceOf is considered bad OOP practice. How do I avoid the use of instanceOf in this case? Thanks.
The drown() method in Human should be (by the way, why do humans want to drown animals?):
public void drown(Animal animal) {
animal.drown();
}
And each Animal will know what to do, for example:
// in class Tiger
public void drown() {
die();
}
// in class Fish
public void drown() {
// do nothing, fish can't drown
}
You would declare Animal.drown() and override it in Fish, containing the appropriate 'kill code' :).
So you'd just need to call drown() on each animal and each instance will behave according to its type specific method implementation.
public class Human {
public void drown(Animal animal) {
animal.drown();
}
}
Methods can be overloaded based on their arguments. You can have two different methods:
public void drown(Fish f) {
return;
}
public void drown(LandAnimal a) {
a.drown();
}
However, it should be noted that this makes determining whether some animal will drown the responsibility of the Human class, which, as other answers show, is arguable.
I am currently working on a project where I am attempting to hide as much detail about a hierarchy I have created as possible. I want to do this to minimize the amount of information the user needs to know about objects (and to control what they can do to the state of the object). In addition, I'm using the pattern to limit what kinds of objects the application can make, and limit it to creation from the factory.
The main issue I am having, however, is that there are a few different kinds of interfaces I would like to expose. Each interface is has additional functionality that I don't believe should be shared, and I would like to keep these interfaces separated. Finally, I don't know what new interfaces may come in the future, but I'd like to try and be ready for them.
Weapon:
public interface Weapon extends GameObject {
Number attack();
boolean addWeaponAttribute(WeaponAttribute attribute);
}
Firearm:
public interface Firearm extends Weapon {
void reload(Number rounds);
}
My question is what would be the best way to have the factory produce objects with different interfaces? Here's what I am thinking "the best would be":
The most clear to the user (it's obvious what they're asking for and what they're getting back)
The best for future expansion (I am uncertain what new interfaces I will be adding to this system).
Here's what I have been thinking so far:
Create properly named methods for each interface
public static Firearm getFirearm(String firearmName) {
...
}
public static Weapon getWeapon(String weaponName) {
...
}
Do the above, but produce the factories in separately named classes
public class WeaponFactory {
public static Weapon getWeapon(String weaponName) {
...
}
}
public class FirearmFactory {
public static Firearm getFirearm(String firearmName) {
...
}
}
Something completely different
I'm open to suggestions, and changes. This is a flexible project, so I can change as much as I want to (in terms of this portion of the project) to make a better result.
Also - As a side note, I was uncertain if this question was too open-ended or not for SO. If I made a mistake posting here, let me know and I'll move my question elsewhere.
What I can suggest is to make the interfaces as concise as possible and move other unrelated methods elsewhere. you might consider doing this for example:
public interface Weapon extends GameObject {
Number attack();
}
public interface Modifiable extends GameObject {
boolean addWeaponAttribute(WeaponAttribute attribute);
}
public class ActualWeapon implements Weapon, Modifiable {
...
}
Then you can create different factories to generate your concrete objects, as you already mentioned:
public class WeaponFactory {
public static Weapon getWeapon(String weaponName) {
...
}
}
or
public class GenericFactory<T extends GameObject> {
public T createGameObject(Object... properties) {
...
}
}
public class WeaponFactory extends GenericFactory<ActualWeapon> {
public ActualWeapon createGameObject(Object... properties) {
...
}
}
I think you can't add static methods to interfaces. I wouldn't recommend it if you even could.
maybe just use the factory method design pattern like
interface GameObject {}
class WeaponAttribute {}
interface Weapon extends GameObject {
Number attack();
boolean addWeaponAttribute(WeaponAttribute attribute);
}
interface Firearm extends Weapon {
void reload(Number rounds);
}
class WeaponBaseClass implements Weapon {
WeaponBaseClass(WeaponName weaponName) {
this.weaponName=weaponName;
}
#Override public Number attack() {
return null;
}
#Override public boolean addWeaponAttribute(WeaponAttribute attribute) {
return false;
}
public String toString() {
return weaponName.toString();
}
final WeaponName weaponName;
}
class FirearmBaseClass extends WeaponBaseClass implements Firearm {
public FirearmBaseClass(WeaponName weaponName) {
super(weaponName);
}
#Override public void reload(Number rounds) {}
}
enum WeaponName {
knife, sword, colt45, glock19, glock19WithLaser;
}
class WeaponCreator {
Weapon create(WeaponName weaponName) {
switch (weaponName) {
case knife:
case sword:
return new WeaponBaseClass(weaponName);
case colt45:
case glock19:
return new FirearmBaseClass(weaponName);
default:
return new WeaponBaseClass(weaponName);
}
}
}
class FancyWeaponCreator extends WeaponCreator {
Weapon create(WeaponName weaponName) {
Weapon weapon = null;
switch (weaponName) {
case glock19WithLaser:
weapon = super.create(WeaponName.glock19);
// whatever it needs
return weapon;
default:
return new WeaponBaseClass(weaponName);
}
}
}
public class Main {
public static void main(String[] args) {
System.out.println(new WeaponCreator().create(WeaponName.knife));
System.out.println(new WeaponCreator().create(WeaponName.colt45));
System.out.println(new FancyWeaponCreator().create(WeaponName.glock19WithLaser));
}
}
What about a factory of factories? Each factory would implement ifactory. Ifacorty would require a method Instantiate(string type) and return your subclassed weapon instance.
Using generics, you might only need one factory method like:
public <T> T getObject(java.lang.Class<T> responseType, String name)
Then the user would call:
Weapon weapon = factory.getObject(Weapon.class, "my weapon");