OOPS Concepts in Java PDF Download PDF
OOPS Concepts in Java PDF Download PDF
OOPS Concepts in Java PDF Download PDF
By Java Guides
1. Object
2. Class
3. Abstraction
4. Encapsulation
5. Inheritance
6. Polymorphism
1. Object
The Object is the real-time entity having some state and behavior. In Java, Object is
an instance of the class having the instance variables like the state of the object and
the methods as the behavior of the object. The object of a class can be created by
using the new keyword in Java Programming language.
A class is a template or blueprint from which objects are created. So, an object is the
instance(result) of a class.
Bicycles also have state (current gear, current pedal cadence, current speed)
and behavior (changing gear, changing pedal cadence, applying brakes).
How to Declare, Create and Initialize an Object in
Java
A class is a blueprint for Object, you can create an object from a class. Let's take Student
class and try to create Java object for it.
Let's create a simple Student class which has name and college fields. Let's write a program
to create declare, create and initialize a Student object in Java.
package net.javaguides.corejava.oops;
Instantiation: The new keyword is a Java operator that creates the object.
Initialization: The new operator is followed by a call to a constructor, which initializes the
new object.
type name;
This notifies the compiler that you will use a name to refer to data whose type is a type. With
a primitive variable, this declaration also reserves the proper amount of memory for the
variable.
From the above program, we can declare variables to refer to an object as:
Student student;
Student student2;
Student student3;
Instantiating a Class
The new operator instantiates a class by allocating memory for a new object and
returning a reference to that memory. The new operator also invokes the object
constructor.
For example:
Read more about Objects in Java with examples at What Is Object in Java with Programming
Examples.
2. Class
A class is a group of objects which have common properties. It is a template or blueprint
from which objects are created. In short, a class is the specification or template of an
object.
A real-world example is Circle. Let’s look at an example of a class and analyze its various
parts in a below diagram. This example declares the class Circle, which has the member-
variables x, y, and radius of type Integer and the two member-
methods, area()and fillColor().
package net.javaguides.corejava.oops;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public Student() {
super();
}
Read more about Class in java with examples at What is Class in Java with Programming
Examples.
3. Abstraction
Abstraction means hiding lower-level details and exposing only the essential and
relevant details to the users.
Real-world examples
1. The first example, let's consider a Car, which abstracts the internal details and
exposes to the driver only those details that are relevant to the interaction of
the driver with the Car.
Let's create Contractor and FullTimeEmployee classes as we know that the salary structure
for a contractor and full-time employees are different so let these classes to override and
implement a calculateSalary() method.
Let's write source code by looking into an above class diagram.
Step 1: Let's first create the superclass Employee. Note the usage of abstract keyword in this
class definition. This marks the class to be abstract, which means it can not be instantiated
directly. We define a method called calculateSalary() as an abstract method. This way you
leave the implementation of this method to the inheritors of the Employee class.
Step 2: The Contractor class inherits all properties from its parent abstract Employee class
but have to provide its own implementation to calculateSalary() method. In this case, we
multiply the value of payment per hour with given working hours.
Read more about Abstraction in Java with examples at Abstraction in Java with
Example.
4. Encapsulation
Encapsulation is a process of wrapping of data and methods in a single unit is called
encapsulation.
In OOP, data and methods operating on that data are combined together to form a single
unit, which is referred to as a Class.
Real-world examples
1. Capsule, it is wrapped with different medicines. In a capsule, all medicine is
encapsulated inside a capsule.
2. A Java class is an example of encapsulation. Java bean is the fully encapsulated class
because all the data members are private here.
Implementation with Example
Consider below Person class diagram, the id and name parameters should not be
accessed directly outside Person class - achieved by private declaration.
public Person() {
// Only Person class can access and assign
id = Math.random();
sayHello();
}
// This method is protected for giving access within Person class only
private void sayHello() {
System.out.println("Hello - " + getId());
}
Encapsulation is a process of binding or wrapping the data and the codes that
operate on the data into a single entity. This keeps the data safe from outside
interface and misuse.
Abstraction is the concept of hiding irrelevant details. In other words, make the
complex system simple by hiding the unnecessary detail from the user.
Abstraction is implemented in Java using interface and abstract class
while Encapsulation is implemented using private, package-private and protected
access modifiers.
Abstraction solves the problem in the design level. Whereas Encapsulation solves
the problem in the implementation level.
Real-world example
1. The real-life example of inheritance is child and parents, all the properties of a father
are inherited by his son.
2. In the Java library, you can see extensive use of inheritance. Below figure shows a
partial inheritance hierarchy from a java.lang library. The Number class abstracts
various numerical (reference) types such as Byte, Integer, Float, Double, Short,
and BigDecimal.
Implementation with Example
Example 1: Let's understand inheritance by example.
Dog class is inheriting behavior and properties of Animal class and can have its own
too.
/**
* Test class for inheritance behavior - Dog class is inheriting behavior
* and properties of Animal class and can have its own too.
*
*
*/
public class Inheritance {
/**
* This is parent (also called as super or base) class Animal
*
*/
class Animal {
int id;
/**
* This is subclass (also called as derived or child or extended) Dog which is
extending Animal
*
*/
class Dog extends Animal {
// Own behavior
private void bark() {
System.out.println("Dog '" + getId() + "' is barking");
}
Example 2: In this example, the Programmer is the subclass and Employee is the
superclass. The relationship between the two classes is the Programmer IS-A
Employee. It means that Programmer is a type of Employee.
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
Types of Inheritance in Java
Below are the different types of inheritance which are supported by Java.
1. Single Inheritance
In single inheritance, subclasses inherit the features of one superclass. In the image below,
class A serves as a base class for the derived class B.
2. Multilevel Inheritance
In Multilevel Inheritance, a derived class will be inheriting a base class and as well as the
derived class also act as the base class to other class. In below image, class A serves as a
base class for the derived class B, which in turn serves as a base class for the derived class C.
In Java, a class cannot directly access the grand parent’s members.
3. Hierarchical Inheritance
In Hierarchical Inheritance, one class serves as a superclass (base class) for more than one
subclass. In below image, class A serves as a base class for the derived class B and class C.
In Multiple inheritances, one class can have more than one superclass and inherit features
from all parent classes. Please note that Java does not support multiple inheritances with
classes. In Java, we can achieve multiple inheritances only through Interfaces. In the image
below, Class C is derived from class A and class B.
5. Hybrid Inheritance (Through Interfaces)
It is a mix of two or more of the above types of inheritance. Since java doesn’t support
multiple inheritances with classes, the hybrid inheritance is also not possible with classes. In
java, we can achieve hybrid inheritance only through Interfaces.
Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes.
If A and B classes have the same method and you call it from child class object, there will be
ambiguity to call a method of A or Bclass.
Since compile-time errors are better than runtime errors, java renders compile-time error if
you inherit 2 classes. So whether you have the same method or different, there will be
compile time error now.
class A{
void msg(){System.out.println("Hello");}
}
class B{
void msg(){System.out.println("Welcome");}
}
class C extends A,B{//suppose if it were
p = new CreditPayment();
p.pay(); // Pay by creditcard
}
/**
* This represents payment interface
*/
interface Payment {
public void pay();
}
/**
* Cash IS-A Payment type
*
* @author tirthalp
*
*/
class CashPayment implements Payment {
// method overriding
@Override
public void pay() {
System.out.println("This is cash payment");
}
/**
* Creditcard IS-A Payment type
*/
class CreditPayment implements Payment {
// method overriding
@Override
public void pay() {
System.out.println("This is credit card payment");
}
}
Types of Polymorphism in Java
1. Compile time polymorphism or method overloading or static banding
2. Runtime polymorphism or method overriding or dynamic binding
When a type of the object is determined at a compiled time(by the compiler), it is known
as static binding.
The compiler will resolve the call to a correct method depending on the actual number
and/or types of the passed parameters The advantage of method overloading is to increases
the readability of the program.
In this example, we are creating static methods so that we don't need to create an instance
for calling methods.
class Adder {
static int add(int a, int b) {
return a + b;
}
static int add(int a, int b, int c) {
return a + b + c;
}
}
class TestOverloading1 {
public static void main(String[] args) {
System.out.println(Adder.add(11, 11));
System.out.println(Adder.add(11, 11, 11));
}
}
In this example, we have created two methods that differ in data type. The first add method
receives two integer arguments and second add method receives two double arguments.
class Adder {
static int add(int a, int b) {
return a + b;
}
static double add(double a, double b) {
return a + b;
}
}
class TestOverloading2 {
public static void main(String[] args) {
System.out.println(Adder.add(11, 11));
System.out.println(Adder.add(12.3, 12.6));
}
}
2. Runtime Polymorphism
Runtime polymorphism is a process in which a call to an overridden method is resolved at
runtime rather than compile-time.
Upcasting
When reference variable of Parent class refers to the object of Child class, it is known as
upcasting.
For example:
class A {}
class B extends A {}
class Demo {
public static void main(String[] args) {
A a = new B(); //upcasting
}
}
Java Runtime Polymorphism Example: Shape
Example
class Shape {
void draw() {
System.out.println("drawing...");
}
}
class Rectangle extends Shape {
void draw() {
System.out.println("drawing rectangle...");
}
}
class Circle extends Shape {
void draw() {
System.out.println("drawing circle...");
}
}
class Triangle extends Shape {
void draw() {
System.out.println("drawing triangle...");
}
}
class TestPolymorphism2 {
public static void main(String args[]) {
Shape s;
s = new Rectangle();
s.draw();
s = new Circle();
s.draw();
s = new Triangle();
s.draw();
}
}
Output:
drawing rectangle...
drawing circle...
drawing triangle...
Java Runtime Polymorphism with Data Member
The method is overridden not applicable data members, so runtime polymorphism can't be
achieved by data members.
In the example given below, both the classes have a data member speedlimit, we are
accessing the data member by the reference variable of Parent class which refers to the
subclass object. Since we are accessing the data member which is not overridden, hence it
will access the data member of Parent class always.
class Bike {
int speedlimit = 90;
}
class Honda extends Bike {
int speedlimit = 150;
Output:
90
Let's try the below scenario: Here the BabyDog is not overriding the eat() method,
so eat() method of Dog class is invoked. Note that if we are not using @Override
annotation in this example.
class Animal {
void eat() {
System.out.println("animal is eating...");
}
}
class Dog extends Animal {
void eat() {
System.out.println("dog is eating...");
}
}
class BabyDog1 extends Dog {
public static void main(String args[]) {
Animal a = new BabyDog1();
a.eat();
}
}
Output:
dog is eating...
Polymorphism - Method Overloading vs Method
Overriding
>> Composition in Java with Example - In this article, we will learn Composition
with real-world examples, class diagram and implementation with lots of examples.
>> Aggregation in Java with Example - In this article, we will learn Aggregation
with real-world examples, class diagram and implementation with lots of examples.
>> Association in Java with Example - In this article, we will learn the Association
with real-world examples, class diagram and implementation with lots of examples.
References
Abstraction in Java with Example
Encapsulation in Java with Example
Inheritance in Java with Example
Polymorphism in Java with Example
Composition in Java with Example
Aggregation in Java with Example
Association in Java with Example
Cohesion in Java with Example
Coupling in Java with Example
Delegation in Java with Example