In a header file, create an Account class that a bank might use to represent cus
ID: 3802221 • Letter: I
Question
In a header file, create an Account class that a bank might use to represent customers' bank accounts. Include a private data member called balance (of type int) to represent the account balance. Provide a constructor that has a parameter and use it to initialize the data member. Provide a public member function getBalance, which should return the balance. Provide a public member function setBalance, that has a parameter and assigns the parameter to the data member. Write a complete program that will have a main function. Assume main function and class definition are in separate files. In main, create an object of class Account and initialize the balance to 500. From main, change the balance of same Account object to 1000. From main, print balance of same Account object.Explanation / Answer
PROGRAM:
package practiceprogram;
//create the Account class
public class Account {
private int balance; //intialize the balance parameter
// generate the public member function getBalance()
public int getBalance() {
return balance;
}
public void setBalance(int balance) {
this.balance = balance;
}
// here u generate the tostring() method to avoid the hashcode valueand it prints the user given value
@Override
public String toString() {
return "Account [balance=" + balance + "]";
}
}
//main class
package practiceprogram;
//create main class test having main function
public class Test extends Account {
// Here we extend the Account class to Test
public static void main(String[] args) {
// create Account object
Account a=new Test();
Test t=(Test)a; // here we downcasting the account class to Test class because of reusablity of account class object balance
a.setBalance(500); //first we assign the account balance as 500 and print this
System.out.println("From account class balance is " +a);
t.setBalance(1000); //here we change the balance value using main function class test object 't' not from account object and print that balance
System.out.println("From main test class balance is "+t);
}
}
OutPut:
From account class balance is
Account [balance=500]
From main test class balance is Account [balance=1000]
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.