0% found this document useful (0 votes)
23 views7 pages

Java Class and Interface Inheritance Example

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)
23 views7 pages

Java Class and Interface Inheritance Example

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

Class – XII

COMPUTER SCIENCE
** Inheritance & Interface **
Q1: Define Interface.
Ans: Interface in Java is defined as an abstract type used to specify the behaviour of a class.
A Java interface contains static constants and abstract methods.

Key Properties of Interface:


 The interface in Java is a mechanism to achieve abstraction.
 By default, variables in an interface are public, static and final.
 It is used to achieve abstraction and multiple inheritance in Java.
 It supports loose coupling (classes depend on behavior, not implementation).
 In other words, interfaces primarily define methods that other classes must implement.

JAVA PROGRAM: Example 1:


interface Test
{
// public, static and final
final int a = 10;

// public and abstract


void display();
}

// Class implementing interface


class Demo implements Test
{
// Implementing the capabilities of Interface
public void display()
{ OUTPUT:
[Link]("Hello!");
} Hello!
} 10
class Run_Interface
{
public static void main(String[] args)
{
Demo t = new Demo();
[Link]();
[Link](t.a);
}
}
Relationship between Class and Interface
 A class can extend another class and similarly, an interface can extend another interface.
However, only a class can implement an interface and the reverse (an interface
implementing a class) is not allowed.

 Java does not support multiple inheritance with classes to avoid ambiguity, but it
supports multiple inheritance using interfaces.

Example 2: This example demonstrates how a class can implement multiple interfaces
(Add and Sub) to provide functionality for both addition and subtraction operations.

// Add interface
interface Add
{
int add(int a,int b);
}
// Sub interface
interface Sub
{
int sub(int a,int b);
}
// Calculator class implementing Add and Sub
class Cal implements Add , Sub
{
// Method to add two numbers
public int add(int a,int b)
{
return a+b;
}
// Method to sub two numbers
public int sub(int a,int b)
{
return a-b;
}
}

class Operation
{
public static void main (String[] args)
{
// instance of Cal class
Cal x = new Cal();
[Link]("Addition : " + [Link](10,20));
[Link]("Substraction : " + [Link](20,15));

}
}
 Interface can now include private methods.
 Private methods are defined within the interface but it cannot be accessed by the
implementing classes.
 Private methods cannot be overridden by implementing classes as they are not inherited.

Difference between Class and Interface


Although Class and Interface seem the same there are certain differences between Classes and
Interface. The major differences between a class and an interface are mentioned below:
Features Class Interface

Instantiation In class, you can create an object. In an interface, you can't create an object

Variables Class can have instance variables Variables are public static final (constants only).

Methods Class can have concrete methods In an interface, methods are abstract by default

Inheritance It supports single inheritance Supports multiple inheritance

Constructors Can have constructors. No constructors allowed.

Supports private, protected, In an interface, all members are public by


Access Modifiers public, default. default

Keyword Defined using class. Defined using interface.

It does not support default


It supports default methods(JDK 8+)
Default Methods methods

Static Methods Can have static methods. Supports static methods (JDK 8+)

Private Methods Can have private methods. Supports private methods (JDK 9+).

Can have main() (since JDK 8, as static methods


Can have main() for execution.
Main Method are allowed).

What is Abstract Class in Java?


Java abstract class is a class that cannot be instantiated by itself, it needs to be sub classed by
another class to use its properties. An abstract class is declared using the "abstract" keyword in
its class definition.

In Java, the following some important observations about abstract classes are as follows:
1. An instance of an abstract class cannot be created.
2. Constructors are allowed.
3. We can have an abstract class without any abstract method.
4. There can be a final method in abstract class but any abstract method in class(abstract
class) cannot be declared as final or in simpler terms final method cannot be abstract
itself as it will yield an error: "Illegal combination of modifiers: abstract and final"
5. We can define static methods in an abstract class
6. We can use the abstract keyword for declaring top-level classes (Outer class) as well
as inner classes as abstract
7. If a class contains at least one abstract method then compulsory should declare a class
as abstract
8. If the Child class is unable to provide implementation to all abstract methods of
the Parent class then we should declare that Child class as abstract so that the next
level Child class should provide implementation to the remaining abstract method
Difference between abstract class & interface:

Feature Abstract Class Interface

Methods Abstract and concrete methods Primarily abstract (before Java 8), can have
default/static methods

Fields Instance variables with various Only public, static, final fields
access modifiers

Constructors Yes No

Inheritance Single inheritance (extend) Multiple inheritance (implement)

Purpose Share common functionality among Define a contract for unrelated classes
related classes

Example 3:
Write a program to display the method print the addition and subtraction by using
abstraction.
// Abstract Class
abstract class arithmetic_operation
{
abstract void printInfo();
}
// Class add
class add extends arithmetic_operation
{
void printInfo()
{
int a = 3;
int b = 4;
[Link](a + b);
}
}
// Class sub
class sub extends arithmetic_operation
{
void printInfo()
{
int c = 4;
int d = 5;
[Link](c - d);
}
}
class abstraction
{
public static void main(String args[])
{
arithmetic_operation n = new add();
[Link]();
arithmetic_operation y = new sub();
[Link]();
}
} ASSIGNMENT – 8
Question 1

An interface Data is defined with a data member and a method volume( ) which returns the
volume of the implementing shape.
A super class Base has been defined to contain the radius of a geometrical shape.
Define a sub class CalVol which uses the properties of the interface Data and the class Base
and calculates the volume of a cylinder.
The details of the members of the interface and both the classes are given below: [5]

Interface name : Data


Data member:
double pi : initialize pi = 3.142

Member functions/methods:
double volume( ) :

Class name: Base


Data member/instance variable:
rad : to store the radius in decimal

Member functions/methods:
Base(...) : parameterized constructor to initialize the data member
void show( ) : displays the radius with an appropriate message

Class name: CalVol


Data member/instance variable:
ht : to store the height in decimal
Member functions/methods:
CalVol(...) : parameterized constructor to initialize the data members of both the classes
double volume( ) : calculates the volume of a sphere by using the formula:
( pi x radius2 x height )
void show( ) : displays the data members of both the classes and the volume of the sphere
with appropriate message

Assume that the interface Data and the super class Base has been defined. Using the
concept of inheritance, specify the class CalVol giving the details of the constructor(...),
double volume( ) and void show( ).

The interface, super class, main function, and algorithm need NOT be written.

Question 2

A super class Bank has been defined to store the details of the customer in a bank.
Define a subclass Interest to calculate the compound interest.

The details of the members of both the classes are given below:

Class name : Bank


Data members/instance variables:
name : to store the name of the customer
acc_no : integer to store the account number
principal : to store the principal amount in decimals

Methods / Member functions:

Bank( ... ) : parameterized constructor to assign values to the data members


void display( ) : to display the customer details

Class name Interest


Data members/instance variables:
rate : to store the interest rate in decimals
time : to store the time period in decimals

Methods / Member functions:


Interest( ... ) : parameterized constructor to assign values to the data members of both the
classes

double calculate( ) : to calculate and return the compound interest using the formula
[ CI = P ( 1 + R/100 )N − P]
where, P is the principal, R is the rate and N is the time

void display( ) : to display the customer details along with the compound interest
Assume that the super class Bank has been defined. Using the concept of inheritance,
specify the class Interest giving the details of the constructor(...), double calculate( ) and
void display( ).

The super class, main function and algorithm need NOT be written.

Common questions

Powered by AI

In Java, a class can implement an interface, which means the class provides concrete implementations for all the methods declared in the interface. This enforces a contract that the class must adhere to, ensuring certain functionalities are implemented. While classes can only extend one other class due to single inheritance, they can implement multiple interfaces, allowing for multiple inheritance in a different form. On the other hand, interfaces can extend other interfaces, promoting a tiered and flexible inheritance model .

Interfaces in Java serve as a mechanism to achieve abstraction by allowing the specification of methods that a class must implement without dictating how these methods should be executed. This is useful for defining a common protocol that can be implemented by unrelated classes. Additionally, interfaces support multiple inheritance, enabling a class to implement more than one interface, thereby promoting loose coupling where classes depend on certain behaviors rather than specific implementations .

Abstract classes and interfaces both define 'contracts' within Java OOP, but they do so differently. Interfaces express strict contracts by declaring methods without implementations that must be provided by any implementing class. This enforces a consistent API across disparate classes. Abstract classes, on the other hand, allow sharing of both implemented and unimplemented behaviors, enabling code reuse and the establishment of a common base while still mandating subclasses provide specifics for abstract methods. They articulate a more flexible contract compared to interfaces .

Variables declared in a Java interface are inherently public, static, and final, meaning they act as constants and cannot be modified. In contrast, classes can have instance variables that may be non-static and non-final, providing more flexibility in variable usage and state management within the object's lifecycle. This stark difference highlights how interfaces are designed to define constants and methods without carrying the state .

In Java, abstract classes can have constructors that are used to initialize common fields and perform setup required for the class. However, interfaces do not have constructors because they cannot be instantiated directly and serve only as a type declaration and a contract for the implementing classes. This difference reflects the essential roles: abstract classes are meant to be partially implemented whereas interfaces provide full abstraction .

Java does not support multiple inheritance through classes to avoid complexity and conflicts, such as the diamond problem, which arises from inheriting multiple features from more than one superclass. Instead, Java supports multiple inheritance via interfaces, allowing a class to implement multiple interfaces. This method does not involve inheriting method implementations, thus avoiding ambiguity. It promotes the separation of concerns by allowing classes to be structured around different interfaces that represent distinct sets of capabilities or behaviors .

Both abstract classes and interfaces can define static and default methods, but there are differences in how they do so. Abstract classes have always been able to contain static methods, while interfaces were first allowed static methods starting in JDK 8. An abstract class can have instance methods (concrete methods), whereas interfaces can only provide default methods (also starting in JDK 8) which require no instantiation. The default methods in interfaces allow for extended flexibility and backward compatibility without enforcing changes across all implementing classes .

Compound interest is the interest on a loan or deposit calculated based on both the initial principal and the accumulated interest from previous periods. In the 'Interest' subclass, which inherits from the 'Bank' superclass, compound interest is calculated using the formula: CI = P (1 + R/100)^N - P, where P is the principal amount, R is the rate of interest, and N is the number of time periods. The 'Interest' class capitalizes on inheritance by building on the data provided in the 'Bank' superclass, effectively showcasing how inherited properties and methods can be extended to facilitate complex calculations .

Private methods in Java interfaces, introduced in JDK 9, are used to encapsulate common code shared by default and static methods within the interface, promoting code reuse and reducing redundancy. These methods cannot be accessed by implementing classes, thereby maintaining encapsulation. This capability enhances the interface's functionality by organizing helper methods internally without exposing them as part of the interface's public API .

The 'CalVol' class exemplifies the combined use of interfaces and inheritance by utilizing the interface 'Data' to implement a method that computes the volume, and extending the superclass 'Base' to inherit the radius property. This design allows 'CalVol' to effectively handle specific calculations (volume of a cylinder, in this case) while adhering to the expected behavior outlined in the interface. This approach showcases polymorphism where common functionalities (like volume computation) are shared and specialized in different contexts .

You might also like