Diamond Problem and Interface Concept in Java
Diamond Problem and Interface Concept in Java
// Diamond Problem
import java.io.*;
// Parent Class1
class Parent1 {
}
// Parent Class2
class Parent2 {
// main function
t.fun();
Output:
Error
Explanation : In above example we have seen that “test” class is extending two
classes “Parent1 ” and “Parent2” and its calling function “fun()” which is
defined in both parent classes so now here it got confused which definition it
should inherit.
Although Diamond Problem is a serious issue but we can create a solution for it
which is Interface. Interface are created by using interface keyword. It contains
all methods by default as abstract we don’t need to declared as abstract ,compiler
will do it implicitly.
// Diamond Problem
import java.io.*;
// Interfaces Declared
interface Parent1 {
void fun();
// Interfaces Declared
interface Parent2 {
void fun();
System.out.println("fun function");
// Driver Class
class test1 {
// main function
{
test t = new test();
t.fun();
Output
fun function
Another Solution???????????
public class A {
public void foo() {
System.out.println("Method foo() from class A");
}
}
public class B {
public void foo() {
System.out.println("Method foo() from class B");
}
}
Java Interface
Syntax
interface {
// declare constant fields
// declare methods that abstract
// by default.
}
import java.io.*;
// Add interface
interface Add{
// Sub interface
interface Sub{
return a+b;
return a-b;
}
}
class GFG{
// Main Method
Output
Addition : 3
Substraction : 1
Another feature that was added in JDK 8 is that we can now define static methods
in interfaces that can be called independently without an object. These methods
are not inherited.
interface TestInterface
{
System.out.println("hello");
// Driver Code
TestInterface.display();
Output
hello
Extending Interfaces
interface A {
void method1();
void method2();
// and method2
interface B extends A {
void method3();
System.out.println("Method 1");
System.out.println("Method 2");
}
public void method3() {
System.out.println("Method 3");
x.method1();
x.method2();
x.method3();
Output???
Output
Method 1
Method 2
Method 3
Question:
You have two interfaces, InterfaceA and InterfaceB, both defining a default
method printMessage(). If a class MyClass implements both interfaces, how can
you resolve the Diamond Problem?
Answer:
Since both interfaces provide a default method with the same signature, Java will
throw a compilation error unless MyClass explicitly overrides printMessage(). The
solution is to override the method and specify which interface's method should
be used using InterfaceName.super.method().
Code Solution
interface InterfaceA {
default void printMessage() {
System.out.println("Message from Interface A");
}
}
interface InterfaceB {
default void printMessage() {
System.out.println("Message from Interface B");
}
}
Expected Output:
Message from Interface A
Message from Interface B
Message from MyClass
Question:
Suppose you have two interfaces, X and Y, both declaring an abstract method
show(). A class Z implements both interfaces. What will happen, and how do you
resolve it?
Answer:
Since interfaces X and Y only declare abstract methods (without default
implementations), no ambiguity occurs. The implementing class Z must override
the method.
Code Solution
interface X {
void show(); // Abstract method
}
interface Y {
void show(); // Abstract method
}
class Z implements X, Y {
// Must override the show() method
@Override
public void show() {
System.out.println("Implemented show() in Z");
}
}
Implemented show() in Z
Question:
What happens if a class extends another class while also implementing an interface
that has a method with the same name?
Answer:
Java gives priority to class methods over interface default methods. If
BaseClass has a method display(), it automatically overrides the interface's
default method.
Code Solution
class BaseClass {
public void display() {
System.out.println("Display from BaseClass");
}
}
interface InterfaceC {
default void display() {
System.out.println("Display from InterfaceC");
}
}
Expected Output:
Question:
Consider three interfaces: A, B, and C. B and C both extend A, and a class D
implements both B and C. If A has a default method greet(), will there be a
Diamond Problem?
Answer:
Since B and C both inherit greet() from A and do not override it, D will directly
inherit greet() from A. There is no conflict unless B or C override greet(), in which
case D must explicitly override it.
Code Solution
interface A {
default void greet() {
System.out.println("Greet from A");
}
}
interface B extends A {}
interface C extends A {}
class D implements B, C {
// No need to override greet() since A provides it
}
Expected Output:
Greet from A
Question:
Can static methods in interfaces cause a Diamond Problem? Consider two
interfaces, M and N, both defining a static method info(). If a class P implements
both, what will happen?
Answer:
Static methods in interfaces do not cause a Diamond Problem because they
belong to the interface itself and cannot be overridden. To call them, use
InterfaceName.methodName().
Code Solution
interface M {
static void info() {
System.out.println("Info from M");
}
}
interface N {
static void info() {
System.out.println("Info from N");
}
}
class P {
void show() {
M.info(); // Calling static method of M
N.info(); // Calling static method of N
}
}
public class Main {
public static void main(String[] args) {
P obj = new P();
obj.show();
}
}
Expected Output:
Info from M
Info from N
3. Class & Interface Class method takes priority over interface default
method conflict methods.
Programs in Interface:
1. Define an interface “QueueOperations” which declares methods for a static queue. Define a class
“MyQueue” which contains an array and front and rear as data members and implements the above
interface. Initialize the queue using a constructor. Write the code to perform operations on a queue
object.
2. Write a java class called ‘student’ with name, and rollno. Write a class ‘Result’ to get Marks of 3 subjects
and another class “Sports’ to get the points obtained in sports. Calculate the total Marks and displays the
result (pass or fail) with points obtained in sports for three students using inheritance and constructor.
3. Define an abstract class “car” with members reg_no, model, reg_date. Define two subclasses of this class
– “transportVehicles ” (validity_no, start_date, period) and “privateVehicle ” (owner_name,
owner_address). Define appropriate constructors. Create n objects which could be of either
transportVehicles or privateVehicle class by asking the user’s choice. Display details of all
“privateVehicle” objects and all “transportVehicles” objects.
4. Create an interface “CreditCardInterface” with methods to viewCreditAmount, viewPin, changePin and
payBalance. Create a class Customer (name, card number, pin, creditAmount – initialized to 0).
Implement methods of the interface “CreditCardInterface” in Customer class. Create an array of
customer objects and perform the following actions.
a. Pay Balance
b. Change Pin
5. Develop a Java application with employee class includes emp_name, emp_id, address, mail_id,
mobile_no as members.
a. Inherit the classes Programmer, Assistant Professor from employee class.
b. Add Basic Pay as the member of all the inherited classes with 97% of BP as DA, 10% of BP
as HRA, 12% of BP as PF, 0.1% of BP for staff club fund.
c. Generate the pay slips for the employees with their gross and net salary.
6. Create a Java application to find the area of different shapes using abstract class.
Use the abstract class Shape that include two integers and an empty method named printArea().
Construct the classes Rectangle, Triangle and Circle inherited from the class Shape. The Derived classes
should include only the method printArea() that print the area of the given shape.
7. A vehicle rental company rents out different types of vehicles, such as Car, Truck, and Bike. Each type of
vehicle has different pricing rules for renting it. We will use runtime polymorphism to call the rent()
method for different vehicle types, and compile-time polymorphism to calculate the rental for multiple
days or hours.
8. In an employee payroll system, we have multiple types of employees (Manager, Developer, and Intern).
Each type of employee has different methods to calculate their salary based on their type and work
hours. The salary calculation is done using polymorphism, where each employee type overrides a
calculateSalary() method.
9. In a shape drawing application, there are various shapes like Circle, Rectangle, and Triangle. Each shape
has a draw() method, but the implementation of drawing the shape is different for each one. Using
polymorphism, the application should be able to call the draw() method on different shapes through a
common reference.
10.Bank Account System with Encapsulation
Design a BankAccount class that encapsulates the details of a bank account, such as the account holder's
name, account number, and balance. Provide the following methods:
These Java programs cover essential OOP concepts like inheritance, polymorphism,
encapsulation, and abstraction. Below are solutions with explanations for each scenario.
This program demonstrates how to define an interface for queue operations and implement it in
a class.
Code
// Interface defining queue operations
interface QueueOperations {
void enqueue(int item);
int dequeue();
void display();
}
// Dequeue operation
public int dequeue() {
if (front == -1 || front > rear) {
System.out.println("Queue is empty");
return -1;
}
return queue[front++];
}
// Display queue
public void display() {
if (front == -1 || front > rear) {
System.out.println("Queue is empty");
return;
}
System.out.print("Queue elements: ");
for (int i = front; i <= rear; i++) {
System.out.print(queue[i] + " ");
}
System.out.println();
}
Explanation
Output
10 added to queue
20 added to queue
30 added to queue
Queue elements: 10 20 30
Dequeued: 10
Queue elements: 20 30
This program calculates the total marks and result by using multiple classes.
Code
// Student class with name and roll number
class Student {
String name;
int rollNo;
public Result(String name, int rollNo, int s1, int s2, int s3) {
super(name, rollNo);
subject1 = s1;
subject2 = s2;
subject3 = s3;
}
public Sports(String name, int rollNo, int s1, int s2, int s3, int points)
{
super(name, rollNo, s1, s2, s3);
sportsPoints = points;
}
Explanation
Output
Code
import java.util.Scanner;
// TransportVehicle subclass
class TransportVehicle extends Car {
String validityNo, startDate, period;
void display() {
System.out.println("Transport Vehicle - " + model + ", Reg No: " +
regNo);
}
}
// PrivateVehicle subclass
class PrivateVehicle extends Car {
String ownerName, ownerAddress;
void display() {
System.out.println("Private Vehicle - " + model + ", Owner: " +
ownerName);
}
}
System.out.println("Transport Vehicles:");
for (Car c : vehicles) {
if (c instanceof TransportVehicle) c.display();
}
System.out.println("\nPrivate Vehicles:");
for (Car c : vehicles) {
if (c instanceof PrivateVehicle) c.display();
}
}
}
Explanation
Output
Transport Vehicles:
Transport Vehicle - Truck, Reg No: TN01AB1234
Transport Vehicle - Bus, Reg No: TN03EF9101
Private Vehicles:
Private Vehicle - Sedan, Owner: John Doe
This program implements a credit card system using an interface and an array of customers.
Code
import java.util.Scanner;
customers[0].payBalance(500);
customers[0].viewCreditAmount();
customers[0].changePin(9999);
}
}
Explanation
Output
Code
// Employee base class
class Employee {
String empName, empId, address, mailId;
long mobileNo;
double basicPay;
public Employee(String name, String id, String addr, String mail, long
mobile, double basicPay) {
this.empName = name;
this.empId = id;
this.address = addr;
this.mailId = mail;
this.mobileNo = mobile;
this.basicPay = basicPay;
}
// Programmer subclass
class Programmer extends Employee {
public Programmer(String name, String id, String addr, String mail, long
mobile, double basicPay) {
super(name, id, addr, mail, mobile, basicPay);
}
}
// AssistantProfessor subclass
class AssistantProfessor extends Employee {
public AssistantProfessor(String name, String id, String addr, String
mail, long mobile, double basicPay) {
super(name, id, addr, mail, mobile, basicPay);
}
}
public class Main {
public static void main(String[] args) {
Employee emp1 = new Programmer("Alice", "P001", "Chennai",
"[email protected]", 9876543210L, 40000);
Employee emp2 = new AssistantProfessor("Bob", "AP002", "Bangalore",
"[email protected]", 8765432109L, 50000);
emp1.displayPaySlip();
emp2.displayPaySlip();
}
}
Explanation
Output
Employee: Alice
Gross Salary: 87400.0
Net Salary: 82600.0
Employee: Bob
Gross Salary: 108500.0
Net Salary: 102900.0
Code
abstract class Shape {
abstract void printArea();
}
// Rectangle subclass
class Rectangle extends Shape {
int length, width;
void printArea() {
System.out.println("Rectangle Area: " + (length * width));
}
}
// Circle subclass
class Circle extends Shape {
int radius;
public Circle(int r) {
radius = r;
}
void printArea() {
System.out.println("Circle Area: " + (Math.PI * radius * radius));
}
}
rect.printArea();
circle.printArea();
}
}
Explanation
Output
Rectangle Area: 50
Circle Area: 153.93804002589985
Code
class Vehicle {
void rent() {
System.out.println("Renting a vehicle");
}
}
// Car subclass
class Car extends Vehicle {
void rent() {
System.out.println("Renting a Car - $50 per day");
}
}
// Bike subclass
class Bike extends Vehicle {
void rent() {
System.out.println("Renting a Bike - $20 per day");
}
}
Explanation
Output
Code
class BankAccount {
private String accountHolder;
private int accountNumber;
private double balance;
Explanation
Output
Deposited: $500
Withdrawn: $300
Account Holder: Alice
Balance: $1200