0% found this document useful (0 votes)
16 views153 pages

Sca Oops

Uploaded by

neel mulla
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views153 pages

Sca Oops

Uploaded by

neel mulla
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 153

Lecture - 1

What is OOP?
Part-1
Object
Oriented
Programmin
g
What is object-oriented
programming?
1. It is one of the most popular programming paradigm.

2. In simple words, it is a programming pattern that resolves around


objects or entities.

3. Object-oriented programming teaches us how to build software by


closely imitating the real world objects or entities.
Popular programming
approaches
● Procedure Oriented Programming

● Object Oriented Programming

● Functional Programming

● Aspect Oriented Programming


Advantages of object-oriented
Programming
Better Representation of Real World Scenario

Class
Enhanced Security
Object

OOP Code Reusability & Easy Code Modification

Better Software Maintenance


Key Concepts Of
Object-Oriented
Programming

● Class
● Object
● Encapsulation

● Abstraction Simplicity

● Polymorphism

● Inheritance
Lecture - 2

Class & Object


Part-2
Class &
Objects
What is an Object ?
1. In programming any real world entity is an Object.
Components of an Object ?
1. Every Object has two main components :- Property and Behaviours

Breed
Weight

Object
Question -

Are you an Object ?


Yes,we humans are objects because:

We have attributes as name, height, age


etc.

We also can show behaviors like walking,


talking, running, eating etc.
Question -

Is your phone an Object ?


Yes, it is an object because:

It has attributes like model, price, color, weight


etc.

It can also perform actions/behaviors like


calling, recording, photo clicking etc.
How to create an object?
1. Now to create/represent objects we first have to write all their
attributes and methods under a single group.

2. This group is called a class


What is Class ?
1. A class is used to specify the basic structure of an object.

2. It contains

a. Data members/Attributes

b. Methods/Behaviour
Example -

Each person collectively comes under a


class called Human.

So we belong to the class Human

Amit Ravi Kiran


Example -
Each Type of car collectively comes under a
class called Car .

Class
Syntax of Object Oriented Programming
<access modifier> class <class Name>
{
// Declaration of Data Types
<access modifier> <data_Type> <variable_Name> = value;
............... ......... ............ = .....;
............... ......... ............ = .....;

// Declaration of Methods

<access modifier> <return_Type> <method_Name>( <argument_dataType> argument )

// Method Body

}
Driver
Class
Sample code of Object
Oriented programming class UseStudent
{
public static void main(String [] args)
Entity {
Class Student s;

s=new Student();
class Student
S.roll = 101;
{ S.name = “Amit”;
int roll; S.per = 82.9;
String name; System.out.println(“Roll:” + s.roll);

double per; System.out.println(“Name:” + s.name);

System.out.println(“Per:” + s.per);

}
}
}
Lecture - 3

Encapsulation
Part-3
Object
Oriented
Programmin
g
What Is
1. Encapsulation ? or wrapping the data and
Encapsulation is the process of binding
the codes that operates on the data into a single entity

2. Another way to think about encapsulation is, that it is a protective


shield that prevents the data from being accessed by the code
outside this shield.
According To Encapsulation. . .
● Data :- Data members must be kept private.

● Methods :- Methods only can access these data members and


these methods can be made public.
Real world example of
Encapsulation
● Suppose you have an account in the bank. Is it possible for anyone obtain your
account details like your account balance, transactions done etc.? Obviously
No.

● This means that your bank details are private, so that anyone cannot see your
account details.

● Only you will have access to your account details and that too using method
defined inside that class and this method will ask your account id and
password for authentication.
How to achieve or
implement Encapsulation
in Java
❖ There are two steps required to achieve or implement encapsulation
in Java program.

➢ Declaring the instance variable of the class as private so that it


cannot be accessed directly by anyone from outside the class.

➢ Provide the public setter and getter methods in the class to


set/modify the values of the variable/fields.
Entity Class (Without
Encapsulation)
class Student {

int roll;
String name;
double per;

}
Driver Class
class UseStudent
{
public static void main(String [] args)
{
Student s;
s=new Student();
s.roll = 101;
s.name = “Amit”;
s.per = 82.9;
System.out.println(“Roll:” + s.roll);
System.out.println(“Name:” + s.name);
System.out.println(“Per:” + s.per);
}
}
Correction In Previous Code
class Student{

private int roll;


private String name;
private double per;

public void setData(int r, String n, double p){


roll=r;
name=n;
per=p;
}
Correction In Previous Code

public void showData( ) {

System.out.println(“Roll no is ” +roll);
System.out.println(“Name is ” +name);

System.out.println(“Percentage is ”+per);
}

}
Correction In Previous Code

class UseStudent
{
public static void main(String [] args)
{
Student s;
s=new Student();
s.setData(101, “Amit”, 82.9);
s.showData();
}
}
Advantages Of Encapsulation
Lecture - 4

Abstraction
Part-4
Object
Oriented
Programmin
g
What Is Abstraction ?

1. Abstraction is one of the key concepts of object-oriented


programming that “shows” only essential attributes and “hides”
unnecessary information.

2. The main purpose of abstraction is to make the interaction with


the application/product simple.
Let's Understand
Abstraction With
Example

Without Abstractio
Abstraction n
Another example to
Understand Abstraction

Without Abstractio
Abstraction n
Let's Understand Abstraction
With
public class Car { Code
private void moveBreakPads() {
}
private void changePistonSpeed(){
}
private void createSpark(){
}
public void turnOnCar(){
createSpark();
}
public void accelerate(){
changePistonSpeed();
}
public void brake(){
moveBreakPads();
}
}
Let's Understand Abstraction
With
//Driver Class Code
public class UseCar {
public static void main(String[] args) {
Car C=new Car(); //Create Object
C.turnOnCar();
C.accelerate();
C.brake();
}
}
Difference Between
Abstraction And Encapsulation

Abstraction Encapsulation

Abstraction hides the implementation


Encapsulation binds and wraps the data
details and shows only the functionality to
and methods together into a single unit
the user

Hides the implementation details to Hides data for the purpose of data
reduce the code complexity protection

It can be achieved by making data


Abstraction can be achieved by using
abstract class and interfaces members private and accessing them
through public methods
Abstraction
Vs
Encapsulation
Lecture - 5

Constructor
Part-5
Object
Oriented
Programmin
g
What Is
Constructor?
A constructor is a special method of a class in object-
oriented programming that initializes a newly created
object of that class.
Constructors are methods
which…
1. Have the same name as that of the class.

2. Don’t have any return type.

3. Automatically called as soon as object is created


What is Default
Constructor
● Default constructor is automatically inserted by java compiler, if
we have not created any constructor explicitly .

class Account {
class Account { private int accid;
private int accid; private String name;
private String name; private double balance;
private double balance;
} public Account() {
}
}

Our Compiler’s Code


Code
Entity
Class Non Parameterized
Constructor
class Account {
private int accid; Driver
private String name;
private double balance; Class
public Account() { class CreateAccount
accid=101;
name=“AMIT” {
balance=50000.0; public static void main(String [] args)
}
{

public void show() { Account A;


System.out.println(accid);
System.out.println(name); A=new Account();

A.show();
System.out.println(balance);
} }
} }
Entity
Class Parametrized
class Account Constructor
{
private int accid; Driver
private String name;
private double balance; Class
public Account(int id, String s, double b) {
accid=id; class CreateAccount
name=n;
balance=b; {
} public static void main(String [] args)
public void show() {
System.out.println(accid); {
System.out.println(name);
Account A;
System.out.println(balance);
} A=new Account(101,”Ravi”,56000);
}
A.show();

}
Lecture - 6

Getter &
Setter
Part-6
Object
Oriented
Programmin
g
What Is Getter and Setter

1. Getter and Setter are methods defined to work upon instance


variables of the class.

2. For each instance variable, a getter method returns its value

3. Setter method sets or updates instance variable value.


Let’s Understand
With Example
Driver
Entity Class Class
class Vehicle { class UseVehicle {
private String color;
public static void main(String[] args) {

Vehicle v1;
public String getColor() {
return color;
v1=new Vehicle();
}
v1.setColor("Red");

public void setColor(String c) { System.out.println(v1.getColor());


this.color = c; }
} }
}
Advantages Of Getter and
Setter
1. It helps us achieve encapsulation

2. Better control over setting the value of the property correctly

3. Achieve immutability by declaring the fields as private and


using only getters
Lecture - 7

Method
Overloadin
Part-7
g

Object
Oriented
Programmin
g
What Is Method Overloading
?

1. Overloading is a concept of OOPS in which we can create


multiple versions of the same entity in the same scope.

2. So , if a class has multiple methods having same name but


different parameters, it is known as Method Overloading.
Benefits of using Method
Overloading. . .minimises the complexity of the code.
1. Method overloading

2. It increases the readability of the program.


How to do Method

In Overloading?
Java, we do method overloading in three ways:

1. By changing data types of parameters.

2. By changing the number of parameters.

3. By changing order of parameters.


By changing data
types.
Driver
Entity Class Class
class Addition{ class UseAddition{
public int add(int a, int b){ public static void main(String[] args){
return a+b; Addition obj;
} obj=new Addition();
public double add(double a, double b){ System.out.println(obj.add(2,4));
return a+b;
} System.out.println(obj.add(22.6,28.7));
}
} }
By changing the
number of
parameters. Driver
Entity Class Class
class Addition{ class UseAddition{
public int add(int a, int b){ public static void main(String[] args){
return a+b; Addition obj;
} obj=new Addition();
public int add(int a,int b,int c){ System.out.println(obj.add(2,11));
return a+b+c; System.out.println(obj.add(6,4,12));
} }
} }
By Changing Order Of
Paramaters
Driver
Entity Class Class
class Addition{ class UseAddition{
private int a; public static void main(String[] args){
private String b; Addition A;
A=new Addition();
public String add(int a, String b){ System.out.println(A.add(2,"Ravi"));
return a+b;
} System.out.println(A.add("Ajay",28));
public String add(String a, int b){ }
return a+b; }
}

}
Lecture - 10
Part-
10
this
Keyword

Object
Oriented
Programmin
g
What Is this keyword ?
➢ “this” is a special object reference, which is also a keyword.

➢ “this” is automatically created by Java in a method’s argument,


as soon we call that method.

➢ “this” stores the memory address of the CURRENT OBJECT (the


object on which the method has been called)
Benefits Of Using “this”. . .

➔ By using “this” we can resolve the overlapping of instance


variable of a class done by the local variables of a method with
the same name.

➔ 2. By using “this” we can perform CONSTRUCTOR CHAINING


Lecture -11 Part-
Inheritance
11
Object
Oriented
Programmin
g
What Is Inheritance?

➔ Inheritance is a technique using which we can


acquire the features of an existing class/object
in a newly created class/object
Let’s Understand
With An Example As per OOP , the
class Orange must
class Fruit
{ inherit the class Fruit
//data
... so that all the
..
. features (data &
//method
} methods) of the Fruit
class Orange
{ class get inherited in
..
} Orange class also
Benefits of Inheritance. . .

➔ Reusability: The child class programmer is not


required to rewrite those methods or data again
which have already been designed by the parent
class programmer

➔ Maintainability: Easy to incorporate changes in the


code
Terminologies Used In
Inheritance
1. The class which gets inherited is knows by 3 names

a. Parent class OOP


b. Base class C++
c. Super class
Java/Python
Terminologies Used In
Inheritance
2. The class which inherits is known by 3
Names

a. Child class OOP


b. Derived class C+
+
c. Sub class
Java/Python
Types Of Inheritance

● Single
● Multilevel
● Multiple
● Hierarchical
● Hybrid
● Note: Java does not support multiple inheritance and
thus it also does not support hybrid inheritance
Single Inheritance:
In Single Inheritance one class extends another class (one class
only).
Multiple Inheritance:
Multiple Inheritance is one of the inheritance in OOP where one class
extends more than one class. Java does not support multiple
inheritance.
Multilevel Inheritance:
In Multilevel Inheritance, one class can inherit from a derived class.
Hence, the derived class becomes the base class for the new class.
Hierarchical Inheritance:
In Hierarchical Inheritance, one class is inherited by many sub classes.
Hybrid Inheritance:
Hybrid inheritance is one of the inheritance types in OOP which is a
combination of Single and Multiple inheritance.
SYNTAX OF INHERITANCE IN JAVA

class <class_name>
{

//body of class

class <class_name> extends <class_name>


{

//body of class

}
Driver
Let’s Understand
Class
With Example
public class Hospital {
public static void main(String args[]) {
Entity Class Surgeon s = new Surgeon();
s.qualification();
s.specialist();
class Doctor { }
public void qualification() {
System.out.println("Qual Details...");
}
}

class Surgeon extends Doctor {


public void specialist() {
System.out.println("Surgeon Detail...");
}
}
Lecture -12 Part-
12
super
Keyword

Object
Oriented
Programmin
g
What Is “super”?

➔ In Java, the keyword “super” is used by a CHILD


CLASS for EXPLICITLY referring (Using dot
operator) the members of its PARENT CLASS.
Let’s Understand Entity Class
With Example
Driver class A
Class {
public void display() {
...
}
B obj=new B(); public void print() {
...
obj.show(); }

}
class B extends A
{
public void show()
{
display();
print();
}
}
Uses of “super”

➔ For calling constructor of PARENT class


from CHILD class

➔ For resolving method overriding


Lecture -13 Part-
13
Method
Overriding

Object
Oriented
Programmin
g
What is Method Overriding

❖ Whenever a child class contains a method with


the same prototype as the parent class, then
we say that the method of child class has
OVERRIDDEN the method of parent class
Let’s Understand Entity Class
With Example
Driver
class DemoA {
Class
public void show(){
class UseDemo {
//Some code
}
public static void main(String
[]args){
}

DemoB obj=new DemoB(); class DemoB extends DemoA {


obj.show();
public void show(){
} //Some other code
} }
}
Question
Why we override a super class method ?
?

Answer :-
To provide better/correct implementation
of that method in child class

Let us understand this with an example


Let’s Understand
Entity Class
With Example
Driver class Fruit{

Class public void taste(){

System.out.println(“Sweet”);
}
class UseFruit{ }

public static void main(String class Grapes extends Fruits{


[]args){
public void taste(){
Grapes G=new Grapes();
G.taste();
System.out.println(“Citrus”);
} }
} }
Role of super in Overriding

➔ If the child class has overriding a method of parent class, but


due to some reason now the programmer of child class also
wants to execute the version of parent class of the overridden
method.

➔ In this case he will use super and the syntax will be:

➔ super.<method_name>(<list_of_arg>);
Method Overriding V/s Method Overloading

Method Overloading Method Overriding

➔ Overloading can be done Overriding can never be done within


either within the same or a single class and it always requires
between methods of PARENT INHERITANCE i.e
& CHILD class overriding can be done between
between of PARENT & CHILD only

➔ Overloading says methods Overriding says methods MUST


must have same, but COMPULSORILY have exactly same
COMPULSORILY different prototype. Although overriding
arguments allows CO-VARIANT return types
Lecture -16 Part-
16
final
keyword

Object
Oriented
Programmin
g
What is “final” keyword in java

➔ final is a non access modifier in java and can


be used in three ways

final

variable method class


“final” variable
➔ final variable: Once we declare a variable as a final we can’t
perform re-assignment.
Let’s Understand With Example

class Circle {
private int radius;
private final double pi = 3.14; //Now this value is
fixed

public Circle(int radius) {


this.radius = radius;
}
}
Another Way To Initialize final Data

class Circle {
private int radius;
private final double pi;

public Circle(int radius) {


this.radius = radius;
pi = 3.14; //Now this value is fixed
}
}
Let’s Understand With Example

class Circle {
private int radius;
private final double pi = 3.14;

public Circle(int radius) {


this.radius = radius;
pi = 5.0; //Error: final cannot be changed
}

}
“final” method

➔ final method: Whenever we declare a method


as a final it can’t be overridden in the child
class.

➔ Let us understand with an Example


//Entity Class
class Bike {
final public void run(){
System.out.println("running");
} Error: Overriding
} a final method is
not allowed
class Honda extends Bike {
public void run() {
System.out.println("running safely with 100kmph");
}
}

// Driver Class
class UseBike {
public static void main(String args[]){
Honda honda= new Honda();
honda.run();
}
}
“final” class

➔ final class: Whenever we declare a


class as final it can’t be extended
or inherited by sub classes.
//Entity Class
final class Bike {
public void run(){
System.out.println("running"); Error: final
} classes cannot
} be inherited

class Honda extends Bike {

}
Some predefined final classes
provide by java
➔ Math
➔ String
➔ All Wrapper Classes like
◆ Integer
◆ Double
◆ Character
◆ etc.
Lecture -17 Part-
Polymorphis
m 17
Object
Oriented
Programmin
g
What is

Polymorphism
The derivation of the word Polymorphism is from two different Greek
words- poly and morph.

➔ “Poly” means multiple, and “Morph” means forms.

➔ So, polymorphism means ability to acquire multiple forms.

Real Life Example of


Polymorphism
Another Example of
Polymorphism
Types of polymorphism in Java

➔ Compile time polymorphism

➔ Runtime polymorphism
Compile time
polymorphism
➢ Compile-time polymorphism is also known as static polymorphism.

➢ To achieve compile time polymorphism we must have different


implementations of the same method in a class.

➢ And this is done using method overloading


Runtime
Part-
18
Polymorphis
m

Object
Oriented
Programmin
g
Runtime
Polymorphism
➢ Runtime polymorphism is also called as Dynamic Method
Dispatch in java.

➢ To achieve Runtime polymorphism in java we must be able to call


different versions of the same method using the same reference
variable.

➢ These methods should be present in child class and the


reference must be of parent class.
How to call area() of
Entity Class
Every Class?
class Rectangle
{
Driver
public void area()
{
Class
... public class UseShape
} {
} public static void main(String[] args)
class Circle {
{ Rectangle r = new
public void area() Rectangle();
{ r.area();
...
} Circle c = new Circle();
} c.area();
class Triangle
{ Triangle t = new Triangle();
public void area() t.area();
{ } Although it works, but it
... }
}
is
} not runtime
polymorphism
Runtime
Polymorphism
➢ But to Understand how this concepts works we
must first understand the concept of binding.
What Is Binding ?
★ The word binding is the mechanism using the
compiler decides that which function call which
function body will get executed.
In Java we have 2 types of binding

a. Early binding Or Compile time binding or static


binding

b. Late binding or runtime binding or dynamic binding


Types of
Part-
19
Binding

Object
Oriented
Programmin
g
Early Binding
❖ If the method being called is a static method, then
java selects the method by looking at the (class) of
the reference used in the call and not the type of
object to which the reference is pointing.
Let’s Understand
Entity Class
With Example
class Parent
{
Driver
public static void show()
{
Class
...
}
}
public class UseShape
class Child extends Parent
{
{
public static void main(String[] args)
public static void show()
{
{
Parent p = new Child
...
();
}
p.show();
}
}
Which method will }
execute ?
Late Binding

❖ If the method being called is a non-static method i.e


instance method, then Java selects the method by
considering the type of object, pointed by the
reference and not considering the type of reference
itself
Let’s Understand
Entity Class
With Example
class Parent
{
Driver
public void show()
{
Class
...
}
}
public class UseShape
class Child extends Parent
{
{
public static void main(String[] args)
public void show()
{
{
Parent p=new
...
Child();
}
p.show();
}
}
Which method will }
execute ?
Abstract
Method & class Part-
21
Object
Oriented
Programmin
g
Find The Problem In This Code?

class Language{

public void greetings(){

}
}

➔ The problem with the code is that we have left the body
of the method greetings() empty

➔ This is because we don’t have any suitable logic for the


method greetings() in the class Language
Can we improve it ?
➔ Yes we can improve it by removing the body of the method and
just declaring it in the class Language

➔ But to do this we must prefix the method as well as the class


with the keyword abstract

For ex:-

abstract class Language


{

abstract public void greetings();


}
When we should declare a method as
abstract ?

➔ There are situations when we have a method in super class which


cannot be implemented properly due to lack of information in
super class.

➔ But we need this method for achieving runtime polymorphism and


thus in such cases we must declare a method as abstract.
For ex:-

➔ Suppose we have class called Instrument and the class has


a method called sound ().

➔ What will be the implementation of sound () in the


Instrument ?
Entity Class Let’s Understand
With Example
class Instrument{
Driver
public void sound(){
Class
}
} class UseInstrument{
class Violin extends Instrument{ public static void main(String args[]){
Instrument I1;
public void sound(){ I1=new Violin();
... I1.sound();
} I1=new Guitar();
} I1.sound();
}
class Guitar extends Instrument{
}
public void sound(){
... What is the
}
implementatio
}
n?
Entity Class
Improved
abstract class Instrument{
Driver
version
abstract public void sound();
Class
}
class Violin extends Instrument{ class UseInstrument{
public static void main(String args[]){
public void sound(){ Instrument I1;
... I1=new Violin();
} I1.sound();
} I1=new Guitar();
class Guitar extends Instrument{ I1.sound();
}
}
public void sound(){
...
}
}
Abstract
Method &
class

Object
Oriented
Programmin
g
Some important points
★ To make a method abstract it is compulsory to use the
keyword abstract in the method prototype.

★ An abstract method should never have any implementation


in the class where it is being declared.

★ If a method has been declared as “abstract” in the class,


then the class itself must be prefixed with the keyword
abstract
For:- example

class A
{
public abstract void show();
}
Error
!
abstract class A
{
public
Nowvoid
abstract it show();
is OK }
Some important points

★ If a class is abstract then we are not allowed to


create its “object” .

★ Although we can create reference of the class.

A obj;// Ok
obj=new A();// Error
Some important points
★ An abstract class can CONTAIN concrete methods as well
as Constructors.

★ This is because abstract classes can be inherited and these


methods can be inherited and these methods can be
accessed by the objects of child classes.
Some important points
★ If a class inherits an abstract class then

○ Either it must compulsorily override all the abstract


methods inherited from the super class.

OR

○ The child class itself will have to be prefix with the


keyword abstract and we won’t be allowed to create its
object also.
Abstract Part-
23
Object
Oriented
Programmin
g
Which methods cannot be declared as
abstract ?
➢ Static Methods

➢ Constructors

➢ Private methods

➢ Final methods
Interface Part-
24
Object
Oriented
Programmin
g
What is an interface?

➔ An interface is almost same as a pure abstract class.

➔ Just like a class or abstract class an interface also can


contain data members.
What is an interface?

➔ But every data declared in an interface is automatically


converted to “public” “static” and “final” by java.

➔ An interface can also contain methods but every method


by default is “public” and “abstract”

➔ However from java 8, an interface can also contain


“default” and “static” methods
What is an interface?

➔ Just like we cannot instantiate an abstract class, similarly


we also cannot instantiate an interface

➔ However we can create a reference of an interface.


What is an interface?

➔ Just like an abstract class an interface also can be inherited


by child classes but the keyword used for this inheritance is
implements.

➔ The reference of an interface can point to the object of its


implementation class or child class

➔ And this forms the basis of runtime polymorphism


What is an interface?

➔ If a class inherits an interface then it is compulsory to


override every abstract method inherited from the
interface.

➔ Otherwise, the derived class also will have to be declared


as abstract.
Syntax of declaring an interface

interface <interface_name>
{
<data_type> <var_name>=<value>;
.
.
.
<return_type> <method_name> (list_of_arg);
.
.
.
}
Let’s Understand With Example

Interface declaration

public interface Animal {


void makeSound();
void eat();
}

//Both the above methods are by default


public and abstract
Let’s Understand With Example
Entity class

public class Elephant implements Animal {


@Override
public void makeSound() {
System.out.println("Trumpet!");
}

@Override
public void eat() {
System.out.println("Elephant eats grasses and leaves");
}
}
Let’s Understand With Example
Entity class

public class Lion implements Animal {


@Override
public void makeSound() {
System.out.println("Roar!");
}

@Override
public void eat() {
System.out.println("Lion eats flesh");
}
}
Let’s Understand With Example
Driver class
class UseAnimal{
public static void main(Sring []args){
Animal obj;

obj= new Elephant();


obj.makeSound();
obj.eat();

obj= new Lion();


obj.makeSound();
obj.eat();
}
}
Abstract Class
vs
Part-
Interface
25
Object
Oriented
Programmin
g
Abstract Interface
Class
1) Interface can have only abstract
1) Abstract class can have abstract and
methods. Since Java 8, it can have default
non-abstract methods.
and static methods also.

2) Abstract class doesn't support 2) Interface supports multiple


multiple inheritance. inheritance.

3) Abstract class can have final, non- 3) Interface has only static and final
final, static and non-static variables. variables.
Abstract Interface
Class
4) Abstract class can provide the 4) Interface can't provide the
implementation of interface. implementation of abstract class.

5) The abstract keyword is used to 5) The interface keyword is used to


declare abstract class. declare interface. we

6) An abstract class can extend another 6) An interface can extend another


Java class and implement multiple Java interface only. However it can extend
interfaces. multiple interfaces.
Abstract Interface
Class
7) An abstract class can be extended 7) An interface can be implemented using
using keyword "extends". keyword "implements".

8) Members of a Java interface are public


8) A Java abstract class can have class by default. But from java 9 onwards
members like private, protected, etc. methods of an interface can also be
declared as private

9) Example: 9) Example:

public abstract class Shape{ public interface Drawable{


public abstract void draw(); void draw();
} }
Association
Part-
26
Object
Oriented
Programmin
g
Java has two types of relationship
1. Inheritance (IS-A)

2. Association (HAS-A)
What Is Inheritance ?
1. Inheritance (IS-A)

★ An IS-A relationship signifies that one object is a type of another.

★ For Example:

○ CAR IS-A vehicle

○ Apple IS-A fruit

○ Circle IS-A shape

★ It is implemented using “extends” or “implements” keywords.


Driver
Let’s Understand
Class
With Example

Entity Class public class UseCar {

class Vehicle { public static void main(String


args[]){
//Some Code
Car car = new Car();
}
//Some More Code
class Car extends Vehicle{
}
}
//Some Code
}
What Is Association ?
2. Association (HAS-A)

★ A HAS-A relationship signifies that a class is associated with that is it holds object(s)
of another class in its body

★ For Example:

○ Car has Engine

○ College has Students

○ House has Rooms

★ For instance, class A holds class B’s reference and can access all properties of class
B.
Entity Class Let’s Understand
class Engine { With Example
public void start() {
//Some Code Driver
}
} Class
class MusicPlayer {
public void start() {
//Some Code public class UseCar{
}
}
public static void main(String
class Car { args[]){
Engine engine = new Engine();
MusicPlayer player = new
MusicPlayer(); Car car = new Car();
car.startEngine();
public void startEngine() { car.startMusicPlayer();
engine.start();
}
public void startMusicPlayer() { //Some More Code
player.start(); }
}
}
}
Types of Relationship
Types
Part-
of
Association
27
Object
Oriented
Programmin
g
What Is Association ?
A HAS-A relationship signifies that a class is associated with that is it holds object(s)
of another class in its body

★ For Example:

○ Car has Engine

○ College has Students

○ Building has Rooms

★ In simple words we can say that, class A holds class B’s reference and can
access methods of class B.
Types Of
Association
Aggregation
★ Aggregation is often represented using a "has-a" relationship.

★ For example, a car object "has-a" music player object.

★ Similarly, a computer object "has-a" hard drive object and so on.

★ In aggregation, the component object can exist independently of the


container object.
Let’s Understand
With Example

class MusicPlayer {
public void start() {
//Some Code
}
}

class Car {
private String name;
private MusicPlayer player;
}
Types
Part-
of
Association
28
Object
Oriented
Programmin
g
Composition
➔ A composition in Java between two objects associated with each other exists
when there is a strong relationship between one class and another.

➔ Means contained object cannot exist without the owner or container object.

➔ For example, A College is a composition of Department. If the College object


doesn’t exist or dies then Department object will also not exist

➔ Thus we can say that composition is a restricted form of Aggregation.


Implementation of Composition in
Java
➔ The College and Department relationship is implemented using the
concept of inner class in Java.

➔ Also we use, the “final” keyword while representing composition.

➔ This is because the ‘Owner’ object expects a part object to be


available and function by making it “final”.

You might also like