Java OOP

Java OOP

Most important features in OOP?

  1. Encapsulation?
  2. Inheritance
  3. Abstraction
  4. Polymorphism

Encapsulation :?

Encapsulation is one of the most fundamental features of OOP that bundles variables and methods together that operate on a single block (unit) called class. In encapsulation, the variables of a class will be hidden from other classes, and can be accessed only through the methods of their current class. Therefore, it is also known as data hiding.

An object, however, is a manifestation of a class, i.e., an instantiation of it. For example, an object of a person class can be “Person A” or “Person B”. Similarly, an object of the animal class can be a dog, a cat, a cow, etc.?

How to work Encapsulation ? Give me an example of Encapsulation.

Bundling Data and Methods:?

Dog class: {

data:

????????????Breed name:

????????????Colour:

????????????Average weight (kg):

??????functions:

????????????func sit() {}

????????????func bark() {}

????????????func walk() {}


????????????func run() {}

}

Here, as you can see, the Dog class constitutes information about the breed’s name, its color, and average weight through (what are known as) class variables. More attributes define a dog’s breed, but we can stick to these for simplicity.

How ot Information Hiding through Encapsulation ?

There are three primary types of access modifiers across most programming languages —

  • Private: The most restrictive access modifier, ‘private’, allows access to the class/object state only through the class itself (e.g., a class function).?
  • Protected: Being slightly liberal than ‘private’, the ‘protected’ modifier additionally allows access to the state by other classes in the same package and through a child class by inheritance for classes outside the package.
  • Public: This modifier imposes no restrictions on the class variable, allowing it to be directly accessed and modified wherever and whenever required.

How Do You Use Encapsulation?

In programming languages like Java, the access modifiers are specified explicitly when declaring the class variables (or methods).

Getter and Setter Methods

In programming languages like Java, this takes place using (what are known as) getter and setter methods. These are essentially class functions that act as intermediary interfaces to fetch or manipulate the state of your object. The below diagram presents an overview of accessing private variables through getter functions.

What are the Advantages of Encapsulation?

Through these examples we discussed above, you must have noticed several advantages of working with encapsulation. Let’s list them all here —

  • By bundling data and methods into one abstracted unit, encapsulation hides complex, lower-level data.
  • It can prevent unwanted access to sensitive data and hide information through access modifiers while also reducing erroneous human changes.
  • Because code changes can be independent, encapsulation makes code maintenance more manageable.
  • It improves code interpretability.

Inheritance

Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent object. It is an important part of OOPs (Object Oriented programming system).The idea behind inheritance in Java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of the parent class. Moreover, you can add new methods and fields in your current class also.

Inheritance represents the IS-A relationship which is also known as a parent-child relationship.

Why use inheritance in java

Terms used in Inheritance

-Class , Sub class , Supper Class , Reusability?

Types of inheritance in java

  • Single inheritance

Multilevel inheritance?

  • Hierarchical inheritance?

Single Inheritance?

When a class inherits another class, it is known as a single inheritance. In the example given below, Dog class inherits the Animal class, so there is the single inheritance.

class Animal{??

void eat(){System.out.println("eating...");}??

}??

class Dog extends Animal{??

void bark(){System.out.println("barking...");}??

}??

class TestInheritance{??

public static void main(String args[]){??

Dog d=new Dog();??

d.bark();??

d.eat();??

}}??

Multilevel inheritance?

When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in the example given below, BabyDog class inherits the Dog class which again inherits the Animal class, so there is a multilevel inheritance.

class Animal{??

void eat(){System.out.println("eating...");}??

}??

class Dog extends Animal{??

void bark(){System.out.println("barking...");}??

}??

class BabyDog extends Dog{??

void weep(){System.out.println("weeping...");}??

}??

class TestInheritance2{??

public static void main(String args[]){??

BabyDog d=new BabyDog();??

d.weep();??

d.bark();??

d.eat();??

}}?

Hierarchical Inheritance

When two or more classes inherit a single class, it is known as hierarchical inheritance. In the example given below, Dog and Cat classes inherit the Animal class, so there is hierarchical inheritance.

class Animal{??

void eat(){System.out.println("eating...");}??

}??

class Dog extends Animal{??

void bark(){System.out.println("barking...");}??

}??

class Cat extends Animal{??

void meow(){System.out.println("meowing...");}??

}??

class TestInheritance3{??

public static void main(String args[]){??

Cat c=new Cat();??

c.meow();??

c.eat();??

//c.bark();//C.T.Error??

}}?


Why is multiple inheritance not supported in java?

To reduce the complexity and simplify the language, multiple inheritance is not supported in java.Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes. If A and B classes have the same method and you call it from a child class object, there will be ambiguity when calling the method of A or B class.

Since compile-time errors are better than runtime errors, Java renders compile-time errors if you inherit 2 classes. So whether you have the same method or different, there will be a compile time error.

class A{??

void msg(){System.out.println("Hello");}??

}??

?????????????class B{??

void msg(){System.out.println("Welcome");}??

}??

class C extends A,B{//suppose if it were??

public static void main(String args[]){??

??? C obj=new C();??

??? obj.msg();//Now which msg() method would be invoked???

} }?

Abstraction

In simple terms, abstraction “displays” only the relevant attributes of objects and “hides” the unnecessary details.

Abstraction in OOP can be of two types

  1. Data Abstraction

In data abstraction, we mostly create complex data types and hide their implementation. We only expose the operations to manipulate these data types without going into the details of their implementation.

One advantage of this approach is that we can change the implementation anytime without changing the behavior that is exposed to the user.

  1. Control Abstraction

Control abstraction collects all the control statements that are a part of the application and exposes them as a unit. This feature is used when we have to perform a working feature using this control unit.

Control abstraction forms the main unit of structured programming and using control abstraction we can define simple functions to complex frameworks.

What Is Abstraction In Java

As Java is an OOP language, abstraction can be seen as one of the important features and building blocks of the Java language. In Java, abstraction is implemented using an abstract class and interface.

So how do we implement abstraction in Java? Java provides a non-access modifier “abstract” for implementing abstraction. This abstract modifier can be used with classes and methods but not variables.

The interface provides complete abstraction i.e. it only provides method prototypes and not their implementation. An abstract class provides partial abstraction wherein at least one method should not be implemented.

Let’s consider the below example.

//abstract class

abstract class Car{?

????abstract void accelerate();?

}?

//concrete class

class Suzuki extends Car{?

????void accelerate(){

????????System.out.println("Suzuki::accelerate");

?????

????}

}

class Main{

????public static void main(String args[]){?

????????Car obj = new Suzuki(); //Car object =>contents of Suzuki

????????obj.accelerate();? ? ? //call the method?

????}??

}?

What Is Java Abstract Class

We already mentioned that Java implements abstraction using abstract classes and interfaces. Let’s first explore all about the abstract class.

An abstract class can be defined as a class declared with the keyword “abstract” and has a restriction that it cannot be instantiated.

An abstract class may or may not have any abstract method (a method with no implementation). As far as JVM is concerned, an abstract class is an incomplete class that does not have a complete behavior.

The general syntax of an abstract class is given below:

abstract class <classname>

????{

????????????public abstract void abstractMethod();

????????????public void normalMethod()

????????????{

????????????????????//method body

????????????}??

????}??

As shown in the syntax of the above abstract class, we can have abstract as well as non-abstract methods in an abstract class. The keyword ‘abstract’ precedes the class declaration.

Polymorphism

Polymorphism in Java occurs when there are one or more classes or objects related to each other by inheritance. It is the ability of an object to take many forms. Inheritance lets users inherit attributes and methods, and polymorphism uses these methods to perform different tasks. So, the goal is communication, but the approach is different.


How can polymorphism be achieved in Java?

Polymorphism in Java can be achieved in two ways i.e., method overloading and method overriding.

Polymorphism in Java is mainly divided into two types.

  • Compile-time polymorphism (method overloading)
  • Runtime polymorphism (method overriding)


Runtime Polymorphism in Java

Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an overridden method is resolved at runtime rather than compile-time.

In this process, an overridden method is called through the reference variable of a superclass. The determination of the method to be called is based on the object being referred to by the reference variable.


Compile Time Polymorphism

Compile-time polymorphism is also known as static polymorphism or early binding. Compile-time polymorphism is a polymorphism that is resolved during the compilation process. Overloading of methods is called through the reference variable of a class. Compile-time polymorphism is achieved by method overloading and operator overloading.


public class MethodOverloading {

?????

??????// 1 parameter

????void show(int num1)

????{

????????System.out.println("number 1 : " + num1);

????}

?

????// 2 parameter

????void show(int num1, int num2)

????{

????????System.out.println("number 1 : " + num1

???????????????????????????+ "? number 2 : " + num2);

????}

?

????public static void main(String[] args)

????{

????????MethodOverloading obj = new MethodOverloading();

???????

??????????// 1st show function

????????obj.show(3);

???????

??????????// 2nd show function

????????obj.show(4, 5);

????}

}

要查看或添加评论,请登录

Md Kawsar的更多文章

社区洞察

其他会员也浏览了