Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //bdunko 5/7/15
- public class AbstractTest {
- public abstract class Human{
- protected String name;
- public String getName(){
- return name;
- }
- public abstract void eat();
- }
- public class Schoolboy extends Human{
- private int grade;
- public Schoolboy(String name, int grade){
- this.name = name;
- this.grade = grade;
- }
- public int getGrade(){
- return grade;
- }
- @Override
- public void eat() {
- System.out.println("Omnomnom");
- }
- }
- public void run(){
- //Human max = new Human(); this line produces an error - Human is abstract
- //Schoolboy glenn = new Human(); this line also produces an error - Human is abstract (again)
- Human kieran = new Schoolboy("Kieran", 11); //This line works
- Schoolboy senan = new Schoolboy("Senan", 9); //This line works - so what's the difference?
- System.out.println(kieran.getName()); //this will print Kieran
- System.out.println(senan.getName()); //this will print Senan
- //System.out.println(kieran.getGrade()); this line produces an error - getGrade does not exist for the abstract class Human
- System.out.println(((Schoolboy)kieran).getGrade()); //however, this line works - we can cast kieran to a Schoolboy. This prints 11.
- 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.
- senan.eat(); //This will print Omnomnom.
- 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.
- }
- public static void main(String args[]){
- AbstractTest test = new AbstractTest();
- test.run();
- }
- }
- /*
- * OUTPUT:
- * Kieran
- * Senan
- * 11
- * 9
- * Omnomnom
- * Omnomnom
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement