DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Enterprise AI Trend Report: Gain insights on ethical AI, MLOps, generative AI, large language models, and much more.

2024 Cloud survey: Share your insights on microservices, containers, K8s, CI/CD, and DevOps (+ enter a $750 raffle!) for our Trend Reports.

PostgreSQL: Learn about the open-source RDBMS' advanced capabilities, core components, common commands and functions, and general DBA tasks.

AI Automation Essentials. Check out the latest Refcard on all things AI automation, including model training, data security, and more.

Related

  • Achieving Inheritance in NoSQL Databases With Java Using Eclipse JNoSQL
  • Advanced Brain-Computer Interfaces With Java
  • Simplify Java: Reducing Unnecessary Layers and Interfaces [Video]
  • Java 21 SequenceCollection: Unleash the Power of Ordered Collections

Trending

  • Organizing Knowledge With Knowledge Graphs: Industry Trends
  • Getting Started With NCache Java Edition (Using Docker)
  • Being a Backend Developer Today Feels Harder Than 20 Years Ago
  • Modern Digital Authentication Protocols
  1. DZone
  2. Coding
  3. Java
  4. Multiple Inheritance in Java

Multiple Inheritance in Java

Learn more about multiple inheritance and the use of default interface methods in multiple inheritance.

By 
Greg Hall user avatar
Greg Hall
·
Feb. 21, 22 · Code Snippet
Like (3)
Save
Tweet
Share
4.5K Views

Join the DZone community and get the full member experience.

Join For Free

Ever since Java 8 introduced default interface methods, I felt there had to be a way to use it for multiple inheritance. I have never needed it, but I was bored for a bit today, so decided to try the following idea:

  • Create a non-public class XData to hold the fields the interface needs to work with, and a public interface X in the same X.java source file
  • The interface has one virtual method getXData() that returns the XData instance
  • The remaining interface methods are default methods that call getXData() to read and write the fields as necessary to perform some useful operations.
  • Create another interface Y and class YDatain the same pattern
  • Create a class XY that implements both interfaces X and Y
  • The class XY has XData and YData fields, which are returned by getXData() and getYData(). These are the only two interface methods XY is required to implement.
  • I didn't bother in my example, but XY would have to decide how to implement the Object methods hashCode, equals, and toString. These methods cannot be implemented by interfaces (but they could be implemented in XData and YData classes if desired)

The end result is the XY class is an instance of both X and Y interfaces, and inherits the encapsulated behaviors of both X and Y default methods - multiple inheritance by any reasonable measure.

It is better than C++ multiple inheritance, in that all constructor logic and declared fields are in the XY class. The only problem you could get is if X and Y interfaces declare the same method that differs only by return type - but this is just a general problem of implementing multiple interfaces.

Here are some code examples using Dogand Cow interfaces.
Dog.java:

Java
 
package mi;

import static java.time.temporal.ChronoField.DAY_OF_MONTH;
import static java.time.temporal.ChronoField.HOUR_OF_DAY;
import static java.time.temporal.ChronoField.MINUTE_OF_DAY;
import static java.time.temporal.ChronoField.MONTH_OF_YEAR;
import static java.time.temporal.ChronoField.NANO_OF_SECOND;
import static java.time.temporal.ChronoField.SECOND_OF_MINUTE;
import static java.time.temporal.ChronoField.YEAR;

import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;

/**
 * The fields of data that Foo needs to operate on
 */
class DogData {
	final String breed;
	final String name;
	final OffsetDateTime birthDate;

	DogData(String breed, String name, OffsetDateTime birthDate) {
		this.breed = breed;
		this.name = name;
		this.birthDate = birthDate;
	}
}

public interface Dog {
	/**
	 * The method the class has to implement to return a DogData instance, from one its own fields.
	 * 
	 * @return dog data
	 */
	DogData getDogData();
	
	/**
	 * Return the next time the dog should go to the vet for a checkup,
	 * which is annually, one week after the dog's birthday.
	 * 
	 * @return date of next checkup.
	 */
	default OffsetDateTime nextCheckup() {
		final OffsetDateTime now = OffsetDateTime.now();
		
		final OffsetDateTime today = now.
			minusHours(now.get(HOUR_OF_DAY)).
			minusMinutes(now.get(MINUTE_OF_DAY)).
			minusSeconds(now.get(SECOND_OF_MINUTE)).
			minusSeconds(now.get(NANO_OF_SECOND));
		
		final OffsetDateTime bday = getDogData().birthDate;
		final int thisYear = now.get(YEAR);
		final int bdayMonth = bday.get(MONTH_OF_YEAR);
		final int bdayDay = bday.get(DAY_OF_MONTH);
		
		OffsetDateTime nextCheckup = OffsetDateTime.
			of(thisYear, bdayMonth, bdayDay, 12, 0, 0, 0, ZoneOffset.UTC).
			plusDays(7);

		if (nextCheckup.isBefore(today)) {
			nextCheckup = nextCheckup.plusYears(1);
		}
		
		return nextCheckup;
	}
	
	default String getBreed() {
		return getDogData().breed;
	}
	
	default String getName() {
		return getDogData().name;
	}
	
	default OffsetDateTime getBirthDate() {
		return getDogData().birthDate;
	}
}

Cow.java:

Java
 
package mi;

import static java.time.temporal.ChronoField.DAY_OF_MONTH;
import static java.time.temporal.ChronoField.HOUR_OF_DAY;
import static java.time.temporal.ChronoField.MINUTE_OF_HOUR;
import static java.time.temporal.ChronoField.MONTH_OF_YEAR;
import static java.time.temporal.ChronoField.NANO_OF_SECOND;
import static java.time.temporal.ChronoField.SECOND_OF_MINUTE;
import static java.time.temporal.ChronoField.YEAR;

import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;

class CowData {
	String breed;
	OffsetDateTime birthDate;

	CowData(String breed, OffsetDateTime birthDate) {
		this.breed = breed;
		this.birthDate = birthDate;
	}
}

public interface Cow {
	/**
	 * The method the class has to implement to return a CowData instance, from one its own fields.
	 * 
	 * @return cow data
	 */
	CowData getCowData();
	
	/**
	 * Return the next time the cow should go to the vet for a shot,
	 * which is annually, one week before the cow's birthday.
	 * 
	 * @return date of next checkup.
	 */
	default OffsetDateTime nextCheckup() {
		final OffsetDateTime now = OffsetDateTime.now();
		
		final OffsetDateTime today = now.
			minusHours(now.get(HOUR_OF_DAY)).
			minusMinutes(now.get(MINUTE_OF_HOUR)).
			minusSeconds(now.get(SECOND_OF_MINUTE)).
			minusNanos(now.get(NANO_OF_SECOND));
		
		final OffsetDateTime bday = getCowData().birthDate;
		final int thisYear = now.get(YEAR);
		final int bdayMonth = bday.get(MONTH_OF_YEAR);
		final int bdayDay = bday.get(DAY_OF_MONTH);
		
		OffsetDateTime nextCheckup = OffsetDateTime.
			of(thisYear, bdayMonth, bdayDay, 12, 0, 0, 0, ZoneOffset.UTC).
			minusDays(7);
		
		if (nextCheckup.isBefore(today)) {
			nextCheckup = nextCheckup.plusYears(1);
		}
		
		return nextCheckup;
	}
	
	default String getBreed() {
		return getCowData().breed;
	}
	
	default OffsetDateTime getBirthDate() {
		return getCowData().birthDate;
	}
}

DogCow.java:

Java
 
package mi;

import static java.time.temporal.ChronoField.YEAR;

import java.time.OffsetDateTime;
import java.time.ZoneOffset;

public class DogCow implements Dog, Cow {
	private final OffsetDateTime dogCowBdate = OffsetDateTime.of(
		OffsetDateTime.now().get(YEAR) - (int)(Math.random() * 5),
		(int)(Math.random() * 12) + 1,
		(int)(Math.random() * 28) + 1,
		(int)(Math.random() * 24),
		(int)(Math.random() * 60),
		0,
		0,
		ZoneOffset.UTC
	);
	
	private final DogData dogData = new DogData(
		"Border Collie",
		"Nate",
		dogCowBdate
	);
	
	private final CowData cowData = new CowData(
		"Angus",
		dogCowBdate
	);
	
	@Override
	public DogData getDogData() {
		return dogData;
	}
	
	@Override
	public CowData getCowData() {
		return cowData;
	}
	
	@Override
	public OffsetDateTime nextCheckup() {
		// Check both Dog and Cow, choose whichever one comes first
		final OffsetDateTime nextDogCheckup = Dog.super.nextCheckup();
		final OffsetDateTime nextCowCheckup = Cow.super.nextCheckup();
		
		return nextDogCheckup.isBefore(nextCowCheckup) ? nextDogCheckup : nextCowCheckup;
	}
	
	@Override
	public String getBreed() {
		return Dog.super.getBreed() + " " + Cow.super.getBreed();
	}
	
	@Override
	public OffsetDateTime getBirthDate() {
		return Dog.super.getBirthDate();
	}
}

Main.java:

Java
 
package mi;

public class Main {
	public static void main(String[] args) {
		for (int i = 1; i < 10; i++) {
			final DogCow dc = new DogCow();
			
			System.out.println(
				"DogCow " + i +
				" is combined breed " +
				dc.getBreed() +
				" named " +
				dc.getName() +
				" born on " +
				dc.getBirthDate() +
				" with next checkup of " +
				dc.nextCheckup()
			);
		}
	}
}

Example Main.java output:

 
DogCow 1 is combined breed Border Collie Angus named Nate born on 2022-11-22T21:40Z with next checkup of 2022-11-15T12:00Z
DogCow 2 is combined breed Border Collie Angus named Nate born on 2018-09-22T01:53Z with next checkup of 2022-09-15T12:00Z
DogCow 3 is combined breed Border Collie Angus named Nate born on 2022-01-26T18:08Z with next checkup of 2022-02-02T12:00Z
DogCow 4 is combined breed Border Collie Angus named Nate born on 2022-02-23T00:32Z with next checkup of 2022-03-02T12:00Z
DogCow 5 is combined breed Border Collie Angus named Nate born on 2019-03-27T04:24Z with next checkup of 2022-03-20T12:00Z
DogCow 6 is combined breed Border Collie Angus named Nate born on 2022-02-04T19:11Z with next checkup of 2022-02-11T12:00Z
DogCow 7 is combined breed Border Collie Angus named Nate born on 2020-02-20T17:13Z with next checkup of 2022-02-27T12:00Z
DogCow 8 is combined breed Border Collie Angus named Nate born on 2018-09-02T18:02Z with next checkup of 2022-08-26T12:00Z
DogCow 9 is combined breed Border Collie Angus named Nate born on 2018-01-07T21:02Z with next checkup of 2022-01-14T12:00Z

See the Java code

Java (programming language) Inheritance (object-oriented programming) Interface (computing)

Published at DZone with permission of Greg Hall. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Achieving Inheritance in NoSQL Databases With Java Using Eclipse JNoSQL
  • Advanced Brain-Computer Interfaces With Java
  • Simplify Java: Reducing Unnecessary Layers and Interfaces [Video]
  • Java 21 SequenceCollection: Unleash the Power of Ordered Collections

Partner Resources


Comments

ABOUT US

  • About DZone
  • Send feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: