Skip to content

Instantly share code, notes, and snippets.

@rajeevprasanna
Created January 19, 2014 02:20
Show Gist options
  • Save rajeevprasanna/8499616 to your computer and use it in GitHub Desktop.
Save rajeevprasanna/8499616 to your computer and use it in GitHub Desktop.
Inheritance IS-A and HAS-A relation
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;
}
}
package inheritanceIsaAndHasA;
public class Engine {
public void start() {
System.out.println("Engine Started:");
}
public void stop() {
System.out.println("Engine Stopped:");
}
}
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
}
}
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