Created
January 19, 2014 02:20
-
-
Save rajeevprasanna/8499616 to your computer and use it in GitHub Desktop.
Inheritance IS-A and HAS-A relation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package inheritanceIsaAndHasA; | |
public class Car { | |
//color and maxSpeed are instance variables | |
private String color; | |
private int maxSpeed; | |
//Below are methods of Car class | |
public void carInfo() { | |
System.out.println("Car Color= " + color + " Max Speed= " + maxSpeed); | |
} | |
public void setColor(String color) { | |
this.color = color; | |
} | |
public void setMaxSpeed(int maxSpeed) { | |
this.maxSpeed = maxSpeed; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package inheritanceIsaAndHasA; | |
public class Engine { | |
public void start() { | |
System.out.println("Engine Started:"); | |
} | |
public void stop() { | |
System.out.println("Engine Stopped:"); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package inheritanceIsaAndHasA; | |
//Maruti is specific type of Car which extends Car class means Maruti IS-A Car | |
public class Maruti extends Car { | |
// Maruti extends Car and thus inherits all methods from Car (except final and static) | |
// Maruti can also define all its specific functionality | |
public void MarutiStartDemo() { | |
Engine MarutiEngine = new Engine(); | |
MarutiEngine.start(); | |
//Maruti class uses Engine object’s start() method via composition. We can say that Maruti class HAS-A Engine | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package inheritanceIsaAndHasA; | |
//RelationsDemo class is making object of Maruti class and initialized it. Though Maruti class does not have setColor(), | |
//setMaxSpeed() and carInfo() methods still we can use it due to IS-A relationship of Maruti class with Car class. | |
public class RelationsDemoTest { | |
public static void main(String[] args) { | |
Maruti myMaruti = new Maruti(); | |
myMaruti.setColor("RED"); | |
myMaruti.setMaxSpeed(180); | |
myMaruti.carInfo(); | |
myMaruti.MarutiStartDemo(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment