Skip to content

Instantly share code, notes, and snippets.

@phoenixperry
Last active December 25, 2015 00:49
Show Gist options
  • Save phoenixperry/6890135 to your computer and use it in GitHub Desktop.
Save phoenixperry/6890135 to your computer and use it in GitHub Desktop.
This is an example of abstract classes, interfaces and polymorphism
/* Polymoprhism allows for objects to be dynamically switched on runtime because
each object extending the root type Pet can be used interchangably. You can think of polymorphism as allowing each object to share a type and a set of functions but to be able ot switch for each other in code based on what you need.
You know every object extending that root object will implement all methods marked abstract and be able touse all methods that are defined. The Abstract functionality gets you around having to instantiate the abstract object.
*/
Cat cat;
Dog dog;
Pet currentPet;
int counter = 0;
void setup(){
cat = new Cat();
dog = new Dog();
}
void draw(){
if(counter%2==0)
currentPet = cat;
else
currentPet = dog;
currentPet.eat();
currentPet.sleep();
counter++;
}
public abstract class Pet{
//every object extending pet will need to define eat for itself
public abstract void eat();
//but they can all sleep and sleep will be the same for all
public void sleep(){
println("i am sleeping");
}
}
public class Cat extends Pet implements Owner{
public String ownerName = "Phoenix";
public Cat(){}
public void eat(){
println("I am a cat and I eat mice!");
}
//here the cat object implements all required methods of the interface
public void parkTrip(){
println("who said cat's couldn't go to the park?!");
}
public void vetTrip(){
println("I am such an evil kitty the vet has a special tag for me!");
}
public void lostCat(){
println("my owner's name is " + ownerName);
}
}
public class Dog extends Pet {
public Dog(){}
public void eat(){
println("I am a dog and I eat bones!");
}
}
//interfaces are very similar to all abstract classes - they can't be implemented and they can't contain any code to the implentation. :) You can have as many as you want! Any object implementing the interface must implement all of it
public interface Owner {
public void parkTrip();
public void vetTrip();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment