+ 2
can somebody give me areal world example for interface usage?
interface confuse me alittle I need clear example in real world to help understand it
2 Réponses
+ 4
Let's say your writing a game (rpg type for sake of the example) that requires an item and inventory management system. Your base class is Item which holds member data like item name and weight. Then we derive (extend) that into multiple subclasses like Weapon, Armor, Stackable, etc. As your code grows and the number of (and types of) items grows it begins to get more and more difficult to code changes and make sure each class has all the methods and members it needs. This is a perfect place for interfaces.
Ok so we have an interface (very basic) called Equipable with a single abstract method onEquip (). The Weapon class implements the Equipable interface and therefore the onEquip method. something like this:
class Weapon extends Item implements Equipable {
public boolean onEquip (){
if (canEquip) {
// requirements met etc
// do whatever you need to, assign this item to weapon slot or whatever
return true;
}
return false; // unable to equip
}
}
Armor could be much more complex if you have things like helmets, gloves, boots, and so on. Each armor type could be a subclass of armor. armor would implement Equipable but leave the onEquip as abstract forcing each subclass to implement it's own onEquip method.
now let's go to consumables. you might have multiple potions. health and mana for instance. same concept. derive item into potion subclass implementing Consumable interface, but leaving the onUse limited in functionality. derive potion into 2 sub classes and implement the onUse for each potion.
class Potion extends Stackable implements Consumable {
public void onUse (){
--stackSize;
}
class HealthPotion extends Potion {
public void onUse (){
// heal some health
+ 2
ok seriously. increase the max length of posts. I'm tired of editing my post and submitting it just to have it cut off.. and reverted to pre edit.... loss of star rating on Google play