Advertisement
Guest User

Untitled

a guest
May 7th, 2015
250
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.88 KB | None | 0 0
  1. //bdunko 5/7/15
  2.  
  3. public class AbstractTest {
  4.    
  5.     public abstract class Human{
  6.         protected String name;
  7.        
  8.         public String getName(){
  9.             return name;
  10.         }
  11.        
  12.         public abstract void eat();
  13.     }
  14.    
  15.     public class Schoolboy extends Human{
  16.         private int grade;
  17.        
  18.         public Schoolboy(String name, int grade){
  19.             this.name = name;
  20.             this.grade = grade;
  21.         }
  22.  
  23.         public int getGrade(){
  24.             return grade;
  25.         }
  26.        
  27.         @Override
  28.         public void eat() {
  29.             System.out.println("Omnomnom");
  30.         }
  31.     }
  32.    
  33.     public void run(){
  34.         //Human max = new Human();  this line produces an error - Human is abstract
  35.         //Schoolboy glenn = new Human();  this line also produces an error - Human is abstract (again)
  36.         Human kieran = new Schoolboy("Kieran", 11); //This line works
  37.         Schoolboy senan = new Schoolboy("Senan", 9); //This line works - so what's the difference?
  38.        
  39.         System.out.println(kieran.getName()); //this will print Kieran
  40.         System.out.println(senan.getName()); //this will print Senan
  41.        
  42.         //System.out.println(kieran.getGrade());   this line produces an error - getGrade does not exist for the abstract class Human
  43.         System.out.println(((Schoolboy)kieran).getGrade()); //however, this line works - we can cast kieran to a Schoolboy. This prints 11.
  44.        
  45.         System.out.println(senan.getGrade()); //no need to cast for senan, as this object was declared as a Schoolboy to start with. This prints 9.
  46.        
  47.         senan.eat(); //This will print Omnomnom.
  48.         kieran.eat(); //And this will also print Omnomnom. The reason we do not have to cast this is because the function eat is declared in Human (even though it is abstract). Calling the function will use Schoolboy's implimentation of it, which simpily prints Omnomnom.
  49.     }
  50.    
  51.     public static void main(String args[]){
  52.         AbstractTest test = new AbstractTest();
  53.         test.run();
  54.     }
  55. }
  56.  
  57. /*
  58.  * OUTPUT:
  59.  * Kieran
  60.  * Senan
  61.  * 11
  62.  * 9
  63.  * Omnomnom
  64.  * Omnomnom
  65.  */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement