public interface Student {
void enroll(String courseName);
}
public class ComputerStudents implements Student {
@Override
public void enroll(String courseName) {
System.out.println("Computer Science Student enrolling in: " + courseName);
// Additional implementation specific to Computer Students
}
// Other methods and properties specific to Computer Students
}
public class HealthStudents implements Student {
@Override
public void enroll(String courseName) {
System.out.println("Health Science Student enrolling in: " + courseName);
// Additional implementation specific to Health Students
}
// Other methods and properties specific to Health Students
}
public class StudentDemo {
public static void main(String[] args) {
Student computerStudent = new ComputerStudents();
Student healthStudent = new HealthStudents();
computerStudent.enroll("Advanced Programming");
healthStudent.enroll("Anatomy 101");
}
}
public class Hello {
public static void main(String[] args) {
// Initialize the Calculator object
Worker.c = new Calculator();
// Calling the static member and storing the returned value
int theAnswer = Worker.c.addNumbers(2, 2);
// Printing the result
System.out.println(theAnswer);
}
}
class Worker {
static Calculator c; // Static Calculator reference
}
class Calculator {
public int addNumbers(int a, int b) {
return a + b;
}
}
// Interface definition
interface Animal {
void makeSound();
}
// Class Dog implementing the interface Animal
class Dog implements Animal {
@Override
public void makeSound() {
System.out.println("Woof! Woof!");
}
}
// Class Cat implementing the interface Animal
class Cat implements Animal {
@Override
public void makeSound() {
System.out.println("Meow! Meow!");
}
}
// Main class to run the program
public class InterfaceDemo {
public static void main(String[] args) {
Animal myDog = new Dog();
Animal myCat = new Cat();
myDog.makeSound(); // Output: Woof! Woof!
myCat.makeSound(); // Output: Meow! Meow!
}
}
javaCopy code
// Abstract class definition
abstract class Vehicle {
// Abstract method
abstract void move();
// Concrete method
void fuelType() {
System.out.println("Unknown");
}
}
// Class Car extending the abstract class Vehicle
class Car extends Vehicle {
@Override
void move() {
System.out.println("Car moves on four wheels");
}
@Override
void fuelType() {
System.out.println("Petrol or Diesel");
}
}
// Class Bicycle extending the abstract class Vehicle
class Bicycle extends Vehicle {
@Override
void move() {
System.out.println("Bicycle moves on two wheels");
}
// fuelType method is not overridden, it will use the version from Vehicle class
}
// Main class to run the program
public class AbstractClassDemo {
public static void main(String[] args) {
Vehicle myCar = new Car();
Vehicle myBicycle = new Bicycle();
myCar.move(); // Output: Car moves on four wheels
myCar.fuelType(); // Output: Petrol or Diesel
myBicycle.move(); // Output: Bicycle moves on two wheels
myBicycle.fuelType(); // Output: Unknown
}
}