Polymorphic, but still not really?

Zapdez

New Member
Joined
May 31, 2014
Messages
8
Reaction score
0
/rant/
So I am learning Java and OOP and need some commmunity input regarding inheritance and interfaces.

Apart from my understanding regarding the topic which I have put below could I ask for 2 things mainly from your thoughts surrounding and your experience with the related principles.

a) Is there something I am missing, judging by my understanding? Because I though interfaces were the poly, in polymorphism.

b) Is it possible to acheive, fully blown polymorphism without having to reference/cast objects.

SO here goes. As simply as possible, this is what I understand about the topic....

Interfaces are basically another way of - breaking the rules of single inheritance. Many classes can impliment and a class can implement multiple interfaces.

By using interfaces, a child class can, both inherit it's parents methods and be forced to implement it's interface methods. Resulting in an easy to extend and maintain inheritance tree etc/code base.

The catch however is, when the child is referenced under the parent, you only have access to the parent methods. To access the interface methods implemented, you will need to cast or create the child under the interface reference type. (partial polymorphism still!)

Interfaces also allow the collection of multiple classes of different families to be collected under the interface type. Such as in an array. To what benefit I am yet to discover.

In my opinion, it is pointless since I still cannot achieve fully blown polymorphism anyways - by just using the parent reference type and still have access to the interface implementations.
 
http://msdn.microsoft.com/en-us/library/ms173152.aspx

Read. Interfaces are mainly code contracts. So you're doing it wrong.

Interfaces also allow the collection of multiple classes of different families to be collected under the interface type. Such as in an array. To what benefit I am yet to discover.

So you don't really know the purpose of interfaces, yet you're starting at the poly route... Perhaps go read up on the purpose of such interfaces, IDisposable is an easy one.
 
Last edited:
Interfaces also allow the collection of multiple classes of different families to be collected under the interface type. Such as in an array. To what benefit I am yet to discover.

interfaces are contracts. kind of like a USB port. a usb port defines a method of communication from a pc to a thing with a usb cable. a thing with a usb cable could be a mouse, a keyboard, a camera, a headset, whatever it doesn't matter.

Code:
public interface IWeapon
{
    string Hit(string target);
}

public class Sword : IWeapon 
{
    public string Hit(string target) 
    {
        return "Slice " + target + " in half";
    }
}

public class Dagger : IWeapon 
{
    public string Hit(string target) 
    {
        return "Stab " + target + " to death";
    }
}

public class Samurai 
{
    readonly IWeapon[] allWeapons;

    public Samurai(IWeapon[] allWeapons) 
    {
        this.allWeapons = allWeapons;
    }

    public void Attack(string target) 
    {
        foreach (IWeapon weapon in this.allWeapons)
            Console.WriteLine(weapon.Hit(target));
    }
}

the code above is stolen from ninjects examples.
but its a fun and awesome example of interfaces.

the code above shows a samurai.
he carries weapons. and he hits with them.
but he doesn't necessarily know what his weapons are.
he just knows how to use them all.

now if you're going to use something like inheritance you could prolly find a need to inherit a sword from a dagger.
makes sense one is a kind of the other.
start with a baseclass called BaseWeapon
then BaseMeleeWeapon inherits from BaseWeapon
then BaseStabbyWeapon inherits from BaseMeleeWeapon
then Dagger inherits there and then Sword inherits dagger.

so that makes sense for things that are always weapons.
but take a pot of boiling water.
a pot of boiling water isn't a weapon.
it inherits from BaseKitchenUtensil coz its a kitchen utensil.
but a samurai would totally be able to use a pot of boiling water against opponents if he had to.
he's had special training.
so even though PotOfBoilingWater inherits from BaseKitchenUtensil we can still implement the IWeapon interface and then when we really need to we can treat it as though its a weapon even though it totally isn't.

interfaces focus on what things can DO not what things are.

http://stackoverflow.com/questions/1389434/benefits-of-implementing-an-interface
http://programmers.stackexchange.com/questions/108240/why-are-interfaces-useful
http://stackoverflow.com/questions/...ver-an-interface-when-designing-c-sharp-class
http://stackoverflow.com/questions/...ctices-inheritance-v-composition-v-interfaces
 
Last edited:
^ nice post, but i couldnt be arsed if someone cant research it themselves.
 
just dont go crazy with interfaces, you see this pointless crap all the time, essentially a 1-to-1 interface:class

Code:
public interface Product {
    String getName();
    void setName(String name);

    int getPrice();
    void setPrice(int price);
}

public class ProductImpl implements Product {
   
    private String name;
    private int price;
     
    public String getName() {
        return name;
    }

    public void setName(String name) {
         this.name = name;
    }

    int getPrice() {
        return price;
    }

    void setPrice(int price) {
        this.price = price
    }
}
 
Very awesome post sp4ceman. Makes plenty sense.

As for semaphore, I have been researching it. But still no worries.

I think my question was misunderstood and perhaps I am struggling to word it clearly.

Speaking in terms of Java and in the context of the Ninja (Uber awesome explanation again.)

MyKitchenPotUtensil implements Weapon interface in the case it needs to be used as a weapon, okay cool, one day a ninja will use it. But, I can only access those weapons functions, if the pot is either stored as in the Weapon interface type OR, when needed to be used as a weapon, type cast into a Weapon interface. Thus making the entire process of polymorphism, completely manual. Shouldnt the Wepon methods be accessible regardless?

Basically - just like the way a child object that adds functionality not inherited - is not known by the parent(for obvious reasone) and cannot be configured somehow, when the object IS created, to be able to become aware of new methods it doesn't have itself.
 
just dont go crazy with interfaces, you see this pointless crap all the time, essentially a 1-to-1 interface:class

Code:
public interface Product {
    String getName();
    void setName(String name);

    int getPrice();
    void setPrice(int price);
}

public class ProductImpl implements Product {
   
    private String name;
    private int price;
     
    public String getName() {
        return name;
    }

    public void setName(String name) {
         this.name = name;
    }

    int getPrice() {
        return price;
    }

    void setPrice(int price) {
        this.price = price
    }
}

i use dependency injection so i have most of my classes implement an interface even if its 1-1
it sounds dumb until you need to quickly add logging or something.
say classA is breaking.
classA implemenets IClassA
i make classB inherit from classA and implement IClassA
i add some logging or something to classB.
i wire up ninject so now everytime i request IClassA i get classB with extra logging or whatever.
fix issue, and wire up as normal....
 
MyKitchenPotUtensil implements Weapon interface in the case it needs to be used as a weapon, okay cool, one day a ninja will use it. But, I can only access those weapons functions, if the pot is either stored as in the Weapon interface type OR, when needed to be used as a weapon, type cast into a Weapon interface. Thus making the entire process of polymorphism, completely manual. Shouldnt the Wepon methods be accessible regardless?

Basically - just like the way a child object that adds functionality not inherited - is not known by the parent(for obvious reasone) and cannot be configured somehow, when the object IS created, to be able to become aware of new methods it doesn't have itself.

They are available

Code:
public class Tap implements Closeable {
   //implement Tap
}

Tap tap = new Tap();
tap.close(); //close in a method from Closeable
 
Last edited:
MyKitchenPotUtensil implements Weapon interface in the case it needs to be used as a weapon, okay cool, one day a ninja will use it. But, I can only access those weapons functions, if the pot is either stored as in the Weapon interface type OR, when needed to be used as a weapon, type cast into a Weapon interface. Thus making the entire process of polymorphism, completely manual. Shouldnt the Wepon methods be accessible regardless?

Basically - just like the way a child object that adds functionality not inherited - is not known by the parent(for obvious reasone) and cannot be configured somehow, when the object IS created, to be able to become aware of new methods it doesn't have itself.

what do you mean "accessible regardless"
if I go

Code:
public class MyKitchenPotUtensil : IWeapon
{
  public int degrees {get;set;}
  
  public MyKitchenPotUtensil()
  {
    degrees = 0;
  }
  
  public string Hit(string target)
  {
    return "pours water on " + target + "oh it burns";
  }
  
  public string IsItBoilingYet()
  {
    if (degrees < 100)
    {
     return "no";
    }
    
    return "yes";
    }
  }

}


MyKitchenPotUtensil pot = new MyKitchenPotUtensil();
pot.Hit("face"); //its a pot so i can hit
pot.degrees = 50; //pots have degrees that i can set
pot.IsItBoilingYet(); //its a pot so i can check the temp

IWeapon potWeapon = new MyKitchenPotUtensil();
potWeapon.Hit("face"); //its a weapon so i can hit
potWeapon.degrees = 50; //weapons dont have degrees this will break
potWeapon.IsItBoilingYet(); //this wont work coz weapons cant boil

i can access those functions?
anything calling a pot can use those functions.
by making MyKitchenPotUtensil implement IWeapon all that means is that I know MyKitchenPotUtensil definitely has a method called hit with the given signature.

if i know its a pot and cast it as a pot i can do everything.
if i know its a pot and use it as a weapon then i can only do weapon stuff....
 
Last edited:
Ok cool. It is making MUCH more sense now. I must thank you guys for your patience and your input!

Muchos Gracias!
 
i use dependency injection so i have most of my classes implement an interface even if its 1-1
it sounds dumb until you need to quickly add logging or something.
say classA is breaking.
classA implemenets IClassA
i make classB inherit from classA and implement IClassA
i add some logging or something to classB.
i wire up ninject so now everytime i request IClassA i get classB with extra logging or whatever.
fix issue, and wire up as normal....

it really just depends on the situation, and your tool set.
with java and spring, if I wanted to temporarily add logging, you can just define a pointcut and advice.


interfaces are absolutely useful, for providing contracts between unrelated things.
you dont create interfaces because you might at some point want to extend the implementer.
 
just dont go crazy with interfaces, you see this pointless crap all the time, essentially a 1-to-1 interface:class

Code:
public interface Product {
    String getName();
    void setName(String name);

    int getPrice();
    void setPrice(int price);
}

public class ProductImpl implements Product {
   
    private String name;
    private int price;
     
    public String getName() {
        return name;
    }

    public void setName(String name) {
         this.name = name;
    }

    int getPrice() {
        return price;
    }

    void setPrice(int price) {
        this.price = price
    }
}

It is always a good idea to separate the "what" (interface/contract) from the how (implementation), especially as it then enables both Interface Segregation as well as Dependency Injection (the I and D in SOLID best practice).

It may seem pointless if there is only 1 implementation, but we don't know what extensions might be required down the line. And refactoring is a hell of a lot easier when every action is under contract (i.e. specified in some interface).
 
DI can be achieved without interfaces.

I also never said "dont use interfaces"
 
Last edited:
DI can be achieved via abstract classes.

I also never said "dont use interfaces"

You can only inherit from one class in Java (which is the language the OP is learning), whereas you can implement multiple interfaces.

In sp4ceman's awesome example, your Pot wouldn't be able to have Weapon features, since it'll only be able to inherit from one class, BaseKitchenUtensil.

I'll reiterate: it is always a good idea to decouple the "what" from the "how".
 
again, I never said "dont use intefaces", just that it is pointless to create interfaces for anemic domain models


Absolutely fine and should be used:
Code:
class Pot implements [B][U]Weapon[/U][/B] {
   //methods
}


absolutely pointless:
Code:
class [B][U]PotImpl[/U][/B] implements [B][U]Pot[/U][/B], Weapon {
   //methods
}
 
Top
Sign up to the MyBroadband newsletter
X