Object-Oriented Programming in Java
Before starting about object-oriented programming, let us first think about what is an “object”.
Object:
blueprint from which you can create an individual object. An object is a real-world entity that has a state and behavior e.g., chair, bike, marker, pen, table, car, etc.
Class:
Class is a blueprint from which you can create an individual object or it’s a collection of objects. e.g. A car is an object because it has states like color, name, brand, etc.
Inheritance
It is a process in which one object acquires all the properties and behaviors of a parent object.
Inheritance represents the IS-A relationship which is also known as a parent-child relationship.
Syntax of Java Inheritance
Types of inheritance in java
- Single
- Multilevel
- Hierarchical.
Multiple inheritance is not supported in java
To reduce the complexity and simplify the language or to remove ambiguity problem multiple inheritance is not supported in java.
Polymorphism
The word polymorphism means having many forms or it is a concept by which we can perform a single action in different ways. e.g. Water has many forms solid, liquid, gas.
There are two types of polymorphism in Java:
- Compile-time polymorphism
- Runtime polymorphism.
This can be performed in java by method overloading and method overriding
Method overriding
In method overriding child class has the same method as declared in the parent class, it is known as method overriding
class car {
void run()
{
System.out.println("running");}class Honda extends car{ void run()
{
System.out.println(" 120 km/h");
}} public static void main(String[] args)
{
Car b = new Honda(); b.run(); }
}
Output:
120km/h
In this example, we have two classes Car and Honda. The child class is overriding the method b.run() of the parent class.
Method overloading
In Java, two or more methods can have the same name but different in parameters in the same class this is called method overloading
class Math{
public int add(int a,int b)
{
return a+b;
}
public int add(int a,int b ,int c)
{
return a+b+c;
}
public double add(double a,double b ,double c)
{
return a+b+c;
}
}class Again
{
public static void main(String[] args)
{
Math m = new Math(); m.add(2,2); System.out.println(m.add(2,2));
System.out.println(m.add(1,2,2));
System.out.println(m.add(1.2,2.1,2.3));}}
Output:
2
5
5.6
In this example, we have created three methods, first,add() method performs the addition of two numbers, and the second add method performs the addition of three numbers and the third method performs the addition of three decimal numbers.