0% found this document useful (0 votes)
2 views17 pages

Oops Concepts in Java

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)
2 views17 pages

Oops Concepts in Java

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/ 17

OOPS CONCEPTS IN JAVA

Important notes
1. Introduction to OOP
Definition:
Object-Oriented Programming (OOP) is a programming paradigm that uses "objects" to represent data and methods to
manipulate that data. OOP allows for organized code, easier troubleshooting, and greater reuse of code.

Key Principles of OOP:


• Encapsulation: Restricting access to certain components to protect the integrity of the object.
• Inheritance: Allowing one class to inherit the properties and methods of another class.
• Polymorphism: Enabling one interface to be used for a general class of actions.
• Abstraction: Hiding complex implementation details and exposing only the necessary parts.

2. Classes and Objects


Definition
• Class: A blueprint or template for creating objects. It defines the data attributes and methods that operate on
the data.
• Object: An instance of a class. Objects hold the state and behavior defined by the class.

• Classes and Objects are basic concepts of Object Oriented Programming that revolve around real-life
entities.
• Class is a set of object which shares common characteristics/ behavior and common properties/
attributes.
• Object is a basic unit of Object-Oriented Programming and represents real-life entities. A typical
Java program creates many objects, which as you know, interact by invoking method

Syntax
class ClassName {
// Attributes
dataType attributeName;

// Methods
returnType methodName(parameters) {
// method body
}
}
Example
class Dog {
String name; // Attribute
int age; // Attribute

// Method
void bark() {
System.out.println("Woof! My name is " + name);
}
}

public class Main {


public static void main(String[] args) {
Dog myDog = new Dog(); // Creating an object of Dog
myDog.name = "Buddy"; // Setting attribute
myDog.age = 3; // Setting attribute
myDog.bark(); // Calling method
}
}
Explanation
In the example:
• Dog is a class with attributes name and age, and a method bark().
• An object myDog of class Dog is created, and its attributes are initialized.
• The bark() method is invoked, demonstrating how objects interact with their methods.

3. Inheritance
Definition
Inheritance is a fundamental concept in Object-Oriented Programming (OOP) that allows a new class (called
a subclass or child class) to inherit the properties and methods of an existing class (called a superclass or
parent class). This promotes code reusability, allowing developers to create new functionality with less effort
by building on existing code.
Benefits of Inheritance
Code Reusability: Inherits methods and attributes from existing classes.
Method Overriding: Subclasses can provide specific implementations of methods defined in the superclass.
Polymorphism: Allows for treating subclasses as instances of their superclass.
Types of Inheritance
Single Inheritance
Multilevel Inheritance
Hierarchical Inheritance
Multiple Inheritance (not directly supported in Java)
Hybrid Inheritance (not directly supported in Java)

________________________________________
1. Single Inheritance
Definition: Single inheritance is when a subclass inherits from one superclass only.
Example
class Animal {
void eat() {
System.out.println("Animal eats.");
}
}

class Dog extends Animal {


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

public class Main {


public static void main(String[] args) {
Dog myDog = new Dog();
myDog.eat(); // Output: Animal eats.
myDog.bark(); // Output: Dog barks.
}
}
Explanation:
Dog is a subclass of Animal, inheriting the eat() method. The Dog class can also define its own methods like
bark().
________________________________________
2. Multilevel Inheritance
Definition: Multilevel inheritance is when a subclass inherits from another subclass, creating a chain of
inheritance.
Example
class Animal {
void eat() {
System.out.println("Animal eats.");
}
}

class Dog extends Animal {


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

class Puppy extends Dog {


void weep() {
System.out.println("Puppy weeps.");
}
}

public class Main {


public static void main(String[] args) {
Puppy myPuppy = new Puppy();
myPuppy.eat(); // Output: Animal eats.
myPuppy.bark(); // Output: Dog barks.
myPuppy.weep(); // Output: Puppy weeps.
}
}
Explanation:
Here, Puppy extends Dog, which in turn extends Animal. This creates a hierarchy where Puppy inherits
methods from both Dog and Animal.
________________________________________
3. Hierarchical Inheritance
Definition: Hierarchical inheritance is when multiple subclasses inherit from the same superclass.
Example
class Animal {
void eat() {
System.out.println("Animal eats.");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog barks.");
}
}

class Cat extends Animal {


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

public class Main {


public static void main(String[] args) {
Dog myDog = new Dog();
Cat myCat = new Cat();

myDog.eat(); // Output: Animal eats.


myDog.bark(); // Output: Dog barks.

myCat.eat(); // Output: Animal eats.


myCat.meow(); // Output: Cat meows.
}
}
Explanation:
Both Dog and Cat extend Animal, inheriting its method eat(). Each subclass can implement its own methods.
________________________________________
4. Multiple Inheritance (Not Supported in Java)
Definition: Multiple inheritance occurs when a subclass inherits from multiple super classes.
Why Java Does Not Support Multiple Inheritance:
Diamond Problem: If a subclass inherits from two classes that have a method with the same signature, it
creates ambiguity about which method to invoke. This is known as the diamond problem.
Example of the Diamond Problem:
class A {
void show() {
System.out.println("A's show method");
}
}

class B extends A {
void show() {
System.out.println("B's show method");
}
}

class C extends A {
void show() {
System.out.println("C's show method");
}
}

class D extends B, C { // This is not allowed in Java


}
Remedy:
Java uses interfaces to allow a form of multiple inheritance. A class can implement multiple interfaces, thus
inheriting abstract methods without the ambiguity associated with multiple inheritance.
Example Using Interfaces
interface CanRun {
void run();
}

interface CanBark {
void bark();
}

class Dog implements CanRun, CanBark {


public void run() {
System.out.println("Dog runs.");
}

public void bark() {


System.out.println("Dog barks.");
}
}

public class Main {


public static void main(String[] args) {
Dog myDog = new Dog();
myDog.run(); // Output: Dog runs.
myDog.bark(); // Output: Dog barks.
}
}
________________________________________
5. Hybrid Inheritance (Not Directly Supported)
Definition: Hybrid inheritance is a combination of two or more types of inheritance. It typically involves a
combination of hierarchical, multilevel, or other inheritance types.
Why Java Does Not Support Hybrid Inheritance Directly:
The complexity and ambiguity associated with multiple inheritance, including the diamond problem, means
hybrid inheritance cannot be implemented using classes in Java.
Remedy:
Again, interfaces can be used to achieve hybrid inheritance-like behavior.
Example
interface CanFly {
void fly();
}

interface CanSwim {
void swim();
}
class Bird implements CanFly {
public void fly() {
System.out.println("Bird flies.");
}
}

class Fish implements CanSwim {


public void swim() {
System.out.println("Fish swims.");
}
}

class Duck extends Bird implements CanSwim {


public void swim() {
System.out.println("Duck swims.");
}
}

public class Main {


public static void main(String[] args) {
Duck myDuck = new Duck();
myDuck.fly(); // Output: Bird flies.
myDuck.swim(); // Output: Duck swims.
}
}
Explanation:
In this example, Duck inherits from Bird (demonstrating multilevel inheritance) and implements CanSwim.
This demonstrates a form of hybrid inheritance using interfaces.

4. Polymorphism
Definition
The word polymorphism means having many forms. In simple words, we can define polymorphism as the
ability of a message to be displayed in more than one form.
A person at the same time can have different characteristics. Like a man at the same time is a father, a
husband, an employee. So the same person possesses different behaviour in different situations. This is
called polymorphism.
Polymorphism is considered one of the important features of Object-Oriented Programming. Polymorphism
allows us to perform a single action in different ways. In other words, polymorphism allows you to define
one interface and have multiple implementations. The word “poly” means many and “morphs” means forms,
So it means many forms.

Polymorphism allows methods to perform different tasks based on the object it is acting upon. It can be
achieved through method overriding and method overloading.
Method Overriding
Method overriding is one of the ways in which Java supports Runtime Polymorphism. Dynamic method
dispatch is the mechanism by which a call to an overridden method is resolved at run time, rather than
compile time.
Method overriding occurs when a subclass provides a specific implementation of a method already defined
in its superclass.
Syntax
class Parent {
void display() {
System.out.println("Parent");
}
}

class Child extends Parent {


void display() {
System.out.println("Child");
}
}
Example
public class Main {
public static void main(String[] args) {
Parent obj = new Child(); // Parent reference, Child object
obj.display(); // Output: Child
}
}
Explanation
In this case:
• The display() method in the Child class overrides the display() method in the Parent class.
• When obj.display() is called, it invokes the Child class’s method, demonstrating polymorphism
through method overriding.

Method Overloading
Method overloading in java is based on the number and type of the parameters passed as an argument to the
methods. We can not define more than one method with the same name, Order, and type of the arguments. It
would be a compiler error. The compiler does not consider the return type while differentiating the
overloaded method. But you cannot declare two methods with the same signature and different return types.
It will throw a compile-time error. If both methods have the same parameter types, but different return types,
then it is not possible.
Method overloading occurs when multiple methods have the same name but different parameters.
Syntax
class Display {
void show(int a) {
System.out.println("Integer: " + a);
}

void show(String b) {
System.out.println("String: " + b);
}
}
Example

public class Main {


public static void main(String[] args) {
Display display = new Display();
display.show(5); // Output: Integer: 5
display.show("Hello"); // Output: String: Hello
}
}
Explanation
In this example:
• The show() method is overloaded with different parameter types.
• This demonstrates polymorphism through method overloading, allowing different behaviors for the
same method name.

5. Encapsulation
Definition
Encapsulation is the idea of bundling data and methods that operate on that data within a single unit, called a
class. This unit acts as a container, hiding the internal implementation details from the outside world and
only exposing a public interface through which other objects can interact with it.
Key Benefits of Encapsulation
1. Data Hiding: Encapsulation helps to hide the internal implementation details of an object from the
outside world, making it difficult for other objects to access or modify the data directly.
2. Abstraction: By exposing only a public interface, encapsulation enables abstraction, which allows
objects to interact with each other without knowing the internal implementation details.
3. Code Reusability: Encapsulated code is more modular and reusable, as it can be easily modified or
extended without affecting other parts of the program.
4. Improved Code Organization: Encapsulation helps to organize code in a more structured and
logical way, making it easier to understand and maintain.
How to Achieve Encapsulation in Java
In Java, encapsulation is achieved through the use of:
1. Access Modifiers: Java provides access modifiers such as public, private, and protected to control
access to data and methods.
2. Classes and Objects: Classes define the structure and behavior of objects, and objects are instances
of classes that encapsulate data and methods.
3. Constructors: Constructors are special methods used to initialize objects when they are created.
4. Getter and Setter Methods: Getter and setter methods are used to access and modify the data
encapsulated within an object.

Syntax
class ClassName {
private dataType attributeName; // Private attribute

// Public setter method


public void setAttribute(dataType value) {
this.attributeName = value;
}

// Public getter method


public dataType getAttribute() {
return this.attributeName;
}
}
Example
class Person {
private String name; // Private attribute

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

// Getter method
public String getName() {
return this.name;
}
}

public class Main {


public static void main(String[] args) {
Person person = new Person();
person.setName("Alice"); // Using setter
System.out.println(person.getName()); // Output: Alice
}
}
Explanation
In this example:
• The Person class encapsulates the name attribute, restricting direct access by marking it as private.
• Access is controlled through public setter and getter methods, allowing validation or transformation
before setting or getting the value.
6. Abstraction
Definition
Data Abstraction is the property by virtue of which only the essential details are displayed to the user. The
trivial or the non-essential units are not displayed to the user. Ex: A car is viewed as a car rather than its
individual components.
Data Abstraction may also be defined as the process of identifying only the required characteristics of an
object ignoring the irrelevant details. The properties and behaviors of an object differentiate it from other
objects of similar type and also help in classifying/grouping the objects.
An abstract class in Java is one that is declared with the abstract keyword. It may have both abstract and
non-abstract methods(methods with bodies). An abstract is a java modifier applicable for classes and
methods in java but not for Variables.

Abstraction is the concept of hiding the complex implementation details and exposing only the essential
features of the object. It focuses on what an object does instead of how it does it.
Syntax
abstract class AbstractClass {
abstract void abstractMethod(); // Abstract method
}

class ConcreteClass extends AbstractClass {


void abstractMethod() {
// Implementation of the abstract method
}
}
Example
abstract class Shape {
abstract void draw(); // Abstract method
}

class Circle extends Shape {


void draw() {
System.out.println("Drawing Circle"); // Implementation
}
}
public class Main {
public static void main(String[] args) {
Shape shape = new Circle(); // Upcasting
shape.draw(); // Output: Drawing Circle
}
}
Explanation
In this example:
• Shape is an abstract class that declares an abstract method draw().
• The Circle class provides an implementation for draw().
• The main method creates a Circle object and calls the draw() method, illustrating how abstraction
allows you to define behavior without exposing implementation details.

Interfaces in Java
Definition
An interface in Java is a reference type, similar to a class, that can contain only constants, method signatures,
default methods, static methods, and nested types. Interfaces cannot contain instance fields. The methods in
interfaces are abstract by default, meaning they do not have a body and must be implemented by classes that
choose to implement the interface.
Why Use Interfaces?
• Multiple Inheritance: Interfaces allow a class to implement multiple interfaces, thus overcoming the
limitation of single inheritance in Java.
• Abstraction: They provide a way to define a contract for classes without enforcing implementation.
• Decoupling: Interfaces help in decoupling the code, making it easier to maintain and extend.
Syntax
Defining an Interface:
interface InterfaceName {
// Constant declarations
int CONSTANT_VALUE = 10;

// Abstract method (no body)


void methodName();

// Default method
default void defaultMethod() {
System.out.println("This is a default method.");
}

// Static method
static void staticMethod() {
System.out.println("This is a static method.");
}
}
Implementing an Interface
class ImplementingClass implements InterfaceName {
// Implementing the abstract method
@Override
public void methodName() {
System.out.println("Method implemented.");
}
}
Example
Step 1: Define the Interface
interface Animal {
void sound(); // Abstract method

default void sleep() { // Default method


System.out.println("Sleeping...");
}
}
Step 2: Implement the Interface in a Class
class Dog implements Animal {
@Override
public void sound() { // Implementing the abstract method
System.out.println("Bark!");
}
}
class Cat implements Animal {
@Override
public void sound() { // Implementing the abstract method
System.out.println("Meow!");
}
}
Step 3: Use the Classes
public class Main {
public static void main(String[] args) {
Animal myDog = new Dog(); // Upcasting
myDog.sound(); // Output: Bark!
myDog.sleep(); // Output: Sleeping...

Animal myCat = new Cat(); // Upcasting


myCat.sound(); // Output: Meow!
myCat.sleep(); // Output: Sleeping...
}
}
Explanation
1. Interface Definition: The Animal interface defines an abstract method sound() and a default method
sleep().
2. Class Implementation: The Dog and Cat classes implement the Animal interface and provide their
specific implementations of the sound() method.
3. Using the Classes: In the Main class, we create instances of Dog and Cat as Animal type references.
We call their sound() method, which outputs their respective sounds, and we also call the default
sleep() method, demonstrating the use of the default method.

You might also like