0% found this document useful (0 votes)
3 views12 pages

javaoops

Object-Oriented Programming (OOP) in Java is based on four main principles: Encapsulation, Inheritance, Polymorphism, and Abstraction, which help in designing applications using objects and classes. Each principle is explained with definitions and examples, illustrating how they contribute to modularity, reusability, flexibility, and security in programming. The document also covers the differences between abstract classes and interfaces, types of inheritance, and the benefits of using OOP in Java.

Uploaded by

Richards Dande
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
3 views12 pages

javaoops

Object-Oriented Programming (OOP) in Java is based on four main principles: Encapsulation, Inheritance, Polymorphism, and Abstraction, which help in designing applications using objects and classes. Each principle is explained with definitions and examples, illustrating how they contribute to modularity, reusability, flexibility, and security in programming. The document also covers the differences between abstract classes and interfaces, types of inheritance, and the benefits of using OOP in Java.

Uploaded by

Richards Dande
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 12

Object-Oriented Programming (OOP) in Java is a programming paradigm that uses "objects" and

classes to design applications. It is based on four main principles: Encapsulation, Inheritance,


Polymorphism, and Abstraction. Let’s break down each of these with definitions and examples.
1. Encapsulation
Encapsulation is the concept of wrapping data (variables) and methods (functions) into a single unit,
typically a class. It restricts direct access to some of an object’s components, meaning the internal
representation of an object is hidden from the outside world, only exposing certain parts.
Example:
class Employee {
// private variables to encapsulate data
private String name;
private int age;

// Constructor to initialize the values


public Employee(String name, int age) {
this.name = name;
this.age = age;
}

// Getter methods to access private data


public String getName() {
return name;
}

public int getAge() {


return age;
}

// Setter methods to modify private data


public void setName(String name) {
this.name = name;
}

public void setAge(int age) {


this.age = age;
}
}

public class Main {


public static void main(String[] args) {
Employee emp = new Employee("John", 30);
// Accessing private data through getter method
System.out.println(emp.getName()); // Output: John
}
}
In the above example, the name and age variables are private, and you can only access or modify
them through getter and setter methods.
2. Inheritance
Inheritance allows a new class (child class) to inherit properties and methods of an existing class
(parent class). This promotes code reuse and establishes a parent-child relationship between classes.
Example:
// Parent class
class Animal {
public void eat() {
System.out.println("This animal eats food");
}
}

// Child class inheriting from Animal


class Dog extends Animal {
public void bark() {
System.out.println("The dog barks");
}
}

public class Main {


public static void main(String[] args) {
Dog dog = new Dog();
dog.eat(); // Inherited method from Animal
dog.bark(); // Method from Dog class
}
}
Here, Dog is a subclass of Animal. It inherits the eat() method from the Animal class and also has its
own method bark().
3. Polymorphism
Polymorphism allows one interface to be used for a general class of actions. There are two types of
polymorphism in Java:
Compile-time Polymorphism (Method Overloading)
Run-time Polymorphism (Method Overriding)
Example of Method Overloading (Compile-time Polymorphism):
class MathOperation {
// Overloaded method with two parameters
public int add(int a, int b) {
return a + b;
}

// Overloaded method with three parameters


public int add(int a, int b, int c) {
return a + b + c;
}
}

public class Main {


public static void main(String[] args) {
MathOperation math = new MathOperation();
System.out.println(math.add(10, 20)); // Output: 30
System.out.println(math.add(10, 20, 30)); // Output: 60
}
}
Here, add() method is overloaded with different parameters, allowing the same method name to
perform different tasks.
Example of Method Overriding (Run-time Polymorphism):
class Animal {
// Parent class method
public void sound() {
System.out.println("This is an animal sound");
}
}

class Dog extends Animal {


// Overriding the sound() method in Dog class
@Override
public void sound() {
System.out.println("The dog barks");
}
}

public class Main {


public static void main(String[] args) {
Animal myDog = new Dog(); // Polymorphism
myDog.sound(); // Output: The dog barks
}
}
In the above example, the sound() method is overridden by the Dog class to provide its own
implementation, while the object is of type Animal.
4. Abstraction
Abstraction is the concept of hiding the complex implementation details and showing only the
essential features of an object. It is achieved using abstract classes and interfaces.
Example of Abstract Class:
// Abstract class
abstract class Vehicle {
// Abstract method (does not have a body)
abstract void start();

// Non-abstract method
public void stop() {
System.out.println("Vehicle stopped");
}
}

// Subclass (Inherits from Vehicle)


class Car extends Vehicle {
// Providing body to the abstract method
public void start() {
System.out.println("Car started");
}
}

public class Main {


public static void main(String[] args) {
Vehicle myCar = new Car();
myCar.start(); // Output: Car started
myCar.stop(); // Output: Vehicle stopped
}
}
In this example, Vehicle is an abstract class, and Car provides the implementation of the abstract
method start().
Benefits of OOP:
Modularity: The source code can be divided into different modules, making it easier to maintain.
Reusability: Through inheritance, you can reuse existing code, making it more efficient.
Flexibility: Polymorphism allows code to be flexible, accommodating new changes without much
modification.
Security: Encapsulation hides sensitive data from external access.
These OOP principles form the foundation for building robust and maintainable Java applications.

In Java, abstraction can be achieved using either abstract classes or interfaces. The implements
keyword is used with interfaces, while the extends keyword is used with abstract classes. Let me
clarify both cases:
1. Abstract Classes and the extends Keyword
When a class is declared as abstract, it can have both abstract methods (without implementation)
and concrete methods (with implementation). To use an abstract class, another class must extend it
and provide implementations for the abstract methods.
Example of Abstract Class with extends:
// Abstract class
abstract class Animal {
// Abstract method (no implementation)
abstract void sound();

// Concrete method
public void sleep() {
System.out.println("Animal is sleeping");
}
}

// Concrete class that extends the abstract class


class Dog extends Animal {
// Providing implementation for the abstract method
@Override
void sound() {
System.out.println("Dog barks");
}
}

public class Main {


public static void main(String[] args) {
Animal myDog = new Dog(); // Creating an object of Dog
myDog.sound(); // Output: Dog barks
myDog.sleep(); // Output: Animal is sleeping
}
}
Here, the class Dog extends the abstract class Animal and provides an implementation for the
abstract method sound().
2. Interfaces and the implements Keyword
An interface is a completely abstract class, meaning it can only have abstract methods (until Java 8
introduced default and static methods). Classes that use an interface must implement the methods
of that interface.
Example of Interface with implements:
// Interface
interface Animal {
// Abstract method (no implementation)
void sound();

// Abstract method (no implementation)


void sleep();
}

// Concrete class implementing the interface


class Dog implements Animal {
// Providing implementation for the abstract methods
@Override
public void sound() {
System.out.println("Dog barks");
}

@Override
public void sleep() {
System.out.println("Dog is sleeping");
}
}

public class Main {


public static void main(String[] args) {
Animal myDog = new Dog(); // Creating an object of Dog
myDog.sound(); // Output: Dog barks
myDog.sleep(); // Output: Dog is sleeping
}
}
Here, the class Dog implements the Animal interface and provides definitions for the methods
sound() and sleep().
Key Differences:
Abstract Class:
Can have both abstract and concrete methods.
Supports inheritance using extends.
Can have member variables and constructors.
Interface:
Can only have abstract methods (until Java 8 introduced default and static methods).
Supports multiple inheritance using implements.
Cannot have instance variables (except constants) or constructors.
When to Use:
Use an abstract class when you want to provide common functionality (with concrete methods) for
all subclasses but also allow subclasses to have their own specific implementations of abstract
methods.
Use an interface when you need to define a contract that classes must follow (without enforcing any
specific implementation) or when you need to support multiple inheritance.
Let's demonstrate the difference between abstract classes and interfaces based on your request. I'll
create an example that shows:
An abstract class with concrete methods: This will provide common functionality for all subclasses
but allow subclasses to implement their own specific methods.
An interface: This will define a contract that classes must follow without enforcing any specific
implementation and can support multiple inheritance.
1. Using an Abstract Class: Common Functionality and Specific Implementations
// Abstract class with common functionality (concrete method) and abstract method
abstract class Animal {
// Concrete method providing common functionality
public void eat() {
System.out.println("All animals eat food.");
}

// Abstract method, which each subclass must implement


abstract void sound();
}

// Subclass 1: Dog
class Dog extends Animal {
// Providing specific implementation for the sound() method
@Override
void sound() {
System.out.println("Dog barks");
}
}

// Subclass 2: Cat
class Cat extends Animal {
// Providing specific implementation for the sound() method
@Override
void sound() {
System.out.println("Cat meows");
}
}

public class Main {


public static void main(String[] args) {
// Common functionality provided by the abstract class
Animal myDog = new Dog();
myDog.eat(); // Output: All animals eat food.
myDog.sound(); // Output: Dog barks

Animal myCat = new Cat();


myCat.eat(); // Output: All animals eat food.
myCat.sound(); // Output: Cat meows
}
}
In this example:
The Animal abstract class provides a common method (eat()) that all animals perform (eating).
Each subclass (Dog and Cat) has its own specific implementation of the abstract method sound(),
which differs for each animal.
2. Using an Interface: Defining a Contract and Supporting Multiple Inheritance
// Interface defining the contract for all animals
interface AnimalActions {
void sound(); // Abstract method to be implemented
void move(); // Another abstract method to be implemented
}

// Interface defining additional behavior (for swimming animals)


interface Swim {
void swim(); // Abstract method to be implemented by swimming animals
}

// Class implementing multiple interfaces (inheritance of behavior)


class Dolphin implements AnimalActions, Swim {
// Implementing sound() method from AnimalActions interface
@Override
public void sound() {
System.out.println("Dolphin clicks");
}

// Implementing move() method from AnimalActions interface


@Override
public void move() {
System.out.println("Dolphin swims gracefully");
}

// Implementing swim() method from Swim interface


@Override
public void swim() {
System.out.println("Dolphin is swimming fast");
}
}

// Another class implementing just AnimalActions interface


class Bird implements AnimalActions {
@Override
public void sound() {
System.out.println("Bird chirps");
}

@Override
public void move() {
System.out.println("Bird flies");
}
}

public class Main {


public static void main(String[] args) {
// Using Dolphin class that implements multiple interfaces
Dolphin dolphin = new Dolphin();
dolphin.sound(); // Output: Dolphin clicks
dolphin.move(); // Output: Dolphin swims gracefully
dolphin.swim(); // Output: Dolphin is swimming fast

// Using Bird class that implements only AnimalActions


Bird bird = new Bird();
bird.sound(); // Output: Bird chirps
bird.move(); // Output: Bird flies
}
}
In this example:
The AnimalActions interface defines the contract for animals (methods sound() and move()).
The Swim interface defines a contract specifically for swimming behavior (swim()).
Dolphin class implements both AnimalActions and Swim interfaces, which demonstrates multiple
inheritance (implementing methods from two interfaces).
Bird class implements only the AnimalActions interface.
Key Differences Illustrated:
Abstract Class (Example 1):
The abstract class Animal provides a concrete method (eat()), which gives common functionality that
is shared by all subclasses.
The subclasses (Dog, Cat) must implement the abstract method (sound()), allowing them to provide
their own specific functionality.
Interface (Example 2):
The interface AnimalActions only defines a contract (what methods the classes should implement)
without providing any common functionality.
The Dolphin class implements methods from both the AnimalActions and Swim interfaces, showing
multiple inheritance of behaviors, which isn’t possible with abstract classes. Each class can choose
how to implement the methods defined in the interfaces.
In summary:
Use abstract classes when you want to provide common functionality (with concrete methods) to
subclasses.
Use interfaces when you need to define a contract that multiple classes can follow, or when you
need to implement multiple inheritance (since Java doesn’t support multiple inheritance with
classes, but allows a class to implement multiple interfaces).

In object-oriented programming (OOP), inheritance allows one class to inherit the properties and
methods of another class. Java supports certain types of inheritance, but unlike other programming
languages like C++, Java does not support multiple inheritance with classes (to avoid complexity and
ambiguity). Below are the main types of inheritance:
1. Single Inheritance
In single inheritance, a class inherits from one parent (or superclass). This is the simplest form of
inheritance.
Example:
class Animal {
void eat() {
System.out.println("This animal eats food");
}
}

class Dog extends Animal {


void bark() {
System.out.println("The dog barks");
}
}

public class Main {


public static void main(String[] args) {
Dog dog = new Dog();
dog.eat(); // Output: This animal eats food
dog.bark(); // Output: The dog barks
}
}
Here, the Dog class inherits from the Animal class, demonstrating single inheritance.
2. Multilevel Inheritance
In multilevel inheritance, a class inherits from a class that is already a subclass. In other words, it
forms a chain of inheritance.
Example:
class Animal {
void eat() {
System.out.println("This animal eats food");
}
}

class Mammal extends Animal {


void walk() {
System.out.println("This mammal walks");
}
}

class Dog extends Mammal {


void bark() {
System.out.println("The dog barks");
}
}

public class Main {


public static void main(String[] args) {
Dog dog = new Dog();
dog.eat(); // Output: This animal eats food
dog.walk(); // Output: This mammal walks
dog.bark(); // Output: The dog barks
}
}
Here, the Dog class inherits from the Mammal class, which in turn inherits from the Animal class.
This demonstrates multilevel inheritance.
3. Hierarchical Inheritance
In hierarchical inheritance, multiple classes inherit from a single parent class. This is useful when you
want several subclasses to share the properties and methods of a common superclass.
Example:
class Animal {
void eat() {
System.out.println("This animal eats food");
}
}

class Dog extends Animal {


void bark() {
System.out.println("The dog barks");
}
}

class Cat extends Animal {


void meow() {
System.out.println("The cat meows");
}
}

public class Main {


public static void main(String[] args) {
Dog dog = new Dog();
dog.eat(); // Output: This animal eats food
dog.bark(); // Output: The dog barks

Cat cat = new Cat();


cat.eat(); // Output: This animal eats food
cat.meow(); // Output: The cat meows
}
}
Here, both Dog and Cat inherit from the Animal class, demonstrating hierarchical inheritance.
4. Multiple Inheritance (with Interfaces)
Java does not support multiple inheritance with classes (i.e., a class cannot have more than one
parent class) to avoid the diamond problem. However, Java allows multiple inheritance through
interfaces. A class can implement more than one interface, thus achieving multiple inheritance in a
controlled way.
Example:
// First interface
interface CanRun {
void run();
}

// Second interface
interface CanBark {
void bark();
}

// Class implementing both interfaces


class Dog implements CanRun, CanBark {
@Override
public void run() {
System.out.println("The dog runs");
}
@Override
public void bark() {
System.out.println("The dog barks");
}
}

public class Main {


public static void main(String[] args) {
Dog dog = new Dog();
dog.run(); // Output: The dog runs
dog.bark(); // Output: The dog barks
}
}
In this case, the Dog class implements both the CanRun and CanBark interfaces, demonstrating
multiple inheritance through interfaces.
5. Hybrid Inheritance (Not Supported Directly in Java)
Hybrid inheritance is a combination of two or more types of inheritance (e.g., hierarchical and
multiple inheritance). Java doesn’t support hybrid inheritance through classes directly because it
doesn’t allow multiple inheritance (to avoid issues like the diamond problem). However, it can be
achieved through interfaces.
Example:
interface Animal {
void eat();
}

interface CanBark {
void bark();
}

class Dog implements Animal, CanBark {


@Override
public void eat() {
System.out.println("The dog eats");
}

@Override
public void bark() {
System.out.println("The dog barks");
}
}

class Cat implements Animal {


@Override
public void eat() {
System.out.println("The cat eats");
}

void meow() {
System.out.println("The cat meows");
}
}
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.eat(); // Output: The dog eats
dog.bark(); // Output: The dog barks

Cat cat = new Cat();


cat.eat(); // Output: The cat eats
cat.meow(); // Output: The cat meows
}
}
Recap:
Single Inheritance: One class inherits from a single superclass.
Multilevel Inheritance: A class inherits from a class, which is already a subclass of another class.
Hierarchical Inheritance: Multiple classes inherit from a single superclass.
Multiple Inheritance: Achieved using interfaces in Java, where a class can implement multiple
interfaces.
Hybrid Inheritance: A combination of multiple types of inheritance, achieved in Java through
interfaces.
Java uses interfaces to avoid complexities like the diamond problem seen in multiple inheritance.

You might also like