0% found this document useful (0 votes)
7 views2 pages

Java Abstraction and Abstract Classes Guide

Uploaded by

sd470967
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views2 pages

Java Abstraction and Abstract Classes Guide

Uploaded by

sd470967
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Abstraction and Abstract Classes in Java

Q2 a. Explain abstraction and abstract classes in Java. Describe abstract method. With a
suitable example demonstrate the application of abstract classes.

1. Abstraction in Java:
Abstraction is a concept in Object-Oriented Programming (OOP) that allows us to hide the
complex implementation details and show only the essential features of the object. It helps
in reducing programming complexity and increases code reusability.
In Java, abstraction is achieved using:
- Abstract classes
- Interfaces

2. Abstract Class in Java:


An abstract class is a class that cannot be instantiated (you cannot create objects from it). It
can have both abstract methods (without body) and non-abstract methods (with body).

Syntax:

abstract class Animal {


abstract void sound(); // abstract method
void eat() {
[Link]("This animal eats food");
}
}

3. Abstract Method:
An abstract method is a method that is declared without implementation. It must be defined
in a subclass that extends the abstract class.

Syntax:

abstract void sound();

4. Example to demonstrate abstract class and method:


// Abstract class
abstract class Animal {
abstract void sound(); // abstract method

void sleep() {
[Link]("Animals sleep");
}
}

// Subclass
class Dog extends Animal {
void sound() {
[Link]("Dog barks");
}
}

// Main class
public class TestAbstraction {
public static void main(String[] args) {
Animal a = new Dog();
[Link](); // Output: Dog barks
[Link](); // Output: Animals sleep
}
}

5. Application of Abstract Classes:


- Abstract classes provide a base for subclasses to build on.
- Used when some methods should be implemented in subclasses.
- Helps in achieving partial abstraction.

Conclusion:
Abstraction in Java allows hiding internal details and showing only essential features.
Abstract classes and methods help achieve this by forcing subclasses to implement specific
methods, making code organized and reusable.

You might also like