0% found this document useful (0 votes)
139 views39 pages

Object Oriented Concepts and Examples

The document discusses object oriented programming concepts in Java. It defines key concepts like class, object, inheritance, encapsulation, abstraction and polymorphism. It provides examples of creating classes like Student and Rectangle, and creating objects of these classes. It also demonstrates initializing objects using reference variables, methods and constructors. The examples show how to define fields and methods in a class, and access them using objects.

Uploaded by

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

Object Oriented Concepts and Examples

The document discusses object oriented programming concepts in Java. It defines key concepts like class, object, inheritance, encapsulation, abstraction and polymorphism. It provides examples of creating classes like Student and Rectangle, and creating objects of these classes. It also demonstrates initializing objects using reference variables, methods and constructors. The examples show how to define fields and methods in a class, and access them using objects.

Uploaded by

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

OBJECT ORIENTED PROGRAMMING CONCEPTS IN JAVA

Object Oriented programming is a programming style which is associated with the


concepts like class, object, Inheritance, Encapsulation, Abstraction, Polymorphism.
Most popular programming languages like Java, C++, C#, Ruby, etc. follow an
object oriented programming paradigm.

Object means a real-world entity such as a pen, chair, table, computer, watch,
etc. Object-Oriented Programming is a methodology or paradigm to design a
program using classes and objects. It simplifies the software development and
maintenance by providing some concepts:

o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation

OBJECTS AND CLASSES

What is an object in Java

An entity that has state and behavior is known as an object e.g. chair, bike, marker,
pen, table, car etc. It can be physical or logical (tangible and intangible). The example of
an intangible object is the banking system.

An object has three characteristics:


o State: represents the data (value) of an object.
o Behavior: represents the behavior (functionality) of an object such as deposit,
withdraw, etc.
o Identity: An object identity is typically implemented via a unique ID. The value
of the ID is not visible to the external user. However, it is used internally by the
JVM to identify each object uniquely

For Example, Pen is an object. Its name is BIC; color is white, known as its state. It is
used to write, so writing is its behavior.

An object is an instance of a class. A class is a template or blueprint from which


objects are created. So, an object is the instance(result) of a class.

Object Definitions:

o An object is a real-world entity.


o An object is a runtime entity.
o The object is an entity which has state and behavior.
o The object is an instance of a class.
What is a class in Java
A class is a group of objects which have common properties. It is a template or blueprint
from which objects are created. It is a logical entity. It can't be physical.

A class in Java can contain:

o Fields
o Methods
o Constructors
o Blocks
o Nested class and interface

Syntax to declare a class:


1. class <class_name>{
2. field;
3. method;
4. }

Instance variable in Java


A variable which is created inside the class but outside the method is known as an
instance variable. Instance variable doesn't get memory at compile time. It gets memory
at runtime when an object or instance is created. That is why it is known as an instance
variable.

Method in Java
In Java, a method is like a function which is used to expose the behavior of an object.

Advantage of Method
o Code Reusability
o Code Optimization

new keyword in Java


The new keyword is used to allocate memory at runtime. All objects get memory in Heap
memory area.

Object and Class Example: main within the class


In this example, we have created a Student class which has two data members id and
name. We are creating the object of the Student class by new keyword and printing the
object's value.

Here, we are creating a main() method inside the class.

File: Student.java//Java Program to illustrate how to define a class and fields

//Defining a Student class.


class Student{
//defining fields
int id;//field or data member or instance variable
String name;
//creating main method inside the Student class
public static void main(String args[]){
//Creating an object or instance
Student s1=new Student();//creating an object of Student
//Printing values of the object
System.out.println(s1.id);//accessing member through reference variable
System.out.println(s1.name);
}
}

Object and Class Example: main outside the class


In real time development, we create classes and use it from another class. It is a better
approach than previous one. Let's see a simple example, where we are having main()
method in another class.

We can have multiple classes in different java files or single java file. If you define
multiple classes in a single java source file, it is a good idea to save the file name with
the class name which has main() method.

File: TestStudent1.java

//Java Program to demonstrate having the main method in

//another class
//Creating Student class.
class Student{
int id;
String name;
}
//Creating another class TestStudent1 which contains the main method
class TestStudent1{
public static void main(String args[]){
Student s1=new Student();
System.out.println(s1.id);
System.out.println(s1.name);
}
}

3 Ways to initialize object


There are 3 ways to initialize object in java.

1. By reference variable
2. By method
3. By constructor
We can also create multiple objects and store information in it through reference
variable.

File: TestStudent3.java
class Student{

int id;
String name;
}
class TestStudent3{
public static void main(String args[]){
//Creating objects
Student s1=new Student();
Student s2=new Student();
//Initializing objects
s1.id=101;
s1.name="Sonoo";
s2.id=102;
s2.name="Amit";
//Printing data
System.out.println(s1.id+" "+s1.name);
System.out.println(s2.id+" "+s2.name);
}
}

Object and Class Example: Initialization through


method
In this example, we are creating the two objects of Student class and initializing the
value to these objects by invoking the insertRecord method. Here, we are displaying the
state (data) of the objects by invoking the displayInformation() method.

File: TestStudent4.java

class Student{
int rollno;
String name;
void insertRecord(int r, String n){
rollno=r;
name=n;
}
void displayInformation(){System.out.println(rollno+" "+name);}
}
class TestStudent4{
public static void main(String args[]){
Student s1=new Student();
Student s2=new Student();
s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan");
s1.displayInformation();
s2.displayInformation();
}
}

Object and Class Example: Initialization through a


constructor
We will learn about constructors in java later.

Object and Class Example: Employee


Let's see an example where we are maintaining records of employees.

File: TestEmployee.java

class Employee{
int id;
String name;
float salary;
void insert(int i, String n, float s) {
id=i;
name=n;
salary=s;
}
void display(){System.out.println(id+" "+name+" "+salary);}
}
public class TestEmployee {
public static void main(String[] args) {
Employee e1=new Employee();
Employee e2=new Employee();
Employee e3=new Employee();
e1.insert(101,"ajeet",45000);
e2.insert(102,"irfan",25000);
e3.insert(103,"nakul",55000);
e1.display();
e2.display();
e3.display(); } }
1) Object and Class Example: Initialization through
reference
Initializing an object means storing data into the object. Let's see a simple example
where we are going to initialize the object through a reference variable.

File: TestStudent2.java

class Student{
int id;
String name;
}
class TestStudent2{
public static void main(String args[]){
Student s1=new Student();
s1.id=101;
s1.name="Sonoo";
System.out.println(s1.id+" "+s1.name);//printing members with a white space
}
}

Object and Class Example: Rectangle


There is given another example that maintains the records of Rectangle class.

File: TestRectangle1.java

class Rectangle{
int length;
int width;
void insert(int l, int w){
length=l;
width=w;
}
void calculateArea(){System.out.println(length*width);}
}
class TestRectangle1{
public static void main(String args[]){
Rectangle r1=new Rectangle();
Rectangle r2=new Rectangle();
r1.insert(11,5);
r2.insert(3,15);
r1.calculateArea();
r2.calculateArea();
}
}

What are the different ways to create an object in


Java?
There are many ways to create an object in java. They are:

o By new keyword
o By newInstance() method
o By clone() method
o By deserialization
o By factory method etc.

Creating multiple objects by one type only


We can create multiple objects by one type only as we do in case of primitives.

Initialization of primitive variables:

int a=10, b=20;

Initialization of refernce variables:

Rectangle r1=new Rectangle(), r2=new Rectangle();//creating two objects

Let's see the example:

//Java Program to illustrate the use of Rectangle class which


//has length and width data members
class Rectangle{
int length;
int width;
void insert(int l,int w){
length=l;
width=w;
}
void calculateArea(){System.out.println(length*width);}
}
class TestRectangle2{
public static void main(String args[]){
Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two objects
r1.insert(11,5);
r2.insert(3,15);
r1.calculateArea();
r2.calculateArea();
}
}

Real World Example: Account


File: TestAccount.java

//Java Program to demonstrate the working of a banking-system


//where we deposit and withdraw amount from our account.
//Creating an Account class which has deposit() and withdraw() methods
class Account{
int acc_no;
String name;
float amount;
//Method to initialize object
void insert(int a,String n,float amt){
acc_no=a;
name=n;
amount=amt;
}
//deposit method
void deposit(float amt){
amount=amount+amt;
System.out.println(amt+" deposited");
}
//withdraw method
void withdraw(float amt){
if(amount<amt){
System.out.println("Insufficient Balance");
}else{
amount=amount-amt;
System.out.println(amt+" withdrawn");
}
}
//method to check the balance of the account
void checkBalance(){System.out.println("Balance is: "+amount);}
//method to display the values of an object
void display(){System.out.println(acc_no+" "+name+" "+amount);}
}
//Creating a test class to deposit and withdraw amount
class TestAccount{
public static void main(String[] args){
Account a1=new Account();
a1.insert(832345,"Ankit",1000);
a1.display();
a1.checkBalance();
a1.deposit(40000);
a1.checkBalance();
a1.withdraw(15000);
a1.checkBalance();
}}

Constructors in Java
In Java, a constructor is a block of codes similar to the method. It is called when an
instance of the object is created, and memory is allocated for the object.

It is a special type of method which is used to initialize the object.

When is a constructor called


Every time an object is created using new() keyword, at least one constructor is called.
It calls a default constructor.

Note: It is called constructor because it constructs the values at the time of object
creation. It is not necessary to write a constructor for a class. It is because java compiler
creates a default constructor if your class doesn't have any.

Rules for creating Java constructor


There are two rules defined for the constructor.

1. Constructor name must be the same as its class name


2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and synchronized

Note: We can use access modifiers while declaring a constructor. It controls the object
creation. In other words, we can have private, protected, public or default constructor in
Java.

Types of Java constructors


There are two types of constructors in Java:

1. Default constructor (no-arg constructor)


2. Parameterized constructor

Java Default Constructor


A constructor is called "Default Constructor" when it doesn't have any parameter.

Syntax of default constructor:


<class_name>(){}

Example of default constructor

In this example, we are creating the no-arg constructor in the Bike class. It will be
invoked at the time of object creation.

//Java Program to create and call a default constructor


class Bike1{
//creating a default constructor
Bike1(){System.out.println("Bike is created");}
//main method
public static void main(String args[]){
//calling a default constructor
Bike1 b=new Bike1();
}
}
Rule: If there is no constructor in a class, compiler automatically creates a default
constructor.

Q) What is the purpose of a default constructor?

The default constructor is used to provide the default values to the object like 0, null,
etc., depending on the type.

Example of default constructor that displays the


default values
//Let us see another example of default constructor
//which displays the default values
class Student3{
int id;
String name;
//method to display the value of id and name
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


//creating objects
Student3 s1=new Student3();
Student3 s2=new Student3();
//displaying values of the object
s1.display();
s2.display();
}
}

Explanation:In the above class,you are not creating any constructor so compiler
provides you a default constructor. Here 0 and null values are provided by default
constructor.
Java Parameterized Constructor
A constructor which has a specific number of parameters is called a parameterized
constructor.

Why use the parameterized constructor?

The parameterized constructor is used to provide different values to the distinct objects.
However, you can provide the same values also.

Example of parameterized constructor


In this example, we have created the constructor of Student class that have two
parameters. We can have any number of parameters in the constructor.

//Java Program to demonstrate the use of parameterized constructor


class Student4{
int id;
String name;
//creating a parameterized constructor
Student4(int i,String n){
id = i;
name = n;
}
//method to display the values
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


//creating objects and passing values
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
//calling method to display the values of object
s1.display();
s2.display();
}
}

Constructor Overloading in Java


In Java, a constructor is just like a method but without return type. It can also be
overloaded like Java methods.

Constructor overloading in Java is a technique of having more than one constructor with
different parameter lists. They are arranged in a way that each constructor performs a
different task. They are differentiated by the compiler by the number of parameters in
the list and their types.

Example of Constructor Overloading


1. //Java program to overload constructors in java
2. class Student5{
3. int id;
4. String name;
5. int age;
6. //creating two arg constructor
7. Student5(int i,String n){
8. id = i;
9. name = n;
10. }
11. //creating three arg constructor
12. Student5(int i,String n,int a){
13. id = i;
14. name = n;
15. age=a;
16. }
17. void display(){System.out.println(id+" "+name+" "+age);}
18.
19. public static void main(String args[]){
20. Student5 s1 = new Student5(111,"Karan");
21. Student5 s2 = new Student5(222,"Aryan",25);
22. s1.display();
23. s2.display();
24. }
25. }

Output:

111 Karan 0
222 Aryan 25
this keyword in java
There can be a lot of usage of java this keyword. In java, this is a reference
variable that refers to the current object.

Usage of java this keyword


Here is given the 6 usage of java this keyword.

1. this can be used to refer current class instance variable.


2. this can be used to invoke current class method (implicitly)
3. this() can be used to invoke current class constructor.
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this can be used to return the current class instance from the method.

Suggestion: If you are beginner to java, lookup only three usage of this keyword.

`
this: to refer current class instance variable
The this keyword can be used to refer current class instance variable. If there is
ambiguity between the instance variables and parameters, this keyword resolves the
problem of ambiguity.

Understanding the problem without this keyword


Let's understand the problem if we don't use this keyword by the example given
below:

class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
rollno=rollno;
name=name;
fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis1{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}

Output:

0 null 0.0
0 null 0.0

In the above example, parameters (formal arguments) and instance variables are same.
So, we are using this keyword to distinguish local variable and instance variable.

Solution of the above problem by this keyword


1. class Student{
2. int rollno;
3. String name;
4. float fee;
5. Student(int rollno,String name,float fee){
6. this.rollno=rollno;
7. this.name=name;
8. this.fee=fee;
9. }
10. void display(){System.out.println(rollno+" "+name+" "+fee);}
11. }
12.
13. class TestThis2{
14. public static void main(String args[]){
15. Student s1=new Student(111,"ankit",5000f);
16. Student s2=new Student(112,"sumit",6000f);
17. s1.display();
18. s2.display();
19. }}

Output:

111 ankit 5000


112 sumit 6000
An object-based application in Java is based on declaring classes, creating objects
from them and interacting between these objects.

Object Oriented Programming: Inheritance

In OOP, computer programs are designed in such a way where everything is an object
that interact with one another. Inheritance is one such concept where the properties
of one class can be inherited by the other. It helps to reuse the code and establish a
relationship between different classes.

1. Single Inheritance:
In single inheritance, one class inherits the properties of another. It enables a derived
class to inherit the properties and behavior from a single parent class. This will in turn
enable code reusability as well as add new features to the existing code.

Here, Class A is your parent class and Class B is your child class which inherits the
properties and behavior of the parent class.

Let’s see the syntax for single inheritance:


1
Class A
2 {
3 ---

4 }

5 Class B extends A {

---
6
}
7

2. Multilevel Inheritance:

When a class is derived from a class which is also derived from


another class, i.e. a class having more than one parent class but at different levels,
such type of inheritance is called Multilevel Inheritance.
If we talk about the flowchart, class B inherits the properties and behavior of class A
and class C inherits the properties of class B. Here A is the parent class for B and class
B is the parent class for C. So in this case class C implicitly inherits the properties and
methods of class A along with Class B. That’s what is multilevel inheritance.

Let’s see the syntax for multilevel inheritance in Java:


1
Class A{
2
---
3 }
4 Class B extends A{

5 ---

6 }

Class C extends B{
7
---
8
}
9

3. Hierarchical Inheritance:

When a class has more than one child classes


(sub classes) or in other words, more than one child classes have the same parent
class, then such kind of inheritance is known as hierarchical.

If we talk about the flowchart, Class B and C are the child classes which are inheriting
from the parent class i.e Class A.

Let’s see the syntax for hierarchical inheritance in Java:

Class A{

---

Class B extends A{
---

Class C extends A{

---

4. Hybrid Inheritance:

Hybrid inheritance is a combination of multiple inheritance


and multilevel inheritance. Since multiple inheritance is not supported in Java as it
leads to ambiguity, so this type of inheritance can only be achieved through the use
of the interfaces.

If we talk about the flowchart, class A is a parent class for class B and C, whereas
Class B and C are the parent class of D which is the only child class of B and C.

Now we have learned about inheritance and their different types. Let’s switch to
another object oriented programming concept i.e Encapsulation.
The syntax of Java Inheritance
1. class Subclass-name extends Superclass-name
2. {
3. //methods and fields
4. }

The extends keyword indicates that you are making a new class that derives from an
existing class. The meaning of "extends" is to increase the functionality.

In the terminology of Java, a class which is inherited is called a parent or superclass, and
the new class is called child or subclass.
Object Oriented Programming : Encapsulation

Encapsulation is a mechanism where you bind your data and code together as a single
unit. It also means to hide your data in order to make it safe from any
modification. What does this mean? The best way to understand encapsulation is to
look at the example of a medical capsule, where the drug is always safe inside the
capsule. Similarly, through encapsulation the methods and variables of a class are
well hidden and safe.

We can achieve encapsulation in Java by:

 Declaring the variables of a class as private.


 Providing public setter and getter methods to modify and view the variables
values.

Let us look at the code below to get a better understanding of encapsulation:


public class Employee {

private String name;

public String getName() {

return name;

public void setName(String name) {

this.name = name;

public static void main(String[] args) {

OUTPUT

Programmer salary is:40000.0


Bonus of programmer is:10000

Single Inheritance Example


File: TestInheritance.java

1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class TestInheritance{
8. public static void main(String args[]){
9. Dog d=new Dog();
10. d.bark();
11. d.eat();
12. }}

Output:

barking...
eating...

Multilevel Inheritance Example


File: TestInheritance2.java

1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class BabyDog extends Dog{
8. void weep(){System.out.println("weeping...");}
9. }
10. class TestInheritance2{
11. public static void main(String args[]){
12. BabyDog d=new BabyDog();
13. d.weep();
14. d.bark();
15. d.eat();
16. }}

Output:

weeping...
barking...
eating...

Hierarchical Inheritance Example


File: TestInheritance3.java

1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class Cat extends Animal{
8. void meow(){System.out.println("meowing...");}
9. }
10. class TestInheritance3{
11. public static void main(String args[]){
12. Cat c=new Cat();
13. c.meow();
14. c.eat();
15. //c.bark();//C.T.Error
16. }}

Output:

meowing...
eating...

Let us try to understand the above code. I have created a class Employee which has
a private variable name. We have then created a getter/accessor and setter/mutator
methods through which we can get and set the name of an employee. Through these
methods, any class which wishes to access the name variable has to do it using these
getter and setter methods.

Let’s move forward to our third Object-oriented programming concept i.e. Abstraction.
Abstraction refers to the quality of dealing with ideas rather than events. It basically
deals with hiding the details and showing the essential things to the user. If you look
at the image here, whenever we get a call, we get an option to either pick it up or just
reject it. But in reality, there is a lot of code that runs in the background. So you don’t
know the internal processing of how a call is generated, that’s the beauty of
abstraction. Therefore, abstraction helps to reduce complexity. You can achieve
abstraction in two ways:

a) Abstract Class

b) Interface

Let’s understand these concepts in more detail.

Abstract class: Abstract class in Java contains the ‘abstract’ keyword. Now what does
the abstract keyword mean? If a class is declared abstract, it cannot be instantiated,
which means you cannot create an object of an abstract class. Also, an abstract class
can contain abstract as well as concrete methods.
Note: You can achieve 0-100% abstraction using abstract class.

To use an abstract class, you have to inherit it from another class where you have to
provide implementations for the abstract methods there itself, else it will also become
an abstract class.

Let’s look at the syntax of an abstract class:


Abstract class Mobile { // abstract class mobile
Abstract void run(); // abstract method

Interface: Interface in Java is a blueprint of a class or you can say it is a collection


of abstract methods and static constants. In an interface, each method is public and
abstract but it does not contain any constructor. Along with abstraction, interface also
helps to achieve multiple inheritance in Java.
Note: You can achieve 100% abstraction using interfaces.

So an interface basically is a group of related methods with empty bodies. Let us


understand interfaces better by taking an example of a ‘ParentCar’ interface with its
related methods.
public interface ParentCar {
public void changeGear( int newValue);
public void speedUp(int increment);
public void applyBrakes(int decrement);
}

These methods need be present for every car, right? But their working is going to be
different.

Let’s say you are working with manual car, there you have to increment the gear one
by one, but if you are working with an automatic car, that time your system decides
how to change gear with respect to speed. Therefore, not all my subclasses have the
same logic written for change gear. The same case is for speedup, now let’s say when
you press an accelerator, it speeds up at the rate of 10kms or 15kms. But suppose,
someone else is driving a super car, where it increment by 30kms or 50kms. Again
the logic varies. Similarly for applybrakes, where one person may have powerful
brakes, other may not.

Since all the functionalities are common with all my subclasses, I have created an
interface ‘ParentCar’ where all the functions are present. After that, I will create a
child class which implements this interface, where the definition to all these method
varies.

Next, let’s look into the functionality as to how you can implement this interface.
So to implement this interface, the name of your class would change to any particular
brand of a Car, let’s say I’ll take an “Audi”. To implement the class interface, I will
use the ‘implement’ keyword as seen below:
public class Audi implements ParentCar {
int speed=0;
int gear=1;
public void changeGear( int value){
gear=value;
}
public void speedUp( int increment)
{
speed=speed+increment;
}
public void applyBrakes(int decrement)
{
speed=speed-decrement;
}
void printStates(){
System.out.println("speed:"+speed+"gear:"+gear);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Audi A6= new Audi();
A6.speedUp(50);
A6.printStates();
A6.changeGear(4);
A6.SpeedUp(100);
A6.printStates();
}
}

Here as you can see, I have provided functionalities to the different methods I have
declared in my interface class. Implementing an interface allows a class to become
more formal about the behavior it promises to provide. You can create another class
as well, say for example BMW class which can inherit the same interface ‘car’ with
different functionalities.

Object Oriented Programming : Polymorphism

Polymorphism means taking many forms, where ‘poly’ means many and ‘morph’
means forms. It is the ability of a variable, function or object to take on multiple
forms. In other words, polymorphism allows you define one interface or method and
have multiple implementations.

Let’s understand this by taking a real-life example and how this concept fits into Object
oriented programming.
Let’s consider this real world scenario in cricket, we know that there are different types
of bowlers i.e. Fast bowlers, Medium pace bowlers and spinners. As you can see in the
above figure, there is a parent class-BowlerClass and it has three child
classes: FastPacer, MediumPacer and Spinner. Bowler class
hasbowlingMethod() where all the child classes are inheriting this method. As we
all know that a fast bowler will going to bowl differently as compared to medium pacer
and spinner in terms of bowling speed, long run up and way of bowling, etc. Similarly
a medium pacer’s implementation of bowlingMethod() is also going to be different
as compared to other bowlers. And same happens with spinner class.
The point of above discussion is simply that a same name tends to multiple forms. All
the three classes above inherited the bowlingMethod() but their implementation is
totally different from one another.

Polymorphism in Java is of two types:

1. Run time polymorphism


2. Compile time polymorphism

Run time polymorphism: In Java, runtime polymorphism refers to a process in


which a call to an overridden method is resolved at runtime rather than at compile-
time. In this, a reference variable is used to call an overridden method of a superclass
at run time. Method overriding is an example of run time polymorphism. Let us
look the following code to understand how the method overriding works:

public Class BowlerClass{


void bowlingMethod()
{
System.out.println(" bowler ");
}
public Class FastPacer{
void bowlingMethod()
{
System.out.println(" fast bowler ");
}
Public static void main(String[] args)
{
FastPacer obj= new FastPacer();
obj.bowlingMethod();
}
}

Compile time polymorphism: In Java, compile time polymorphism refers to a


process in which a call to an overloaded method is resolved at compile time rather
than at run time. Method overloading is an example of compile time
polymorphism. Method Overloading is a feature that allows a class to have two or
more methods having the same name but the arguments passed to the methods are
different. Unlike method overriding, arguments can differ in:

1. Number of parameters passed to a method


2. Datatype of parameters
3. Sequence of datatypes when passed to a method.

Let us look at the following code to understand how the method overloading works:
class Adder {
Static int add(int a, int b)
{
return a+b;
}
static double add( double a, double b)
{
return a+b;
}

public static void main(String args[])


{
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}
}

Method Overloading in Java


If a class has multiple methods having same name but different in parameters, it is known as Method O

If we have to perform only one operation, having same name of the methods increases the readability o

Suppose you have to perform addition of the given numbers but there can be any number of arguments
method such as a(int,int) for two parameters, and b(int,int,int) for three parameters then it may be diff
other programmers to understand the behavior of the method because its name differs.

So, we perform method overloading to figure out the program quickly.


Advantage of method overloading

Method overloading increases the readability of the program.

Different ways to overload the method

There are two ways to overload the method in java

1. By changing number of arguments


2. By changing the data type

Method Overloading: changing no. of arguments


In this example, we have created two methods, first add() method performs addition of two numbers an
performs addition of three numbers.

In this example, we are creating static methods so that we don't need to create instance for calling met

1. class Adder{
2. static int add(int a,int b){return a+b;}
3. static int add(int a,int b,int c){return a+b+c;}
4. }
5. class TestOverloading1{
6. public static void main(String[] args){
7. System.out.println(Adder.add(11,11));
8. System.out.println(Adder.add(11,11,11));
9. }}

Output:

22
33

Method Overriding in Java


If subclass (child class) has the same method as declared in the parent class, it is known as method ov

In other words, If a subclass provides the specific implementation of the method that has been declared
class, it is known as method overriding.

Usage of Java Method Overriding


o Method overriding is used to provide the specific implementation of a method which is already pr
superclass.
o Method overriding is used for runtime polymorphism
Rules for Java Method Overriding
1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
3. There must be an IS-A relationship (inheritance).

Example of method overriding


In this example, we have defined the run method in the subclass as defined in the parent class but it ha
implementation. The name and parameter of the method are the same, and there is IS-A relationship b
there is method overriding.

1. //Java Program to illustrate the use of Java Method Overriding


2. //Creating a parent class.
3. class Vehicle{
4. //defining a method
5. void run(){System.out.println("Vehicle is running");}
6. }
7. //Creating a child class
8. class Bike2 extends Vehicle{
9. //defining the same method as in the parent class
10. void run(){System.out.println("Bike is running safely");}
11.
12. public static void main(String args[]){
13. Bike2 obj = new Bike2();//creating object
14. obj.run();//calling method
15. }
16. }

Output:

Bike is running safely

A real example of Java Method Overriding


Consider a scenario where Bank is a class that provides functionality to get the rate of interest. Howeve
varies according to banks. For example, SBI, ICICI and AXIS banks could provide 8%, 7%, and 9% rate
Java method overriding is mostly used in Runtime Polymorphism which we will learn in next pages.

1. //Java Program to demonstrate the real scenario of Java Method Overriding


2. //where three classes are overriding the method of a parent class.
3. //Creating a parent class.
4. class Bank{
5. int getRateOfInterest(){return 0;}
6. }
7. //Creating child classes.
8. class SBI extends Bank{
9. int getRateOfInterest(){return 8;}
10. }
11.
12. class ICICI extends Bank{
13. int getRateOfInterest(){return 7;}
14. }
15. class AXIS extends Bank{
16. int getRateOfInterest(){return 9;}
17. }
18. //Test class to create objects and call the methods
19. class Test2{
20. public static void main(String args[]){
21. SBI s=new SBI();
22. ICICI i=new ICICI();
23. AXIS a=new AXIS();
24. System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
25. System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
26. System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
27. }
28. }

Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9

Difference between method overloading and metho


overriding in java
There are many differences between method overloading and method overriding in java. A list of differe
overloading and method overriding are given below:

No. Method Overloading Method Overriding

1) Method overloading is used to increase the readability of Method overriding is used t


the program. specific implementation of
that is already provided by

2) Method overloading is performed within class. Method overriding occurs in


classesthat have IS-A (inhe
relationship.

3) In case of method overloading, parameter must be In case of method overridin


different. must be same.

4) Method overloading is the example of compile time Method overriding is the ex


polymorphism. time polymorphism.

5) In java, method overloading can't be performed by Return type must be same


changing return type of the method only. Return type can method overriding.
be same or different in method overloading. But you must
have to change the parameter.

Java Method Overloading example


1. class OverloadingExample{
2. static int add(int a,int b){return a+b;}
3. static int add(int a,int b,int c){return a+b+c;}
4. }

Java Method Overriding example


1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void eat(){System.out.println("eating bread...");}
6. }

JAVA NAMING CONVENTIONS


Java naming convention is a rule to follow as you decide what to name your identifiers
such as class, package, variable, constant, method etc.

But, it is not forced to follow. So, it is known as convention not rule.

All the classes, interfaces, packages, methods and fields of java programming language
are given according to java naming convention.

Advantage of naming conventions in java


By using standard Java naming conventions, you make your code easier to read for
yourself and for other programmers. Readability of Java program is very important. It
indicates that less time is spent to figure out what the code does.

Name Convention

class name should start with uppercase letter and be a noun e.g. String, Color, Button, Sys
etc.

interface name should start with uppercase letter and be an adjective e.g. Runnable, Remote,
etc.

method name should start with lowercase letter and be a verb e.g. actionPerformed(), main()
println() etc.
variable name should start with lowercase letter e.g. firstName, orderNumber etc.

package name should be in lowercase letter e.g. java, lang, sql, util etc.

constants should be in uppercase letter. e.g. RED, YELLOW, MAX_PRIORITY etc.


name

CamelCase in java naming conventions


Java follows camelcase syntax for naming the class, interface, method and variable.

If name is combined with two words, second word will start with uppercase letter always
e.g. actionPerformed(), firstName, ActionEvent, ActionListener etc.

You might also like