0% found this document useful (0 votes)
13 views5 pages

Understanding Java Interfaces and Usage

The document discusses interfaces in Java. It defines an interface as being like a class that can only contain constants and abstract methods. An interface specifies what a class must do but not how. A class implements an interface using the implements keyword. The document provides an example Vehicle interface and Bicycle and Bike classes that implement it. It discusses how interfaces allow for multiple inheritance in Java and provides an example demonstrating this.
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)
13 views5 pages

Understanding Java Interfaces and Usage

The document discusses interfaces in Java. It defines an interface as being like a class that can only contain constants and abstract methods. An interface specifies what a class must do but not how. A class implements an interface using the implements keyword. The document provides an example Vehicle interface and Bicycle and Bike classes that implement it. It discusses how interfaces allow for multiple inheritance in Java and provides an example demonstrating this.
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

Interface

interface is like a class. The interface keyword is used to declare an [Link] contains only
constants and abstract methods. If you don’t use final keyword default all variables are final and
all methods are abstract. Interfaces specify what a class must do and not how. It is the blueprint
of the class. A class uses the implements keyword to implement an interface. The implements
keyword appears in the class declaration following the extends portion of the declaration.
Syntax
interface interfacename{
final variables;
abstract methods;
}
class classname implements interfacename{
abstract methods(){
-----
}
Other methods
}
Why use Java interface?
There are mainly three reasons to use interface. They are given below.
o It is used to achieve abstraction.
o By interface, we can support the functionality of multiple inheritance.
o It can be used to achieve loose coupling

Example
interface Vehicle {
// all are the abstract methods.
void changeGear(int a);
void speedUp(int a);
void applyBrakes(int a);
}
class Bicycle implements Vehicle{
int speed;
int gear;
// to change gear
public void changeGear(int newGear){
gear = newGear;
}
// to increase speed
public void speedUp(int increment){
speed = speed + increment;
}
// to decrease speed
public void applyBrakes(int decrement){
speed = speed - decrement;
}
public void printStates() {
[Link]("speed: " + speed + " gear: " + gear);
}
}
class Bike implements Vehicle {
int speed;
int gear;
// to change gear
public void changeGear(int newGear){
gear = newGear;
}
// to increase speed
public void speedUp(int increment){
speed = speed + increment;
}
// to decrease speed
public void applyBrakes(int decrement){
speed = speed - decrement;
}
public void printStates() {
[Link]("speed: " + speed + " gear: " + gear);
}
}
public class GFG {
public static void main (String[] args) {
Bicycle bicycle = new Bicycle();
[Link](2);
[Link](3);
[Link](1);
[Link]("Bicycle present state :");
[Link]();
// creating instance of the bike.
Bike bike = new Bike();
[Link](1);
[Link](4);
[Link](3);
[Link]("Bike present state :");
[Link]();
}
}
Output
Bicycle present state :
speed: 2 gear: 2
Bike present state :
speed: 1 gear: 1

Important points
 All interface Methods are implicitly public and abstract. Even if you use keyword it will
not create the problem as you can see in the second Method declaration.
 Interfaces can declare only Constant. Instance variables are not allowed. This means all
variables inside the Interface must be public, static, final. Variables inside Interface
are implicitly public static final.
 Interface Methods cannot be static.
 Interface Methods cannot be final.
 The Interface can extend one or more other Interface. Note: The Interface can only
extend another interface.
Example : interface twowheeler extends Vehicle{
void milage();
}
Multiple Inheritance in java
Multiple inheritance in achieved in java when one of the parent class is made an interface and
another class a normal class.

Example: we have an interface called Exam and a class called student. We have a third class
Result which implements the properties of both the Exam & student class as shown in the
diagram below. Write a code in java to implement the same.

interface Exam {
void Percent_cal();
}
class Student {
String name;
int roll_no, Marks1, Marks2;
Student(String n, int rn, int m1, int m2) {
name = n;
roll_no = rn;
Marks1 = m1;
Marks2 = m2;
}
void show() {
[Link]("Student Name : "+name);
[Link]("Roll no : "+roll_no);
[Link]("Marks1 : "+Marks1);
[Link]("Marks2 : "+Marks2);
}
}
class Result extends Student implements Exam {
float per;
Result(String n,int rn,int m1,int m2) {
super(n,rn,m1,m2);
}
public void Percent_cal() {
int tot = Marks1 + Marks2;
per = (float)tot / 2;
}
void display() {
show();
[Link]("Percentage = "+per);
}
}
public class StudentDetails {
public static void main (String[] args) {
Result r = new Result("Aashish",11,75,95);
r.Percent_cal();
[Link]();
}
}

Difference between abstract class and interface

Difference between extends and implements keyword

When to use extends and implements keyword?

Assignment
1. Difference between abstract class and interface
2. Difference between extends and implements keyword
3. Can we re-assign a value to a field of interfaces?
4. Can a class implement more than one interface? Justify.
5. How can we access an interface from another interface and how to access from a class?
Explain with an example.
6. How many interfaces can a class inherit and can a same interface be inherited by 2
different classes? Explain it?
7. Write a program to demonstrate multiple inheritance. Consider two base classes
worker(int code, char name, float salary), HR who calculates the different allowances like
(float DA, HRA). You have another class manger with calculates (float TA(is 10% of
salary), gross salary) where the properties of worker and HR is used in this class. Write a
test application class to create an array of 10 workers and display their details with gross
salary.

Common questions

Powered by AI

Java enables multiple inheritance through the use of interfaces. A class can implement multiple interfaces, thus inheriting the behavior specified in each interface. This approach allows for combining functionalities from different sources without the complexities associated with multiple inheritance in languages that allow classes to inherit from multiple parent classes directly. It ensures a clear separation of implementation and interface, reducing the risk of ambiguity and conflicts found in traditional multiple inheritance scenarios .

No, it is not possible to re-assign a variable defined in an interface. Variables in interfaces are implicitly public, static, and final, meaning their values are constants and cannot be modified once initialized. This ensures that constants are accessible across classes that implement the interface, preserving data integrity and consistency throughout the application .

In Java, multiple inheritance can be achieved by having a class implement multiple interfaces and optionally extending a class. For example, consider an interface Exam with a method Percent_cal(), and a class Student with attributes name, roll_no, and Marks. By extending Student and implementing Exam, the Result class can achieve multiple inheritance, combining properties and behaviors from both Student (a regular class) and Exam (an interface), thus modeling a comprehensive student results system .

Having all methods in an interface as public and abstract means that they set a clear and consistent contract that any implementing class must fulfill. This design enforces that all implementing classes provide specific method implementations, ensuring uniformity and predictability in behavior across different classes adhering to the same interface. This consistency helps in enforcing clean separation between the interface (what the class should do) and its implementation (how the class does it), thereby supporting maintainable and robust software architectures .

The 'extends' keyword in Java is used for class inheritance, where a subclass inherits from a superclass, or for interface inheritance, where one interface inherits from another. In contrast, 'implements' is used when a class implements an interface. 'Extends' implies a "is-a" relationship, importing existing implementation and attributes of the parent class or interface. 'Implements' signifies a contract where a class agrees to provide concrete implementations for the abstract methods defined in the interface, without necessarily reusing any implementation .

Yes, a single class can implement multiple interfaces in Java. This capability allows for a flexible class design where a class can adopt multiple roles or behaviors as defined by the interfaces. It promotes modularization and a clean separation of concerns, enabling one class to handle diverse functionalities by simply implementing the appropriate interfaces .

Loose coupling through interfaces is especially beneficial in a plugin architecture framework. For example, consider a media player application where new formats and codecs are regularly added. By defining common interfaces for playing, stopping, and encoding media (e.g., IMediaPlayer), the application can easily integrate new plugins for these functions. Each plugin class implements the interfaces, allowing the core framework to interact with them polymorphically. This setup minimizes modifications to the existing codebase when adding new functionalities, thereby easing maintenance and future evolution .

Interfaces in Java serve several key purposes: they allow for abstraction, enable multiple inheritance, and facilitate loose coupling. By defining methods without specifying how they should be implemented, interfaces provide a contract that classes must follow, promoting abstraction. They support multiple inheritance by allowing a class to implement multiple interfaces, overcoming the limitation of single inheritance in Java. Lastly, interfaces promote loose coupling by defining how classes should interact without dictating the implementation details, making the system more modular and easier to maintain .

Abstract classes in Java can have both abstract methods (without implementation) and concrete methods (with implementation), whereas interfaces can only have abstract methods (until Java 8 added default and static methods). You would use an abstract class when you have a base class that should provide some common implementation to be shared among subclasses. An interface, on the other hand, is used when you want to define a contract that multiple classes can implement, without enforcing any common implementation. The choice between the two often depends on whether a shared implementation is beneficial or if a clear separation of contract and implementation should be maintained .

In Java, an interface can extend another interface using the extends keyword. This feature allows for the creation of a hierarchy of interfaces that can inherit behavior specifications from one another. It facilitates the reuse of interface contracts and the development of more complex behaviors by combining simpler ones, thus promoting coherent and scalable designs .

You might also like