There are a few things to note about the code:
We have used abstract keyword to define the Bank class and its abstract
method getBalance(). This means that we cannot create an object of the Bank
class directly, but can only create objects of its subclasses, which must
implement the getBalance() method.
We have used the extends keyword to create subclasses BankA, BankB, and
BankC that inherit from the Bank class. This means that these subclasses will
have access to the methods and variables of the Bank class, and must implement
the getBalance() method as required by the Bank class.
We have created private instance variables in each subclass to store the
balance amounts. This ensures that these variables cannot be accessed or
modified directly from outside the class, and can only be accessed through the getBalance()
method.
We have overridden the getBalance() method in each subclass to return the
corresponding balance amount stored in the private instance variable.
Finally, we have created objects of each of the three subclasses and called
their getBalance() methods to print their respective balance amounts. This
demonstrates the use of inheritance and polymorphism in object-oriented
programming.
Source Code..
package class2;
//@author Java_Programs
public class Class2 {
public static void main(String[] args) {
BankA bA = new BankA();
bA.getBalance();
BankB bB = new BankB();
bB.getBalance();
BankC bC = new BankC();
bC.getBalance();
}
}
abstract class Bank{
public abstract void getBalance();
}
class BankA extends Bank{
@Override
public void getBalance(){
System.out.println("Deposited: $100 ");
}
}
class BankB extends Bank{
@Override
public void getBalance(){
System.out.println("Deposited: $150 ");
}
}
class BankC extends Bank{
@Override
public void getBalance(){
System.out.println("Deposited: $200 ");
}
}
In this code, we first define an abstract class Bank with an
abstract method getBalance(). This method will be implemented by the subclasses
BankA, BankB, and BankC. Each of these subclasses has a private instance
variable for the balance, initialized to the specified amounts in the problem
statement.
In the Main class, we create objects of each of the three
subclasses and call their getBalance() methods to print their respective
balances.
When we run the program, the output will be:
Bank A balance: $100
Bank B balance: $150
Bank C balance: $200
This shows that each of the three banks has the correct
balance as specified in the problem statement.
No comments:
Post a Comment