javaCopy code
// Class representing a Book
public class Book {
private String title;
private boolean isBorrowed;
public Book(String title) {
this.title = title;
this.isBorrowed = false;
}
public void borrowBook() {
if (!isBorrowed) {
isBorrowed = true;
} else {
System.out.println(title + " is already borrowed.");
}
}
public void returnBook() {
isBorrowed = false;
}
public String getTitle() {
return title;
}
public boolean isBorrowed() {
return isBorrowed;
}
}
// Class representing a Member of the Library
public class Member {
private String name;
private int borrowedBooks;
public Member(String name) {
this.name = name;
this.borrowedBooks = 0;
}
public void borrow(Book book) {
if (!book.isBorrowed()) {
book.borrowBook();
borrowedBooks++;
System.out.println(name + " borrowed " + book.getTitle());
} else {
System.out.println(book.getTitle() + " is not available.");
}
}
public String getName() {
return name;
}
public int getBorrowedBooks() {
return borrowedBooks;
}
}
// Main class to demonstrate interactions
public class LibrarySystem {
public static void main(String[] args) {
// Array of books in the library
Book[] books = new Book[]{
new Book("1984"),
new Book("To Kill a Mockingbird"),
new Book("The Great Gatsby")
};
// Array of members in the library
Member[] members = new Member[]{
new Member("Alice"),
new Member("Bob")
};
// Simulating some interactions
members[0].borrow(books[0]); // Alice borrows "1984"
members[1].borrow(books[0]); // Bob tries to borrow "1984", but it's already borrowed
members[1].borrow(books[1]); // Bob borrows "To Kill a Mockingbird"
}
}
javaCopy code
import java.util.ArrayList;
// Superclass
public class Vehicle {
public void startEngine() {
System.out.println("Vehicle engine started.");
}
public void stopEngine() {
System.out.println("Vehicle engine stopped.");
}
}
// Subclass Car
public class Car extends Vehicle {
@Override
public void startEngine() {
System.out.println("Car engine started with a key.");
}
// Overloading method
public void startEngine(boolean isRemoteStart) {
if (isRemoteStart) {
System.out.println("Car engine started remotely.");
} else {
super.startEngine(); // Calls the overridden method
}
}
}
// Subclass Motorcycle
public class Motorcycle extends Vehicle {
@Override
public void startEngine() {
System.out.println("Motorcycle engine started with a button.");
}
}
// Main class to demonstrate polymorphism
public class Transport {
public static void main(String[] args) {
ArrayList<Vehicle> vehicles = new ArrayList<>();
vehicles.add(new Car());
vehicles.add(new Motorcycle());
// Demonstrating polymorphism
for (Vehicle v : vehicles) {
v.startEngine();
}
// Demonstrating overloading
Car car = new Car();
car.startEngine(true); // Starts engine remotely
}
}