Master Core Java Concepts!
Subscribe to Ram N Java for clear explanations, practical code examples, and essential Java tutorials!
Subscribe Now on YouTubeRelationship Between Classes and Interfaces in Java
In Java object-oriented programming, understanding how classes and interfaces connect to one another is essential. The two key keywords that establish these connections are extends and implements.
Depending on whether you are connecting two classes, two interfaces, or a class to an interface, Java defines specific rules on which keyword you must use.
The Three Core Relationships
- A Class
extendsAnother Class: A child class inherits state and behavior from a single parent class using theextendskeyword (Java supports single class inheritance). - An Interface
extendsAnother Interface: An interface can inherit abstract methods and constants from another interface using theextendskeyword. An interface can even extend multiple interfaces simultaneously. - A Class
implementsan Interface: When a class adopts the contract defined by an interface, it uses theimplementskeyword and must provide concrete implementations for the interface's abstract methods.
Code Example: Showing the Relationships
// 1. Interface extends Interface
interface Animal {
void eat();
}
interface Pet extends Animal {
void play();
}
// 2. Class extends Class and implements Interface
class LivingBeing {
void breathe() {
System.out.println("Breathing...");
}
}
class Dog extends LivingBeing implements Pet {
public void eat() {
System.out.println("Dog eats food");
}
public void play() {
System.out.println("Dog plays fetch");
}
}
interface Animal {
void eat();
}
interface Pet extends Animal {
void play();
}
// 2. Class extends Class and implements Interface
class LivingBeing {
void breathe() {
System.out.println("Breathing...");
}
}
class Dog extends LivingBeing implements Pet {
public void eat() {
System.out.println("Dog eats food");
}
public void play() {
System.out.println("Dog plays fetch");
}
}
Summary Quick Reference
- Class to Class: Use
extends - Interface to Interface: Use
extends - Class to Interface: Use
implements
I adore the tutorial, however It would have been even better if you had drawn those relationships in a creately like software in the video.
ReplyDelete