Advertisement
adityapaliwal134

AbstractClassAndInterface

Oct 31st, 2014
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.24 KB | None | 0 0
  1. public abstract Animal
  2. {
  3.    public void eat(Food food)
  4.    {
  5.         // do something with food....
  6.    }
  7.  
  8.    public void sleep(int hours)
  9.    {
  10.         try
  11.     {
  12.         // 1000 milliseconds * 60 seconds * 60 minutes * hours
  13.         Thread.sleep ( 1000 * 60 * 60 * hours);
  14.     }
  15.     catch (InterruptedException ie) { /* ignore */ }
  16.    }
  17.  
  18.    public abstract void makeNoise();
  19. }
  20. Note that the abstract keyword is used to denote both an abstract method, and an abstract class. Now, any animal that wants to be instantiated (like a dog or cow) must implement the makeNoise method - otherwise it is impossible to create an instance of that class. Let's look at a Dog and Cow subclass that extends the Animal class.
  21.  
  22. public Dog extends Animal
  23. {
  24.   public void makeNoise() { System.out.println ("Bark! Bark!"); }
  25. }
  26.  
  27. public Cow extends Animal
  28. {
  29.   public void makeNoise() { System.out.println ("Moo! Moo!"); }
  30. }
  31. Now you may be wondering why not declare an abstract class as an interface, and have the Dog and Cow implement the interface. Sure you could - but you'd also need to implement the eat and sleep methods. By using abstract classes, you can inherit the implementation of other (non-abstract) methods. You can't do that with interfaces - an interface cannot provide any method implementations.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement