Monday, 1 February 2016

Java Tutorial : Relationship between classes and interfaces

Master Core Java Concepts!

Subscribe to Ram N Java for clear explanations, practical code examples, and essential Java tutorials!

Subscribe Now on YouTube

Relationship 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

  1. A Class extends Another Class: A child class inherits state and behavior from a single parent class using the extends keyword (Java supports single class inheritance).
  2. An Interface extends Another Interface: An interface can inherit abstract methods and constants from another interface using the extends keyword. An interface can even extend multiple interfaces simultaneously.
  3. A Class implements an Interface: When a class adopts the contract defined by an interface, it uses the implements keyword 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");
  }
}

Summary Quick Reference

  • Class to Class: Use extends
  • Interface to Interface: Use extends
  • Class to Interface: Use implements

Watch More Java Interface Tutorials:

1 comment:

  1. 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

Tutorials