Title | Overriding - Notes on how to override variables in java from the labs and the answer to the |
---|---|
Course | Introduction to Object-Oriented Programming |
Institution | University College Cork |
Pages | 2 |
File Size | 62.5 KB |
File Type | |
Total Downloads | 93 |
Total Views | 128 |
Notes on how to override variables in java from the labs and the answer to the practical...
Polymorphism Example – OVERRIDING
/** * note this does not extend any class * This is a parent class (superclass) **/ class Student { //instance variable private String general = "Enjoying Life"; //method public void transport() { System.out.println("I'm broke so I walk to college"); } } /** * subclass of Student **/ class SchoolKid extends Student { //overriding transport method in Student Class public void transport() { System.out.println("My Mammy or Daddy drops me to school"); } } /** * subclass of Student **/ class MedStudent extends Student { public void transport() { System.out.println("I go to college in the hospital"); } } /** * subclass of Student **/ class BisStudent extends Student { //overriding transport method in Student Class public void transport() { System.out.println("I get the bus to college"); } }
Polymorphism Example – OVERRIDING
public class TestPolymorphism { // main method from where all Java applications begin public static void main(String args[]) { MedStudent med = new MedStudent(); // instantiate a MedStudent SchoolKid kid = new SchoolKid(); // instantiate a SchoolKid BisStudent bis = new BisStudent(); // Instantiate a BisStudent //invoke the transport method in the med object med.transport(); //invoke the transport method in the kid object kid.transport(); //invoke the transport method in the bis object bis.transport(); //invoke the transport method in the med object med.transport(); } } OUTPUT I go to college in the hospital My Mammy or Daddy drops me to school I get the bus to college I go to college in the hospital...