OOP (Object oriented programming)


OOP (Object oriented programming)

Object-oriented programming is a method of programming based on a hierarchy of classes, and well-defined and cooperating objects. Procedural programming is about writing procedures or methods that perform operations on the data, while object-oriented programming is about creating objects that contain both data and methods.


Java Class

Class are a blueprint or a set of instructions to build a specific type of object. It is a basic concept of Object-Oriented Programming which revolve around the real-life entities. Class in Java determines how an object will behave and what the object will contain. class ClassName {
// fields
// methods
}

Methods

A method is a block of code which only runs when it is called. You can pass data, known as parameters, into a method. Methods are used to perform certain actions, and they are also known as functions. modifier static returnType nameOfMethod (parameter1, parameter2, ...) {
// method body
}

Constructor

A constructor in Java is a special method that is used to initialize objects. The constructor is called when an object of a class is created. class Test {
Test() {
// constructor body
}
}

Objects

An object is any entity that has a state and behavior. A class is a blueprint for the object. class Bicycle {
// state or field
private int gear = 5;
// behavior or method
public void braking() {
System.out.println("Working of Braking");
}
}

// Object Syntax
className object = new className();
// for Bicycle class
Bicycle sportsBicycle = new Bicycle();
Bicycle touringBicycle = new Bicycle();


Java Member

Class member

The components of a class, such as its instance variables or methods are called the members of a class or class members. A class member is declared with an access modifier to specify how it is accessed by the other classes in Java. Class members are the static members.

Object Member

Everything in Java is within classes and objects. Java objects hold a state, state are variables which are saved together within an object, we call them fields or member variables.


Access Modifier

The following table shows the access to members permitted by each modifier.

Modifier Class Package Subclass World
public Y Y Y Y
protected Y Y Y N
no modifier(Default) Y Y N N
private Y N N N

Encapsulation

In Java, a class encapsulates the fields, which hold the state of an object, and the methods, which define the actions of the object. Encapsulation enables you to write reusable programs. It also enables you to restrict access only to those features of an object that are declared public. All other fields and methods are private and can be used for internal object processing.
class Person {
// private field
private int age;
// getter method
public int getAge() {
return age;
}
// setter method
public void setAge(int age) {
this.age = age;
}
}

class Main {
public static void main(String[] args) {
// create an object of Person
Person p1 = new Person();
// change age using setter
p1.setAge(24);
// access age using getter
System.out.println("My age is " + p1.getAge());
}
}


Inheritance

Inheritance can be defined as the process where one class acquires the properties (methods and fields) of another.
The class which inherits the properties of other is known as subclass (derived class, child class) and the class whose properties are inherited is known as superclass (base class, parent class).

Parent /Super Class

A base class is a class in an object-oriented programming language, from which other classes are derived. It facilitates the creation of other classes that can reuse the code implicitly inherited from the base class (except constructors and destructors).

Child/SubClass

A derived class is a Java class that inherits properties from its super class.
class Animal {
// methods and fields
}

// use of extends keyword
// to perform inheritance
class Dog extends Animal {
// methods and fields of Animal
// methods and fields of Dog
}

Diamond Problem:

It is an ambiguity that can rise as a consequence of allowing multiple inheritance. It is a serious problem for other OPPs languages. It is referred to as the diamond Problem.

Diamond Problem

Solution of diamond problem: Interface Implementation.
An implementation of an interface is a Java program that references the interface using the implements keyword. The program is required to provide method logic for all non-default methods.


Abstraction

Abstraction is a process of hiding the implementation details from the user, only the functionality will be provided to the user. In other words, the user will have the information on what the object does instead of how it does it. In Java, abstraction is achieved using Abstract classes and interfaces.

Abstract classes
abstract class Shape{
abstract void calculateArea();
}

class xyz extends Shape{
@Override
void calculateArea()
{
System.out.println("Area of Shape");
}

public static void main(String args[]){
Shape obj = new xyz();
obj.calculateArea();
}
}
Interface

An interface is a completely "abstract class" that is used to group related methods with empty bodies.
To access the interface methods, the interface must be "implemented" (kinda like inherited) by another class with the implements keyword (instead of extends).
// interface
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void run(); // interface method (does not have a body)
}

class Dog implements Animal {
// The body of animalSound() is provided here
// The body of run() is provided here
}

Polymorphism

Polymorphism is a feature of object oriented programming. It is a Greek word where Poly means multiple and morphs means form. It is the ability of an object to take multiple forms.
Polymorphism in JAVA can be defined as a task that can perform a single action in different ways. Polymorphism occurs when there is inheritance, i.e. there are many classes that are related to each other. It allows one to do multiple implementations by defining one interface.

There are two types of Polymorphism:

  • Run time/dynamic polymorphism (example: overriding)
  • Compile time/ static polymorphism (example: overloading)
Overloading

Method overloading is called compile time polymorphism because the decision of which method should be called is decided in the compile time. Method overloading is done by changing the number of arguments of the same method or by changing the data types of the arguments of the same method.
class DisplayOverloading{
public void disp(char c){
System.out.println(c);
}
public void disp(char c, int num){
System.out.println(c + " "+num);
}
}

class Sample{
public static void main(String args[]){
DisplayOverloading obj = new DisplayOverloading();
obj.disp('a');
obj.disp('a',10);
}
}

Overriding

If a subclass (child class) has the same method as declared in the parent class, it is known as method overriding in Java. In other words, if a subclass provides the specific implementation of the method that has been declared by one of its parent classes, it is known as method overriding. It is used for runtime polymorphism.

Static method cannot be overridden. Because the static method belongs to a specific class area whereas the instance method is bound to an object.

class Human{
//Overridden method
public void eat(){
System.out.println("Human is eating");
}
}

class Boy extends Human{
//Overriding method
public void eat(){
System.out.println("Boy is eating");
}

public static void main( String args[]) {
Boy obj = new Boy();
//This will call the child class version of eat()
obj.eat();
}
}

What is a final class in Java?
What happens to string after final classification?

When declaring a class with the final keyword, It enables JVM to make assumptions & optimization. As final is the reserved keyword of java, and once added to any class, it means reference for that class is not allowed to be changed. The compiler will check if any referencing is taking place again then it will produce an error.

If we declare any class final & instantiate any final class, then it becomes created in the pool area, objects created in the pool have a special feature of immutability. Some of the best examples of immutable java classes are String, Integer, Double, etc.