Practice Programs - Inheritance2
Practice Programs - Inheritance2
//Base class
class Vehicle {
void start() {
System.out.println("The vehicle is starting.");
}
}
//Derived class
class Car extends Vehicle {
void honk() {
System.out.println("The car is honking.");
}
}
Output:
The vehicle is starting.
The car is honking.
Program2: :Inheritance
//Base class
class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}
//Derived class
class Dog extends Animal {
void bark() {
System.out.println("The dog barks.");
}
}
Output:
This animal eats food.
The dog barks.
//Derived class
class Student extends Person {
Student() {
System.out.println("Student constructor called.");
}
}
Program 4:Inheritance
class Bank{
double GetInterestRate(){
return 0.0;
}
}
class SBI extends Bank{
double GetInterestRate(){
return 5.5;
}
}
class ICIC extends Bank{
double GetInterestRate(){
return 6.0;
}
}
Output:
rate of interest of sbi is :5.5
rate of interest of icic is :6.0
rate of interest of sbi is :5.5
Program 4:Private members
class Car {
// Private member variable
private String model;
Program 5:
Program 6:
//BankAccount.java
class BankAccount {
protected double balance;
//SavingsAccount.java
class SavingsAccount extends BankAccount {
// Override the withdraw method to prevent balance from going below 100
@Override
public void withdraw(double amount) {
if (amount > 0 && (balance - amount) >= 100) {
balance -= amount;
System.out.println("Withdrawal successful. New balance: $" +
balance);
} else {
System.out.println("Withdrawal failed. Minimum balance of $100
required. Current balance: $" + balance);
}
}
}
//Main.java
public class Main {
public static void main(String[] args) {
// Create a regular bank account
BankAccount myAccount = new BankAccount(500);
myAccount.deposit(100);
myAccount.withdraw(200);
myAccount.withdraw(600); // Invalid withdrawal
Program 7: Multilevel
// Child class 1
class Cars extends Vehicle {
public void drive() {
System.out.println("Car is driving.");
}
}
// Child class 2
class Bike extends Vehicle {
public void ride() {
System.out.println("Bike is riding.");
}
}
//Superclass
class Animals {
String name;
// Constructor of Superclass
public Animals(String name) {
this.name = name;
System.out.println("Animal constructor called");
}
}
//Subclass
class Dogs extends Animals {
String breed;
// Constructor of Subclass
public Dogs(String name, String breed) {
// Calling the superclass constructor using super()
super(name);
this.breed = breed;
//this.name=name;
//this.name=name;
System.out.println("Dog constructor called");
}