Skip to content

Instantly share code, notes, and snippets.

@kpunith8
Last active January 11, 2025 12:13
Show Gist options
  • Save kpunith8/b6fea21ca1ad4263daaf6fa1aea02c37 to your computer and use it in GitHub Desktop.
Save kpunith8/b6fea21ca1ad4263daaf6fa1aea02c37 to your computer and use it in GitHub Desktop.
Java Examples - Tested
// An interface can extend any number of interfaces but a class can extend only one class (multiple inheritance is not
// supported in Java - diamond problem)
// Diamond Problem
// When A and B class have the same method and when the class C extends A, B
// implementing the method name from either of A or B, compiler doesn't from which
// class the method should be overridden or considerd.
interface Vehicle {
void accelerate();
}
// Extend Vehicle interface so that consumers of Vehicle interface doesn't have to implement
// methods specific to IndianVehicle
// Or add default or static methods to existing interface so that consuments don't have to implement them.
// Default methods enable you to add new functionality to existing interfaces and ensure binary
// compatibility with code written for older versions of those interfaces
interface IndianVehicle extends Vehicle {
String manufacurer(String manufacturer);
default String country() {
return "India";
}
}
class Bike implements Vehicle {
public void accelerate() {
System.out.println("General Bike acc");
}
}
class IndianBike implements IndianVehicle {
public void accelerate() {
System.out.println("Indian bike acc");
}
public String manufacurer(String manf) {
return manf;
}
// Extending interfaces that contain default methods:
// 1. Not mention the default method at all, which lets your extended interface inherit the default method.
// 2. Redeclare the default method, which makes it abstract.
// 3. Redefine the default method, which overrides it.
}
class Main {
public static void main(String[] args) {
Vehicle bike = new Bike();
bike.accelerate();
IndianVehicle indianBike = new IndianBike();
indianBike.accelerate();
System.out.println("Bike country: " + indianBike.country());
System.out.println("Bike manf: " + indianBike.manufacurer("Bajaj"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment