Java OOPS
Java OOPS
com
9123820085
JAVA OOPS
kasper-analytics
kasperanalytics.com
9123820085
1. Object
2. Class
3. Abstraction
4. Encapsulation
5. Inheritance
6. Polymorphism
kasper-analytics
kasperanalytics.com
9123820085
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.
Real-world examples
• Dogs have state (name, color, breed, hungry) and behavior (barking,
fetching, wagging tail). Chair, Bike, Marker, Pen, Table, Car, Book, Apple, Bag
etc. It can be physical or logical (tangible and intangible).
kasper-analytics
kasperanalytics.com
9123820085
• Bicycles also have state (current gear, current pedal cadence, current
speed) and behavior (changing gear, changing pedal cadence, applying
brakes).
kasper-analytics
kasperanalytics.com
9123820085
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.
kasper-analytics
kasperanalytics.com
9123820085
package net.javaguides.corejava.oops;
Instantiation: The new keyword is a Java operator that creates the object.
kasper-analytics
kasperanalytics.com
9123820085
General syntax:
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:
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:
kasper-analytics
kasperanalytics.com
9123820085
Initializing an Object
The new keyword is followed by a call to a constructor, which initializes the new
object. For example:
kasper-analytics
kasperanalytics.com
9123820085
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().
Below diagram shows a Circle class which is a template to create three objects:
kasper-analytics
kasperanalytics.com
9123820085
Let's demonstrate how to create Class in Java with an example. Here is a Student
class:
package net.javaguides.corejava.oops;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class Student { private
String name = "Ramesh"; private
String college = "ABC";
public Student() {
super();
}
public Student(String name, String college) {
super(); this.name = name; this.college =
college;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCollege() {
return college;
}
public void setCollege(String college) {
this.college = college;
}
}
kasper-analytics
kasperanalytics.com
9123820085
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.
kasper-analytics
kasperanalytics.com
9123820085
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.
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
kasper-analytics
kasperanalytics.com
9123820085
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.
kasper-analytics
kasperanalytics.com
9123820085
kasper-analytics
kasperanalytics.com
9123820085
4. 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
kasper-analytics
kasperanalytics.com
9123820085
Consider below Person class diagram, the id and name parameters should not be
accessed directly outside Person class - achieved by private declaration.
kasper-analytics
kasperanalytics.com
9123820085
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());
}
public double getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) { this.name
= name;
}
}
kasper-analytics
kasperanalytics.com
9123820085
kasper-analytics
kasperanalytics.com
9123820085
kasper-analytics
kasperanalytics.com
9123820085
5. Inheritance
The Inheritance is a process of obtaining the data members and methods from
one class to another class, plus can have its own is known as inheritance. It is one
of the fundamental features of object-oriented programming.
Super Class: The class whose features are inherited is known as a superclass (or a
base class or a parent class).
Sub Class: The class that inherits the other class is known as a subclass(or a
derived class, extended class, or child class). The subclass can add its own fields
and methods in addition to the superclass fields and methods.
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.
kasper-analytics
kasperanalytics.com
9123820085
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.
Dog class is inheriting behavior and properties of Animal class and can have its
own too.
kasper-analytics
kasperanalytics.com
9123820085
/**
* Test class for inheritance behavior - Dog class is inheriting behavior * and
properties of Animal class and can have its own too.
*
*
*/ public class Inheritance {
public static void main(String[] args) { Animal
dog = new Dog();
dog.setId(123); // inherited from super class dog.sound(); //
overrided behavior of sub class
}
}
/**
* This is parent (also called as super or base) class Animal
*
*/ class Animal {
int id;
public int getId() { return id;
}
public void setId(int id) { this.id =
id;
}
/**
* This is subclass (also called as derived or child or extended) Dog which is
extending Animal
*
*/ class Dog extends
Animal {
kasper-analytics
kasperanalytics.com
9123820085
Syntax :
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.
kasper-analytics
kasperanalytics.com
9123820085
Below are the different types of inheritance which are supported by Java.
1. Single Inheritance
2. Multilevel Inheritance
kasper-analytics
kasperanalytics.com
9123820085
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.
kasper-analytics
kasperanalytics.com
9123820085
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.
kasper-analytics
kasperanalytics.com
9123820085
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.
To reduce the complexity and simplify the language, multiple inheritance is not
supported in java.
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
kasper-analytics
kasperanalytics.com
9123820085
6. Polymorphism
Suppose if you are in a classroom that time you behave like a student, when you
are in the market at that time you behave like a customer, when you at your
home at that time you behave like a son or daughter, Here one person present in
different-different behaviors.
kasper-analytics
kasperanalytics.com
9123820085
kasper-analytics
kasperanalytics.com
9123820085
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");
}
kasper-analytics
kasperanalytics.com
9123820085
If the class contains two or more methods having the same name and different
arguments then it is method overloading.
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 have created two methods, first, add() method performs the
addition of two numbers and a second add method performs addition of three
numbers.
In this example, we are creating static methods so that we don't need to create
an instance for calling methods.
kasper-analytics
kasperanalytics.com
9123820085
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.
2. Runtime Polymorphism
kasper-analytics
kasperanalytics.com
9123820085
being referred to by the reference variable. Let's first understand the upcasting
before Runtime Polymorphism.
When reference variable of Parent class refers to the object of Child class, it is
known as upcasting.
For example:
kasper-analytics
kasperanalytics.com
9123820085
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:
kasper-analytics
kasperanalytics.com
9123820085
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.
Output:
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.
kasper-analytics
kasperanalytics.com
9123820085
Output:
kasper-analytics