0% found this document useful (0 votes)
72 views14 pages

Java Abstract Classes & Interfaces Guide

The document provides an overview of abstract classes and interfaces in Java, highlighting their definitions, key features, and differences. It includes examples of faulty code and their corrections, demonstrating the proper use of abstract classes and interfaces. Additionally, it discusses the purpose and characteristics of both constructs, along with examples of their implementation.

Uploaded by

Stu udy
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)
72 views14 pages

Java Abstract Classes & Interfaces Guide

The document provides an overview of abstract classes and interfaces in Java, highlighting their definitions, key features, and differences. It includes examples of faulty code and their corrections, demonstrating the proper use of abstract classes and interfaces. Additionally, it discusses the purpose and characteristics of both constructs, along with examples of their implementation.

Uploaded by

Stu udy
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

Abstract Classes and

Interfaces in java
💡 Abstract Classes in Java
✅ Key Points:
1. An abstract class is one that can (but doesn’t have to) contain abstract
methods.
To create an abstract class, use the abstract keyword:

abstract class ClassName {


// class members
}

📝 Tip: An abstract class can also have variables, concrete


methods, and constructors.

2. An abstract method has only the prototype (no body). To define one:

abstract return-type method-name(parameter-list);

3. You cannot create an object of an abstract class, but you can create
reference variables.

4. A subclass of an abstract class must implement all abstract methods, or it


must itself be declared abstract.

5. Runtime polymorphism is achieved when a reference of an abstract class


refers to a subclass object. Method invocation is resolved using dynamic
method dispatch.

Abstract Classes and Interfaces in java 1


We Activity – Identify and Fix Errors
❌ Faulty Code:
class A {
abstract void show();

void foo() {
[Link]("Inside foo of class A");
}

class B extends A {
void fun() {
}
}

class C extends A {
void show() {
[Link]("Inside show of class C");
}

void tez() {
[Link]("Inside tez of class C");
}

public static void main(String... args) {


A a = new A();
A temp;
temp = new C();
[Link]();
}
}

Abstract Classes and Interfaces in java 2


✅ Corrected Code:
abstract class A {
abstract void show();

void foo() {
[Link]("Inside foo of class A");
}
}

// Either implement 'show()' or declare B as abstract


abstract class B extends A {
void fun() {
[Link]("Inside foo of class B");
}
}

class C extends A {
@Override
void show() {
[Link]("Inside show of class C");
}

void tez() {
[Link]("Inside tez of class C");
}

public static void main(String... args) {



// A a = new A(); // Cannot instantiate abstract class
A temp;
temp = new C();
[Link](); // ✔️ Dynamic method dispatch
}
}

Abstract Classes and Interfaces in java 3


🧪 Abstract Class Example – Shape

[Link] (Abstract Superclass)

abstract class Shape {


private double dimOne;
private double dimTwo;

Shape(double dimOne, double dimTwo) {


[Link] = dimOne;
[Link] = dimTwo;
}

public double getDimOne()


return dimOne;
}

public void setDimOne(double dimOne) {


[Link] = dimOne;
}

public double getDimTwo() {


return dimTwo;
}

public void setDimTwo(double dimTwo) {


[Link] = dimTwo;
}

abstract double area();


abstract double perimeter();
}

Abstract Classes and Interfaces in java 4


[Link] (Concrete Subclass)

public class Triangle extends Shape {


// dimOne = base, dimTwo = height
public Triangle(double dimOne, double dimTwo) {
super(dimOne, dimTwo);
}

@Override
double area() {
return 0.5 * getDimOne() * getDimTwo();
}

@Override
double perimeter() {
double hypotenuse = [Link]([Link](getDimOne(), 2) + [Link](g
etDimTwo(), 2));
double triPeri = [Link]((getDimOne() + getDimTwo() + hypotenuse)
* 100) / 100.0;
return triPeri
}
}

[Link] (Concrete Subclass)

public class Rhombus extends Shape {


// dimOne = diagonal-1, dimTwo = diagonal-2
public Rhombus(double dimOne, double dimTwo) {
super(dimOne, dimTwo);
}

Abstract Classes and Interfaces in java 5


@Override
double area() {
return 0.5 * getDimOne() * getDimTwo();
}

@Override
double perimeter() {
double halfDiag1 = getDimOne() / 2;
double halfDiag2 = getDimTwo() / 2;
double side = [Link]([Link]([Link](halfDiag1, 2) + [Link]
(halfDiag2, 2)) * 100) / 100.0;
return 4 * si
}
}

[Link] (Driver Class)

public class AbstractTester {


public static void main(String[] args) {
Shape shape;

shape = new Triangle(7, 49);


[Link]("The area of triangle is " + [Link]());
[Link]("The perimeter of triangle is " + [Link]());
[Link]();

shape = new Rhombus(6, 8);


[Link]("The area of rhombus is " + [Link]());
[Link]("The perimeter of rhombus is " + [Link]());
}

Abstract Classes and Interfaces in java 6


}

✅ Output:
The area of triangle is 171.5
The perimeter of triangle is 105.5

The area of rhombus is 24.0


The perimeter of rhombus is 20.0

🆚ClassDifference Between Abstract Class and Concrete


Feature Abstract Class Concrete Class

Method May have abstract (non-implemented) All methods fully


Implementation methods implemented

Instantiation ❌ Cannot be instantiated ✅ Can be instantiated


Use of final keyword ❌ Cannot be final ✅ Can be final

To provide a base for other classes to


Purpose To be used directly
extend

Subclass
✅ Must be subclassed to use ❌ No subclassing
Requirement required

🧠 Interfaces in Java
✅ Key Points:
Abstract Classes and Interfaces in java 7
An interface defines a generic template which can be implemented by related
or unrelated classes.

All methods in an interface are abstract by default, so you don’t need to write
the abstract keyword.

All variables are public, static, and final — they must be assigned values.

🚫 No instance variables or constructors allowed in


interfaces.

To declare an interface:

[access-modifier] interface InterfaceName {


// constants and abstract methods
}

All methods are public even if not declared so. Therefore, while
implementing, you must use public (because Java doesn’t allow reducing
access during method overriding).

Use the implements keyword to implement one or more interfaces:

[access-modifier] class ClassName [extends SuperClass] implements Inte


rface1, Interface2 {
// class body
}

If the class doesn’t implement all methods, it must be declared abstract .

You can create reference variables of interfaces, but cannot instantiate an


interface.

Abstract Classes and Interfaces in java 8


Dynamic Method Dispatch is used when calling overridden methods using
interface references.

Interfaces represent "is-a" relationship and support total abstraction.

❌ We Activity — Identify and Fix Errors


🔻 Problematic Code:
interface A {
float a = 5.7f;
void show();
}
class B implements A {
void get() {
[Link]("inside get");
a = 5.8f;
}
}

class C implements A {
void show() {
[Link]("inside show");
}

void foo() {
[Link]("inside foo");
}
}

class Demo {
public static void main(String args[]) {
A a = new A();
A a1 = new C();
[Link]();
[Link]();

Abstract Classes and Interfaces in java 9


C c1 = new C();
[Link]();
}
}

✅ Corrected Code:
interface A {
float a = 5.7f;
void show();
}

// Either implement 'show()' or make class abstract


abstract class B implements A {
void get() {
[Link]("inside get");
// a = 5.8f; ❌
Error: 'a' is final, cannot be reassigned
}
}

publi class C implements A {


// Must use public when implementing interface methods
public void show() {
[Link]("inside show");
}

void foo() {
[Link]("inside foo");
}
}

class Demo {
public static void main(String args[]) {

Abstract Classes and Interfaces in java 10


// A a = new A(); ❌ Cannot create object of interface
A a1 = new C();
[Link]();
// [Link](); ❌ Cannot call class-specific methods using interface referen
ce

C c1 = new C();
[Link](); // OK ✅
}
}

✅ Interface Example – Mensuration


[Link] (Interface)

public interface Mensuration {


double PI = 3.14;

public double getVolume();


public double getSurfaceArea();
}

[Link] (Implementation Class)

public class Sphere implements Mensuration {


private double radius;

public Sphere(double radius) {


[Link] = radius;
}

Abstract Classes and Interfaces in java 11


@Override
public double getVolume() {
double volume = 4.0 / 3.0 * PI * [Link](radius, 3);
return [Link](volume * 100) / 100.0;
}

@Override
public double getSurfaceArea() {
double surfaceArea = 4 * PI * [Link](radius, 2);
return [Link](surfaceArea * 100) / 100.0;
}
}

[Link] (Implementation Class)

public class Cone implements Mensuration {


private double radius;
private double height;
private double slantHeight;

public Cone(double radius, double height) {


[Link] = radius;
[Link] = height;
[Link] = [Link]([Link](radius, 2) + [Link](height, 2));
}

@Override
public double getVolume() {
double volume = 1.0 / 3.0 * PI * [Link](radius, 2) * height;
return [Link](volume * 100) / 100.0;
}

@Override
public double getSurfaceArea() {

Abstract Classes and Interfaces in java 12


double surfaceArea = PI * radius * (radius + slantHeight);
return [Link](surfaceArea * 100) / 100.0;
}
}

[Link] (Driver Class)

public class MensurationDemo {


public static void main(String[] args) {
Mensuration m = null;

m = new Sphere(7.0);
[Link]("The surface area of sphere is " + [Link]
());
[Link]("The volume of sphere is " + [Link]());

m = new Cone(5.0, 12.0);


[Link]("The surface area of cone is " + [Link]());
[Link]("The volume of cone is " + [Link]());
}
}

🖨️ Output:
The surface area of sphere is 615.44
The volume of sphere is 1436.03
The surface area of cone is 282.6
The volume of cone is 314.0

Abstract Classes and Interfaces in java 13


Difference Between Abstract Class and Interface in
Java
Aspect Abstract Class Interface

Can have instance variables Cannot have instance variables or


Variables
and constructors constructors

Does not support multiple


Inheritance Supports multiple inheritance
inheritance

All methods (static and non- Static methods are not inherited by
Method
static) are inherited by implementing classes; they must be
Inheritance
subclasses accessed using the interface name

You can use any access


Access
modifier ( private , protected , All methods are public by default
Modifiers
public )

Used for creating a common


Used to define a common contract for
Purpose base implementation for
both related and unrelated classes
derived classes

Typically used for related Can be used for related or unrelated


Coupling &
classes → leads to high classes → leads to high cohesion,
Cohesion
cohesion, tight coupling loose coupling

Abstract Classes and Interfaces in java 14

Common questions

Powered by AI

The inability to instantiate an abstract class in Java necessitates that such classes can only be used as superclasses. This design decision enforces a clear separation between abstract concepts and their concrete implementations, promoting a structured approach to extending functionality through subclasses. It encourages developers to think in terms of abstractions for common behaviors and provides a mechanism for polymorphism and code reusability in software systems as developers create specific instances of subclasses that implement the abstract class methods .

Allowing a Java class to implement multiple interfaces provides significant advantages, such as enabling a class to inherit varied behaviors from multiple sources, thus supporting code modularity and reusability. It facilitates flexible design patterns, such as the use of mix-ins for adding functionality without altering class hierarchies. However, potential drawbacks include increased complexity in system design, where too many interface implementations can lead to a tangled web of dependencies that are difficult to manage and maintain. Additionally, conflicting interface methods may lead to ambiguous implementations .

In Java, method overriding in concrete subclasses of abstract classes is handled by allowing subclasses to provide specific implementations for abstract methods defined in their abstract superclasses. This mechanism enables polymorphism, as objects can be treated as instances of their superclass, and the overridden method in the subclass is executed. The benefit of this design is that it provides flexibility and extensibility in code, allowing the introduction of subclasses that provide unique functionalities while adhering to the superclass’s contract .

Dynamic method dispatch in Java allows a method to be overridden in a subclass, such that the version of the method executed is determined at runtime. This supports runtime polymorphism by enabling a reference of an abstract class to point to a subclass object, and the appropriate method implementation is called using this object. For instance, when a method is invoked on a superclass reference that is pointing to a subclass object, Java considers the type of the actual object being referred to, not the reference type, thus determining which overridden method to execute .

Java’s restriction that interface variables are public, static, and final enhances both software security and design principles. From a security standpoint, it prevents unauthorized modification of interface constants, protecting the integrity of shared values across operations reliant on those constants. From a design perspective, it enforces immutability and ensures that constants in interfaces cannot introduce instance-specific data or state inconsistencies across implementations, promoting robustness and reliability in the system architecture .

Abstract classes in Java provide a common base implementation that can include both abstract methods and fields which can have state (instance variables). They are intended for related classes with a shared implementation and lead to high cohesion and tight coupling. In contrast, interfaces define a contract with abstract methods, do not hold any state, support multiple inheritance, and are meant to provide a common template for classes, related or unrelated, which leads to loose coupling. Interfaces cannot have constructors or instance variables, emphasizing the enforcement of method contracts without providing any default behavior .

Runtime polymorphism in Java using abstract classes involves method calls being resolved at runtime rather than compile time, relying on the object's actual class rather than the reference type. In the context of the Shape and Triangle classes, a reference of type Shape can point to a Triangle object. When a method like area() is invoked using this reference, the overridden version in Triangle is executed. For example, if `Shape shape = new Triangle(7, 49);` is instantiated, the call `shape.area()` executes the Triangle class’s implementation of the area method, demonstrating runtime polymorphism .

In Java, interfaces provide a mechanism for achieving high cohesion and loose coupling. High cohesion is achieved as interfaces allow related functionalities to be bundled as contracts which implementing classes must adhere to, ensuring consistency in design. Loose coupling is facilitated because interfaces enable classes to interact through specified methods without needing internal details, thus reducing dependencies. This separation allows changes in one part without impacting others, fostered by the principle of programming to an interface rather than an implementation .

When a class extends an abstract class in Java, it must implement all its abstract methods; otherwise, the subclass itself must be declared abstract. This enforcement ensures that any class which is not abstract implements the complete functionality defined by its superclass, maintaining the integrity and contract of the abstract class. If a subclass doesn’t implement all inherited abstract methods, compiling the subclass will result in a compilation error unless the class is also abstract .

In Java, all methods declared in an interface are implicitly public, even if not specified explicitly. This is significant because it ensures that any class implementing the interface does not reduce the visibility of the method from the contract defined by the interface. Maintaining public visibility is essential to adhere to the interface’s promise that the methods are available for invocation by any implementing class's clients .

You might also like