-
Is-A and Has-A Relationship in JavaStaticPL/JAVA 2020. 2. 5. 20:39
1. Overview
- IS-A Relationship:
The concept of IS-A is totally based on Inheritance, which can be of two types Class Inheritance or Interface Inheritance. It is just like saying "A is a B type of thing". For example, Apple is a Fruit, Car is a Vehicle etc. Inheritance is uni-directional. For example, House is a Building. But Building is not a House.
It is a key point to note that you can easily identify the IS-A relationship. Wherever you see an extends keyword or implements keyword in a class declaration, then this class is said to have IS-A relationship.
- HAS-A Relationship:
Composition(HAS-A) simply means the use of instance variables that are references to other objects. For example, Maruti has Engine, or House has Bathroom.
2. Description
2.1 Is-A
package relationsdemo; public class Bike { private String color; private int maxSpeed; public void bikeInfo() { System.out.println("Bike Color= "+color + " Max Speed= " + maxSpeed); } public void setColor(String color) { this.color = color; } public void setMaxSpeed(int maxSpeed) { this.maxSpeed = maxSpeed; } }
package relationsdemo; public class Pulsar extends Bike { public void PulsarStartDemo() { Engine PulsarEngine = new Engine(); PulsarEngine.stop(); } }
2.2 Has-A
package relationsdemo; public class Pulsar extends Bike { public void PulsarStartDemo() { Engine PulsarEngine = new Engine(); PulsarEngine.stop(); } }
package relationships; public class Engine { public void start(){ System.out.println("Engine Started:"); } public void stop(){ System.out.println("Engine Stopped:"); } }
3. Reference
https://www.c-sharpcorner.com/UploadFile/3614a6/is-a-and-has-a-relationship-in-java/
https://www.w3resource.com/java-tutorial/inheritance-composition-relationship.php
'StaticPL > JAVA' 카테고리의 다른 글
Atomic Variables (0) 2020.02.26 Access Modifier (0) 2020.02.23 Boxing, unboxing, and autoboxing (0) 2019.09.27 Functional (0) 2019.08.27 Generics and Generic Methods (0) 2019.08.27