Object Oriented Programming

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 42

Object Oriented Programming (OOPs) Concept in Java

Object-oriented programming: As the name suggests, Object-Oriented Programming or OOPs


refers to languages that uses objects in programming. Object-oriented programming aims to
implement real-world entities like inheritance, hiding, polymorphism etc in programming. The main
aim of OOP is to bind together the data and the functions that operate on them so that no other part
of the code can access this data except that function.
OOPs Concepts:
 Polymorphism
 Inheritence
 Encapsulation
 Abstraction
 Class
 Object
 Method
 Message Passing
Let us learn about the different characteristics of an Object Oriented Programming language:
1. Polymorphism: Polymorphism refers to the ability of OOPs programming languages to
differentiate between entities with the same name efficiently. This is done by Java with the help
of the signature and declaration of these entities.
For example:
filter_none
edit
play_arrow
brightness_4
// Java program to demonstrate Polymorphism

// This class will contain


// 3 methods with same name,
// yet the program will
// compile & run successfully
public class Sum {

// Overloaded sum().
// This sum takes two int parameters
public int sum(int x, int y)
{
return (x + y);
}

// Overloaded sum().
// This sum takes three int parameters
public int sum(int x, int y, int z)
{
return (x + y + z);
}

// Overloaded sum().
// This sum takes two double parameters
public double sum(double x, double y)
{
return (x + y);
}

// Driver code
public static void main(String args[])
{
Sum s = new Sum();
System.out.println(s.sum(10, 20));
System.out.println(s.sum(10, 20, 30));
System.out.println(s.sum(10.5, 20.5));
}
}
Output:
30
60
31.0
Polymorphism in Java are mainly of 2 types:
 Overloading in Java
 Overriding in Java
2. Inheritence: Inheritance is an important pillar of OOP(Object Oriented Programming). It is the
mechanism in java by which one class is allow to inherit the features(fields and methods) of
another class.
Important terminology:

 Super Class: The class whose features are inherited is known as superclass(or a base
class or a parent class).
 Sub Class: The class that inherits the other class is known as 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.
 Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create
a new class and there is already a class that includes some of the code that we want, we
can derive our new class from the existing class. By doing this, we are reusing the fields
and methods of the existing class.
The keyword used for inheritance is extends.
Syntax:
class derived-class extends base-class
{
//methods and fields
}
3. Encapsulation: Encapsulation is defined as the wrapping up of data under a single unit. It is
the mechanism that binds together code and the data it manipulates.Other way to think about
encapsulation is, it is a protective shield that prevents the data from being accessed by the
code outside this shield.
 Technically in encapsulation, the variables or data of a class is hidden from any other
class and can be accessed only through any member function of own class in which they
are declared.
 As in encapsulation, the data in a class is hidden from other classes, so it is also known
as data-hiding.
 Encapsulation can be achieved by: Declaring all the variables in the class as private and
writing public methods in the class to set and get the values of variables.

4. Abstraction: Data Abstraction is the property by virtue of which only the essential details are
displayed to the user.The trivial or the non-essentials units are not displayed to the user. Ex: A
car is viewed as a car rather than its individual components.
Data Abstraction may also be defined as the process of identifying only the required
characteristics of an object ignoring the irrelevant details. The properties and behaviours of an
object differentiate it from other objects of similar type and also help in classifying/grouping the
objects.
Consider a real-life example of a man driving a car. The man only knows that pressing the
accelerators will increase the speed of car or applying brakes will stop the car but he does not
know about how on pressing the accelerator the speed is actually increasing, he does not know
about the inner mechanism of the car or the implementation of accelerator, brakes etc in the
car. This is what abstraction is.
In java, abstraction is achieved by interfaces and abstract classes. We can achieve 100%
abstraction using interfaces.
5. Class: A class is a user defined blueprint or prototype from which objects are created. It
represents the set of properties or methods that are common to all objects of one type. In
general, class declarations can include these components, in order:
1. Modifiers : A class can be public or has default access (Refer this for details).
2. Class name: The name should begin with a initial letter (capitalized by convention).
3. Superclass(if any): The name of the class’s parent (superclass), if any, preceded by the
keyword extends. A class can only extend (subclass) one parent.
4. Interfaces(if any): A comma-separated list of interfaces implemented by the class, if any,
preceded by the keyword implements. A class can implement more than one interface.
5. Body: The class body surrounded by braces, { }.
6. Object: It is a basic unit of Object Oriented Programming and represents the real life entities.
A typical Java program creates many objects, which as you know, interact by invoking
methods. An object consists of :
0. State : It is represented by attributes of an object. It also reflects the properties of an
object.
1. Behavior : It is represented by methods of an object. It also reflects the response of an
object with other objects.
2. Identity : It gives a unique name to an object and enables one object to interact with other
objects.
Example of an object : dog

7. Method: A method is a collection of statements that perform some specific task and return
result to the caller. A method can perform some specific task without returning anything.
Methods allow us to reuse the code without retyping the code. In Java, every method must be
part of some class which is different from languages like C, C++ and Python.
Methods are time savers and help us to reuse the code without retyping the code.
Method Declaration
In general, method declarations has six components :
 Modifier-: Defines access type of the method i.e. from where it can be accessed in your
application. In Java, there 4 type of the access specifiers.
 public: accessible in all class in your application.
 protected: accessible within the class in which it is defined and in its subclass(es)
 private: accessible only within the class in which it is defined.
 default (declared/defined without using any modifier) : accessible within same class
and package within which its class is defined.
 The return type : The data type of the value returned by the the method or void if does
not return a value.
 Method Name : the rules for field names apply to method names as well, but the
convention is a little different.
 Parameter list : Comma separated list of the input parameters are defined, preceded with
their data type, within the enclosed parenthesis. If there are no parameters, you must use
empty parentheses ().
 Exception list : The exceptions you expect by the method can throw, you can specify
these exception(s).
 Method body : it is enclosed between braces. The code you need to be executed to
perform your intended operations.

8. Message Passing: Objects communicate with one another by sending and receiving
information to each other. A message for an object is a request for execution of a procedure
and therefore will invoke a function in the receiving object that generates the desired results.
Message passing involves specifying the name of the object, the name of the function and the
information to be sent.

Recommended Posts:

 OOPs | Object Oriented Design


 Why Java is not a purely Object-Oriented Language?
 Aspect Oriented Programming and AOP in Spring Framework
 OOPS | Generalization as extension and restriction using Java
 Java tricks for competitive programming (for Java 8)
 Object class in Java
 Stack add(int, Object) method in Java with Example
 Stack add(Object) method in Java with Example
 Object toString() Method in Java
 Object Graph in Java Serialization
 AbstractSequentialList set(int, Object) method in Java with Example
 Object Serialization with Inheritance in Java
 Stack lastIndexOf(Object, int) method in Java with Example
 Understanding Object Cloning in Java with Examples
 Stack remove(Object) method in Java with Example
Inheritance in Java
Inheritance is an important pillar of OOP(Object Oriented Programming). It is the mechanism in java
by which one class is allow to inherit the features(fields and methods) of another class.
Important terminology:
 Super Class: The class whose features are inherited is known as super class(or a base class
or a parent class).
 Sub Class: The class that inherits the other class is known as sub class(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.
 Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a
new class and there is already a class that includes some of the code that we want, we can
derive our new class from the existing class. By doing this, we are reusing the fields and
methods of the existing class.

How to use inheritance in Java


The keyword used for inheritance is extends.
Syntax :
class derived-class extends base-class
{
//methods and fields
}
Example: In below example of inheritance, class Bicycle is a base class, class MountainBike is a
derived class which extends Bicycle class and class Test is a driver class to run program.
filter_none
edit
play_arrow
brightness_4
//Java program to illustrate the
// concept of inheritance

// base class
class Bicycle
{
// the Bicycle class has two fields
public int gear;
public int speed;

// the Bicycle class has one constructor


public Bicycle(int gear, int speed)
{
this.gear = gear;
this.speed = speed;
}

// the Bicycle class has three methods


public void applyBrake(int decrement)
{
speed -= decrement;
}

public void speedUp(int increment)


{
speed += increment;
}

// toString() method to print info of Bicycle


public String toString()
{
return("No of gears are "+gear
+"\n"
+ "speed of bicycle is "+speed);
}
}

// derived class
class MountainBike extends Bicycle
{

// the MountainBike subclass adds one more field


public int seatHeight;

// the MountainBike subclass has one constructor


public MountainBike(int gear,int speed,
int startHeight)
{
// invoking base-class(Bicycle) constructor
super(gear, speed);
seatHeight = startHeight;
}

// the MountainBike subclass adds one more method


public void setHeight(int newValue)
{
seatHeight = newValue;
}

// overriding toString() method


// of Bicycle to print more info
@Override
public String toString()
{
return (super.toString()+
"\nseat height is "+seatHeight);
}

// driver class
public class Test
{
public static void main(String args[])
{

MountainBike mb = new MountainBike(3, 100, 25);


System.out.println(mb.toString());

}
}
Output:
No of gears are 3
speed of bicycle is 100
seat height is 25
In above program, when an object of MountainBike class is created, a copy of the all methods and
fields of the superclass acquire memory in this object. That is why, by using the object of the
subclass we can also access the members of a superclass.
Please note that during inheritance only object of subclass is created, not the superclass. For more,
refer Java Object Creation of Inherited Class.
Illustrative image of the program:

In practice, inheritance and polymorphism are used together in java to achieve fast performance and
readability of code.
Types of Inheritance in Java
Below are the different types of inheritance which is supported by Java.
1. Single Inheritance : In single inheritance, subclasses inherit the features of one superclass. In
image below, the class A serves as a base class for the derived class B.
filter_none
edit
play_arrow
brightness_4
//Java program to illustrate the
// concept of single inheritance
import java.util.*;
import java.lang.*;
import java.io.*;

class one
{
public void print_geek()
{
System.out.println("Geeks");
}
}

class two extends one


{
public void print_for()
{
System.out.println("for");
}
}
// Driver class
public class Main
{
public static void main(String[] args)
{
two g = new two();
g.print_geek();
g.print_for();
g.print_geek();
}
}
Output:
Geeks
for
Geeks

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, the
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 grandparent’s members.

filter_none
edit
play_arrow
brightness_4
// Java program to illustrate the
// concept of Multilevel inheritance
import java.util.*;
import java.lang.*;
import java.io.*;

class one
{
public void print_geek()
{
System.out.println("Geeks");
}
}

class two extends one


{
public void print_for()
{
System.out.println("for");
}
}

class three extends two


{
public void print_geek()
{
System.out.println("Geeks");
}
}

// Drived class
public class Main
{
public static void main(String[] args)
{
three g = new three();
g.print_geek();
g.print_for();
g.print_geek();
}
}
Output:
Geeks
for
Geeks
3. Hierarchical Inheritance : In Hierarchical Inheritance, one class serves as a superclass (base
class) for more than one sub class.In below image, the class A serves as a base class for the
derived class B,C and D.
filter_none
edit
play_arrow
brightness_4
// Java program to illustrate the
// concept of Hierarchical inheritance
import java.util.*;
import java.lang.*;
import java.io.*;

class one
{
public void print_geek()
{
System.out.println("Geeks");
}
}

class two extends one


{
public void print_for()
{
System.out.println("for");
}
}

class three extends one


{
/*............*/
}

// Drived class
public class Main
{
public static void main(String[] args)
{
three g = new three();
g.print_geek();
two t = new two();
t.print_for();
g.print_geek();
}
}
Output:
Geeks
for
Geeks
4. Multiple Inheritance (Through Interfaces) : In Multiple inheritance ,one class can have more
than one superclass and inherit features from all parent classes. Please note that Java
does not support multiple inheritance with classes. In java, we can achieve multiple inheritance
only through Interfaces. In image below, Class C is derived from interface A and B.

filter_none
edit
play_arrow
brightness_4
// Java program to illustrate the
// concept of Multiple inheritance
import java.util.*;
import java.lang.*;
import java.io.*;
interface one
{
public void print_geek();
}

interface two
{
public void print_for();
}

interface three extends one,two


{
public void print_geek();
}
class child implements three
{
@Override
public void print_geek() {
System.out.println("Geeks");
}

public void print_for()


{
System.out.println("for");
}
}

// Drived class
public class Main
{
public static void main(String[] args)
{
child c = new child();
c.print_geek();
c.print_for();
c.print_geek();
}
}
Output:
Geeks
for
Geeks
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 inheritance with classes, the hybrid inheritance
is also not possible with classes. In java, we can achieve hybrid inheritance only
through Interfaces.
Important facts about inheritance in Java
 Default superclass: Except Object class, which has no superclass, every class has one and
only one direct superclass (single inheritance). In the absence of any other explicit superclass,
every class is implicitly a subclass of Object class.
 Superclass can only be one: A superclass can have any number of subclasses. But a
subclass can have only one superclass. This is because Java does not support multiple
inheritance with classes. Although with interfaces, multiple inheritance is supported by java.
 Inheriting Constructors: A subclass inherits all the members (fields, methods, and nested
classes) from its superclass. Constructors are not members, so they are not inherited by
subclasses, but the constructor of the superclass can be invoked from the subclass.
 Private member inheritance: A subclass does not inherit the private members of its parent
class. However, if the superclass has public or protected methods(like getters and setters) for
accessing its private fields, these can also be used by the subclass.
What all can be done in a Subclass?
In sub-classes we can inherit members as is, replace them, hide them, or supplement them with new
members:
 The inherited fields can be used directly, just like any other fields.
 We can declare new fields in the subclass that are not in the superclass.
 The inherited methods can be used directly as they are.
 We can write a new instance method in the subclass that has the same signature as the one in
the superclass, thus overriding it (as in example above, toString() method is overridden).
 We can write a new static method in the subclass that has the same signature as the one in the
superclass, thus hiding it.
 We can declare new methods in the subclass that are not in the superclass.
 We can write a subclass constructor that invokes the constructor of the superclass, either
implicitly or by using the keyword super.
 Java and Multiple Inheritance
 Multiple Inheritance is a feature of object oriented concept, where a class can inherit
properties of more than one parent class. The problem occurs when there exist methods with
same signature in both the super classes and subclass. On calling the method, the compiler
cannot determine which class method to be called and even on calling which class method
gets the priority.
 Why Java doesn’t support Multiple Inheritance?

Consider the below Java code. It shows error.
 filter_none
 edit
 play_arrow
 brightness_4
// First Parent class
class Parent1
{
void fun()
{
System.out.println("Parent1");
}
}

// Second Parent Class


class Parent2
{
void fun()
{
System.out.println("Parent2");
}
}

// Error : Test is inheriting from multiple


// classes
class Test extends Parent1, Parent2
{
public static void main(String args[])
{
Test t = new Test();
t.fun();
}
}
 Output :
 Compiler Error
 From the code, we see that, on calling the method fun() using Test object will cause
complications such as whether to call Parent1’s fun() or Parent2’s fun() method.
 1. The Diamond Problem:
 GrandParent
 / \
 / \
 Parent1 Parent2
 \ /
 \ /
 Test
 filter_none
 edit
 play_arrow
 brightness_4
// A Grand parent class in diamond
class GrandParent
{
void fun()
{
System.out.println("Grandparent");
}
}

// First Parent class


class Parent1 extends GrandParent
{
void fun()
{
System.out.println("Parent1");
}
}

// Second Parent Class


class Parent2 extends GrandParent
{
void fun()
{
System.out.println("Parent2");
}
}

// Error : Test is inheriting from multiple


// classes
class Test extends Parent1, Parent2
{
public static void main(String args[])
{
Test t = new Test();
t.fun();
}
}
 From the code, we see that: On calling the method fun() using Test object will cause
complications such as whether to call Parent1’s fun() or Child’s fun() method.
 Therefore, in order to avoid such complications Java does not support multiple inheritance of
classes.
 2. Simplicity – Multiple inheritance is not supported by Java using classes , handling the
complexity that causes due to multiple inheritance is very complex. It creates problem during
various operations like casting, constructor chaining etc and the above all reason is that
there are very few scenarios on which we actually need multiple inheritance, so better to omit
it for keeping the things simple and straightforward.

 How are above problems handled for Default Methods and Interfaces ?

Java 8 supports default methods where interfaces can provide default implementation of
methods. And a class can implement two or more interfaces. In case both the implemented
interfaces contain default methods with same method signature, the implementing class
should explicitly specify which default method is to be used or it should override the default
method.
 filter_none
 edit
 play_arrow
 brightness_4
// A simple Java program to demonstrate multiple
// inheritance through default methods.
interface PI1
{
// default method
default void show()
{
System.out.println("Default PI1");
}
}

interface PI2
{
// Default method
default void show()
{
System.out.println("Default PI2");
}
}

// Implementation class code


class TestClass implements PI1, PI2
{
// Overriding default show method
public void show()
{
// use super keyword to call the show
// method of PI1 interface
PI1.super.show();

// use super keyword to call the show


// method of PI2 interface
PI2.super.show();
}

public static void main(String args[])


{
TestClass d = new TestClass();
d.show();
}
}
 Output:
 Default PI1
 Default PI2
 If we remove implementation of default method from “TestClass”, we get compiler error.
See this for a sample run.
 If there is a diamond through interfaces, then there is no issue if none of the middle
interfaces provide implementation of root interface. If they provide implementation, then
implementation can be accessed as above using super keyword.
 filter_none
 edit
 play_arrow
 brightness_4
// A simple Java program to demonstrate how diamond
// problem is handled in case of default methods

interface GPI
{
// default method
default void show()
{
System.out.println("Default GPI");
}
}

interface PI1 extends GPI { }

interface PI2 extends GPI { }

// Implementation class code


class TestClass implements PI1, PI2
{
public static void main(String args[])
{
TestClass d = new TestClass();
d.show();
}
}
 Output:
 Default GPI
 This article is contributed by Vishal S. If you like GeeksforGeeks and would like to
contribute, you can also write an article using contribute.geeksforgeeks.org or mail your
article to [email protected]. See your article appearing on the GeeksforGeeks
main page and help other Geeks.
 Please write comments if you find anything incorrect, or you want to share more information
about the topic discussed above.

Encapsulation in Java
Encapsulation is defined as the wrapping up of data under a single unit. It is the mechanism that
binds together code and the data it manipulates.Other way to think about encapsulation is, it is a
protective shield that prevents the data from being accessed by the code outside this shield.
 Technically in encapsulation, the variables or data of a class is hidden from any other class and
can be accessed only through any member function of own class in which they are declared.
 As in encapsulation, the data in a class is hidden from other classes, so it is also known
as data-hiding.
 Encapsulation can be achieved by: Declaring all the variables in the class as private and writing
public methods in the class to set and get the values of variables.

filter_none
edit
play_arrow
brightness_4
// Java program to demonstrate encapsulation
public class Encapsulate
{
// private variables declared
// these can only be accessed by
// public methods of class
private String geekName;
private int geekRoll;
private int geekAge;

// get method for age to access


// private variable geekAge
public int getAge()
{
return geekAge;
}

// get method for name to access


// private variable geekName
public String getName()
{
return geekName;
}

// get method for roll to access


// private variable geekRoll
public int getRoll()
{
return geekRoll;
}

// set method for age to access


// private variable geekage
public void setAge( int newAge)
{
geekAge = newAge;
}

// set method for name to access


// private variable geekName
public void setName(String newName)
{
geekName = newName;
}

// set method for roll to access


// private variable geekRoll
public void setRoll( int newRoll)
{
geekRoll = newRoll;
}
}
In the above program the class EncapsulateDemo is encapsulated as the variables are declared as
private. The get methods like getAge() , getName() , getRoll() are set as public, these methods are
used to access these variables. The setter methods like setName(), setAge(), setRoll() are also
declared as public and are used to set the values of the variables.
The program to access variables of the class EncapsulateDemo is shown below:

filter_none
edit
play_arrow
brightness_4
public class TestEncapsulation
{
public static void main (String[] args)
{
Encapsulate obj = new Encapsulate();

// setting values of the variables


obj.setName("Harsh");
obj.setAge(19);
obj.setRoll(51);

// Displaying values of the variables


System.out.println("Geek's name: " + obj.getName());
System.out.println("Geek's age: " + obj.getAge());
System.out.println("Geek's roll: " + obj.getRoll());

// Direct access of geekRoll is not possible


// due to encapsulation
// System.out.println("Geek's roll: " +
obj.geekName);
}
}
Output:
Geek's name: Harsh
Geek's age: 19
Geek's roll: 51
Advantages of Encapsulation:
 Data Hiding: The user will have no idea about the inner implementation of the class. It will not
be visible to the user that how the class is storing values in the variables. He only knows that
we are passing the values to a setter method and variables are getting initialized with that
value.
 Increased Flexibility: We can make the variables of the class as read-only or write-only
depending on our requirement. If we wish to make the variables as read-only then we have to
omit the setter methods like setName(), setAge() etc. from the above program or if we wish to
make the variables as write-only then we have to omit the get methods like getName(),
getAge() etc. from the above program
 Reusability: Encapsulation also improves the re-usability and easy to change with new
requirements.
 Testing code is easy: Encapsulated code is easy to test for unit testing.

Abstraction in Java
Data Abstraction is the property by virtue of which only the essential details are displayed to the
user.The trivial or the non-essentials units are not displayed to the user. Ex: A car is viewed as a car
rather than its individual components.
Data Abstraction may also be defined as the process of identifying only the required characteristics
of an object ignoring the irrelevant details.The properties and behaviors of an object differentiate it
from other objects of similar type and also help in classifying/grouping the objects.
Consider a real-life example of a man driving a car. The man only knows that pressing the
accelerators will increase the speed of car or applying brakes will stop the car but he does not know
about how on pressing the accelerator the speed is actually increasing, he does not know about the
inner mechanism of the car or the implementation of accelerator, brakes etc in the car. This is what
abstraction is.
In java, abstraction is achieved by interfaces and abstract classes. We can achieve 100%
abstraction using interfaces.
Abstract classes and Abstract methods :
1. An abstract class is a class that is declared with abstract keyword.
2. An abstract method is a method that is declared without an implementation.
3. An abstract class may or may not have all abstract methods. Some of them can be concrete
methods
4. A method defined abstract must always be redefined in the subclass,thus
making overriding compulsory OR either make subclass itself abstract.
5. Any class that contains one or more abstract methods must also be declared with abstract
keyword.
6. There can be no object of an abstract class.That is, an abstract class can not be directly
instantiated with the new operator.
7. An abstract class can have parametrized constructors and default constructor is always present
in an abstract class.
When to use abstract classes and abstract methods with an example
There are situations in which we will want to define a superclass that declares the structure of a
given abstraction without providing a complete implementation of every method. That is, sometimes
we will want to create a superclass that only defines a generalization form that will be shared by all
of its subclasses, leaving it to each subclass to fill in the details.
Consider a classic “shape” example, perhaps used in a computer-aided design system or game
simulation. The base type is “shape” and each shape has a color, size and so on. From this, specific
types of shapes are derived(inherited)-circle, square, triangle and so on – each of which may have
additional characteristics and behaviors. For example, certain shapes can be flipped. Some
behaviors may be different, such as when you want to calculate the area of a shape. The type
hierarchy embodies both the similarities and differences between the shapes.

filter_none
edit
play_arrow
brightness_4
// Java program to illustrate the
// concept of Abstraction
abstract class Shape
{
String color;

// these are abstract methods


abstract double area();
public abstract String toString();

// abstract class can have constructor


public Shape(String color) {
System.out.println("Shape constructor called");
this.color = color;
}

// this is a concrete method


public String getColor() {
return color;
}
}
class Circle extends Shape
{
double radius;

public Circle(String color,double radius) {

// calling Shape constructor


super(color);
System.out.println("Circle constructor called");
this.radius = radius;
}

@Override
double area() {
return Math.PI * Math.pow(radius, 2);
}

@Override
public String toString() {
return "Circle color is " + super.color +
"and area is : " + area();
}

}
class Rectangle extends Shape{

double length;
double width;

public Rectangle(String color,double length,double width) {


// calling Shape constructor
super(color);
System.out.println("Rectangle constructor called");
this.length = length;
this.width = width;
}
@Override
double area() {
return length*width;
}

@Override
public String toString() {
return "Rectangle color is " + super.color +
"and area is : " + area();
}

}
public class Test
{
public static void main(String[] args)
{
Shape s1 = new Circle("Red", 2.2);
Shape s2 = new Rectangle("Yellow", 2, 4);

System.out.println(s1.toString());
System.out.println(s2.toString());
}
}
Output:
Shape constructor called
Circle constructor called
Shape constructor called
Rectangle constructor called
Circle color is Redand area is : 15.205308443374602
Rectangle color is Yellowand area is : 8.0
Encapsulation vs Data Abstraction
1. Encapsulation is data hiding(information hiding) while Abstraction is detail
hiding(implementation hiding).
2. While encapsulation groups together data and methods that act upon the data, data abstraction
deals with exposing the interface to the user and hiding the details of implementation.
Advantages of Abstraction
1. It reduces the complexity of viewing the things.
2. Avoids code duplication and increases reusability.
3. Helps to increase security of an application or program as only important details are provided to
the user.
Related articles :
 Interfaces in java
 Abstract classes in java
 Difference between abstract class and interface
 abstract keyword in java
Classes and Objects in Java
Classes and Objects are basic concepts of Object Oriented Programming which revolve around the
real life entities.
Class
A class is a user defined blueprint or prototype from which objects are created. It represents the set
of properties or methods that are common to all objects of one type. In general, class declarations
can include these components, in order:
1. Modifiers : A class can be public or has default access (Refer this for details).
2. Class name: The name should begin with a initial letter (capitalized by convention).
3. Superclass(if any): The name of the class’s parent (superclass), if any, preceded by the
keyword extends. A class can only extend (subclass) one parent.
4. Interfaces(if any): A comma-separated list of interfaces implemented by the class, if any,
preceded by the keyword implements. A class can implement more than one interface.
5. Body: The class body surrounded by braces, { }.
Constructors are used for initializing new objects. Fields are variables that provides the state of the
class and its objects, and methods are used to implement the behavior of the class and its objects.
There are various types of classes that are used in real time applications such as nested
classes, anonymous classes, lambda expressions.

Object
It is a basic unit of Object Oriented Programming and represents the real life entities. A typical Java
program creates many objects, which as you know, interact by invoking methods. An object consists
of :
1. State : It is represented by attributes of an object. It also reflects the properties of an object.
2. Behavior : It is represented by methods of an object. It also reflects the response of an object
with other objects.
3. Identity : It gives a unique name to an object and enables one object to interact with other
objects.
Example of an object : dog

Objects correspond to things found in the real world. For example, a graphics program may have
objects such as “circle”, “square”, “menu”. An online shopping system might have objects such as
“shopping cart”, “customer”, and “product”.
Declaring Objects (Also called instantiating a class)
When an object of a class is created, the class is said to be instantiated. All the instances share the
attributes and the behavior of the class. But the values of those attributes, i.e. the state are unique
for each object. A single class may have any number of instances.
Example :

As we declare variables like (type name;). This notifies the compiler that we will use name to refer to
data whose type is type. With a primitive variable, this declaration also reserves the proper amount
of memory for the variable. So for reference variable, type must be strictly a concrete class name. In
general,we can’t create objects of an abstract class or an interface.
Dog tuffy;
If we declare reference variable(tuffy) like this, its value will be undetermined(null) until an object is
actually created and assigned to it. Simply declaring a reference variable does not create an object.

Initializing an object
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 class constructor.

filter_none
edit
play_arrow
brightness_4
// Class Declaration

public class Dog


{
// Instance Variables
String name;
String breed;
int age;
String color;

// Constructor Declaration of Class


public Dog(String name, String breed,
int age, String color)
{
this.name = name;
this.breed = breed;
this.age = age;
this.color = color;
}

// method 1
public String getName()
{
return name;
}

// method 2
public String getBreed()
{
return breed;
}

// method 3
public int getAge()
{
return age;
}

// method 4
public String getColor()
{
return color;
}

@Override
public String toString()
{
return("Hi my name is "+ this.getName()+
".\nMy breed,age and color are " +
this.getBreed()+"," + this.getAge()+
","+ this.getColor());
}

public static void main(String[] args)


{
Dog tuffy = new Dog("tuffy","papillon", 5, "white");
System.out.println(tuffy.toString());
}
}
Output:
Hi my name is tuffy.
My breed,age and color are papillon,5,white
 This class contains a single constructor. We can recognize a constructor because its
declaration uses the same name as the class and it has no return type. The Java compiler
differentiates the constructors based on the number and the type of the arguments. The
constructor in the Dog class takes four arguments. The following statement provides
“tuffy”,”papillon”,5,”white” as values for those arguments:
 Dog tuffy = new Dog("tuffy","papillon",5, "white");
The result of executing this statement can be illustrated as :

Note : All classes have at least one constructor. If a class does not explicitly declare any, the Java
compiler automatically provides a no-argument constructor, also called the default constructor. This
default constructor calls the class parent’s no-argument constructor (as it contain only one statement
i.e super();), or the Object class constructor if the class has no other parent (as Object class is
parent of all classes either directly or indirectly).

Ways to create object of a class


There are four ways to create objects in java.Strictly speaking there is only one way(by
using new keyword),and the rest internally use new keyword.
 Using new keyword : It is the most common and general way to create object in
java. Example:

 // creating object of class Test
 Test t = new Test();
 Using Class.forName(String className) method : There is a pre-defined class in java.lang
package with name Class. The forName(String className) method returns the Class object
associated with the class with the given string name.We have to give the fully qualified name
for a class. On calling new Instance() method on this Class object returns new instance of the
class with the given string name.
 // creating object of public class Test
 // consider class Test present in com.p1 package
Test obj = (Test)Class.forName("com.p1.Test").newInstance();
 Using clone() method: clone() method is present in Object class. It creates and returns a copy
of the object.

 // creating object of class Test
 Test t1 = new Test();

 // creating clone of above object
 Test t2 = (Test)t1.clone();

 Deserialization : De-serialization is technique of reading an object from the saved state in a


file. Refer Serialization/De-Serialization in java

 FileInputStream file = new FileInputStream(filename);
 ObjectInputStream in = new ObjectInputStream(file);
 Object obj = in.readObject();
Creating multiple objects by one type only (A good practice)
 In real-time, we need different objects of a class in different methods. Creating a number of
references for storing them is not a good practice and therefore we declare a static reference
variable and use it whenever required. In this case,wastage of memory is less. The objects that
are not referenced anymore will be destroyed by Garbage Collector of java. Example:

 Test test = new Test();
 test = new Test();
 In inheritance system, we use parent class reference variable to store a sub-class object. In this
case, we can switch into different subclass objects using same referenced variable. Example:
 class Animal {}

 class Dog extends Animal {}
 class Cat extends Animal {}

 public class Test
 {
 // using Dog object
 Animal obj = new Dog();

 // using Cat object
 obj = new Cat();
 }
Anonymous objects
Anonymous objects are the objects that are instantiated but are not stored in a reference variable.
 They are used for immediate method calling.
 They will be destroyed after method calling.
 They are widely used in different libraries. For example, in AWT libraries, they are used to
perform some action on capturing an event(eg a key press).
 In example below, when a key is button(referred by the btn) is pressed, we are simply creating
anonymous object of EventHandler class for just calling handle method.
 btn.setOnAction(new EventHandler()
 {
 public void handle(ActionEvent event)
 {
 System.out.println("Hello World!");
 }
});

Methods in Java
A method is a collection of statements that perform some specific task and return the result to the
caller. A method can perform some specific task without returning anything. Methods allow us
to reuse the code without retyping the code. In Java, every method must be part of some class
which is different from languages like C, C++, and Python.
Methods are time savers and help us to reuse the code without retyping the code.
Method Declaration
In general, method declarations has six components :
 Modifier-: Defines access type of the method i.e. from where it can be accessed in your
application. In Java, there 4 type of the access specifiers.
 public: accessible in all class in your application.
 protected: accessible within the class in which it is defined and in its subclass(es)
 private: accessible only within the class in which it is defined.
 default (declared/defined without using any modifier) : accessible within same class and
package within which its class is defined.
 The return type : The data type of the value returned by the method or void if does not return a
value.
 Method Name : the rules for field names apply to method names as well, but the convention is
a little different.
 Parameter list : Comma separated list of the input parameters are defined, preceded with their
data type, within the enclosed parenthesis. If there are no parameters, you must use empty
parentheses ().
 Exception list : The exceptions you expect by the method can throw, you can specify these
exception(s).
 Method body : it is enclosed between braces. The code you need to be executed to perform
your intended operations.
Method signature: It consists of the method name and a parameter list (number of parameters, type
of the parameters and order of the parameters). The return type and exceptions are not considered
as part of it.
Method Signature of above function:
max(int x, int y)
How to name a Method?: A method name is typically a single word that should be a verbin
lowercase or multi-word, that begins with a verb in lowercase followed by adjective, noun….. After
the first word, first letter of each word should be capitalized. For example, findSum,
computeMax, setX and getX
Generally, A method has a unique name within the class in which it is defined but sometime a
method might have the same name as other method names within the same class as method
overloading is allowed in Java.
Calling a method
The method needs to be called for using its functionality. There can be three situations when a
method is called:
A method returns to the code that invoked it when:
 It completes all the statements in the method
 It reaches a return statement
 Throws an exception
filter_none
edit
play_arrow
brightness_4
// Program to illustrate methodsin java
import java.io.*;

class Addition {

int sum = 0;

public int addTwoInt(int a, int b){


// adding two integer value.
sum = a + b;

//returning summation of two values.


return sum;
}

class GFG {
public static void main (String[] args) {

// creating an instance of Addition class


Addition add = new Addition();

// calling addTwoInt() method to add two integer using instance


created
// in above step.
int s = add.addTwoInt(1,2);
System.out.println("Sum of two integer values :"+ s);

}
}
Output :
Sum of two integer values :3
See the below example to understand method call in detail :

filter_none
edit
play_arrow
brightness_4
// Java program to illustrate different ways of calling a method
import java.io.*;

class Test
{
public static int i = 0;
// constructor of class which counts
//the number of the objects of the class.
Test()
{
i++;

}
// static method is used to access static members of the class
// and for getting total no of objects
// of the same class created so far
public static int get()
{
// statements to be executed....
return i;
}

// Instance method calling object directly


// that is created inside another class 'GFG'.
// Can also be called by object directly created in the same
class
// and from another method defined in the same class
// and return integer value as return type is int.
public int m1()
{
System.out.println("Inside the method m1 by object of GFG
class");

// calling m2() method within the same class.


this.m2();

// statements to be executed if any


return 1;
}

// It doesn't return anything as


// return type is 'void'.
public void m2()
{

System.out.println("In method m2 came from method m1");


}
}

class GFG
{
public static void main(String[] args)
{
// Creating an instance of the class
Test obj = new Test();

// Calling the m1() method by the object created in above


step.
int i = obj.m1();
System.out.println("Control returned after method m1 :" + i);

// Call m2() method


// obj.m2();
int no_of_objects = Test.get();

System.out.print("No of instances created till now : ");


System.out.println(no_of_objects);

}
}
Output :
Inside the method m1 by object of GFG class
In method m2 came from method m1
Control returned after method m1 :1
No of instances created till now : 1
Control flow of above program:

Memory allocation for methods calls


Methods calls are implemented through stack. Whenever a method is called a stack frame is created
within the stack area and after that the arguments passed to and the local variables and value to be
returned by this called method are stored in this stack frame and when execution of the called
method is finished, the allocated stack frame would be deleted. There is a stack pointer register that
tracks the top of the stack which is adjusted accordingly.
Let us learn about the different characteristics of an Object Oriented Programming language:
1. Polymorphism: Polymorphism refers to the ability of OOPs programming languages to
differentiate between entities with the same name efficiently. This is done by Java with the help
of the signature and declaration of these entities.
For example:
filter_none
edit
play_arrow
brightness_4
// Java program to demonstrate Polymorphism

// This class will contain


// 3 methods with same name,
// yet the program will
// compile & run successfully
public class Sum {

// Overloaded sum().
// This sum takes two int parameters
public int sum(int x, int y)
{
return (x + y);
}

// Overloaded sum().
// This sum takes three int parameters
public int sum(int x, int y, int z)
{
return (x + y + z);
}

// Overloaded sum().
// This sum takes two double parameters
public double sum(double x, double y)
{
return (x + y);
}

// Driver code
public static void main(String args[])
{
Sum s = new Sum();
System.out.println(s.sum(10, 20));
System.out.println(s.sum(10, 20, 30));
System.out.println(s.sum(10.5, 20.5));
}
}
Output:
30
60
31.0
Polymorphism in Java are mainly of 2 types:
 Overloading in Java
 Overriding in Java
2. Inheritence: Inheritance is an important pillar of OOP(Object Oriented Programming). It is the
mechanism in java by which one class is allow to inherit the features(fields and methods) of
another class.
Important terminology:

 Super Class: The class whose features are inherited is known as superclass(or a base
class or a parent class).
 Sub Class: The class that inherits the other class is known as 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.
 Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create
a new class and there is already a class that includes some of the code that we want, we
can derive our new class from the existing class. By doing this, we are reusing the fields
and methods of the existing class.
The keyword used for inheritance is extends.
Syntax:
class derived-class extends base-class
{
//methods and fields
}
3. Encapsulation: Encapsulation is defined as the wrapping up of data under a single unit. It is
the mechanism that binds together code and the data it manipulates.Other way to think about
encapsulation is, it is a protective shield that prevents the data from being accessed by the
code outside this shield.
 Technically in encapsulation, the variables or data of a class is hidden from any other
class and can be accessed only through any member function of own class in which they
are declared.
 As in encapsulation, the data in a class is hidden from other classes, so it is also known
as data-hiding.
 Encapsulation can be achieved by: Declaring all the variables in the class as private and
writing public methods in the class to set and get the values of variables.

4. Abstraction: Data Abstraction is the property by virtue of which only the essential details are
displayed to the user.The trivial or the non-essentials units are not displayed to the user. Ex: A
car is viewed as a car rather than its individual components.
Data Abstraction may also be defined as the process of identifying only the required
characteristics of an object ignoring the irrelevant details. The properties and behaviours of an
object differentiate it from other objects of similar type and also help in classifying/grouping the
objects.
Consider a real-life example of a man driving a car. The man only knows that pressing the
accelerators will increase the speed of car or applying brakes will stop the car but he does not
know about how on pressing the accelerator the speed is actually increasing, he does not know
about the inner mechanism of the car or the implementation of accelerator, brakes etc in the
car. This is what abstraction is.
In java, abstraction is achieved by interfaces and abstract classes. We can achieve 100%
abstraction using interfaces.
5. Class: A class is a user defined blueprint or prototype from which objects are created. It
represents the set of properties or methods that are common to all objects of one type. In
general, class declarations can include these components, in order:
1. Modifiers : A class can be public or has default access (Refer this for details).
2. Class name: The name should begin with a initial letter (capitalized by convention).
3. Superclass(if any): The name of the class’s parent (superclass), if any, preceded by the
keyword extends. A class can only extend (subclass) one parent.
4. Interfaces(if any): A comma-separated list of interfaces implemented by the class, if any,
preceded by the keyword implements. A class can implement more than one interface.
5. Body: The class body surrounded by braces, { }.
6. Object: It is a basic unit of Object Oriented Programming and represents the real life entities.
A typical Java program creates many objects, which as you know, interact by invoking
methods. An object consists of :
0. State : It is represented by attributes of an object. It also reflects the properties of an
object.
1. Behavior : It is represented by methods of an object. It also reflects the response of an
object with other objects.
2. Identity : It gives a unique name to an object and enables one object to interact with other
objects.
Example of an object : dog

7. Method: A method is a collection of statements that perform some specific task and return
result to the caller. A method can perform some specific task without returning anything.
Methods allow us to reuse the code without retyping the code. In Java, every method must be
part of some class which is different from languages like C, C++ and Python.
Methods are time savers and help us to reuse the code without retyping the code.
Method Declaration
In general, method declarations has six components :
 Modifier-: Defines access type of the method i.e. from where it can be accessed in your
application. In Java, there 4 type of the access specifiers.
 public: accessible in all class in your application.
 protected: accessible within the class in which it is defined and in its subclass(es)
 private: accessible only within the class in which it is defined.
 default (declared/defined without using any modifier) : accessible within same class
and package within which its class is defined.
 The return type : The data type of the value returned by the the method or void if does
not return a value.
 Method Name : the rules for field names apply to method names as well, but the
convention is a little different.
 Parameter list : Comma separated list of the input parameters are defined, preceded with
their data type, within the enclosed parenthesis. If there are no parameters, you must use
empty parentheses ().
 Exception list : The exceptions you expect by the method can throw, you can specify
these exception(s).
 Method body : it is enclosed between braces. The code you need to be executed to
perform your intended operations.

8. Message Passing: Objects communicate with one another by sending and receiving
information to each other. A message for an object is a request for execution of a procedure
and therefore will invoke a function in the receiving object that generates the desired results.
Message passing involves specifying the name of the object, the name of the function and the
information to be sent.

No. Method Overloading Method Overriding

1) Method overloading is used to increase the readability of the Method overriding is used to provide the
program. specific implementation of the method that i
already provided by its super class.

2) Method overloading is performed within class. Method overriding occurs in two classes that
have IS-A (inheritance) relationship.

3) In case of method overloading, parameter must be different. In case of method overriding, parameter mu
be same.

4) Method overloading is the example of compile time Method overriding is the example of run tim
polymorphism. polymorphism.

5) In java, method overloading can't be performed by changing Return type must be same or covariant in
return type of the method only. Return type can be same or method overriding.
different in method overloading. But you must have to change the
parameter.

You might also like