How many way to access another class
There are two way to access another class property:
1. Association
2. Inheritance
1. Association
An Object associate with other Object to use the functionality and services provided by that object.
Association is relation between two separate classes which establishes through their Objects.
Association can be achieve by one-to-one, one-to-many, many-to-one and many-to-many.
Association has two form Aggregation and Composition.
For Example :
class User{ String name; } class Car{ String name; } class Test{ public static void main(String [] args){ User user=new User(); user.name="Ramesh"; Car car=new Car(); car.name="Bmw"; //Association Example System.out.println(user.name + " has a " + car.name); } }
i) Aggregation:
- It is a special form of Association.
- It represents Has-A relationship.
- It is a unidirectional association or one way communication.
- In this case both the entities can survive individually.
- It is also called week relation ship.
Examples :
Student has-a Mobile
User has-a Car
ii) Composition:
- Restriction in Aggregation that is called composition.
- It represents Part-Of relation ship.
- In this case both the entities can never survive individually.
- It is also called strong relation ship.
Examples :
Book is part-of Lib
Student is part-of college
Teacher is part-of college
engine is part-of car
lens is part-of projector
2. Inheritance
- To access the requires property from base class we use Inheritance.
- It represents is-a relation ship.
- In case inheritance we use extends or implements keyword.
- We use inheritance when you customize the code.
- Parent class also known as Base class or super class while child class is known as derived class or sub class.
- There are five types of Inheritance:
- Single Level
- Multi Level
- Multiple
- Hierarchical
- Hybrid
- Java supports only three types of inheritance :
- Single Level
- Multi Level
- Hierarchical
Examples :
Dog is-an Animal
Lenovo is-a Laptop
Dependency Injection:
When an object is dependent an another object that is called dependency.
When we full the requirements of another object that is called dependency injection.
How many way to achieve Dependency Injection ?
There are two way :
1. Setter Injection or Method Injection
2. Constructor Injection
Simply we can say we use setter or method injection when we want to achieve Aggregation and When we want to achieve Composition we use Constructor.
No comments:
Post a Comment