Java Inheritance Help Needed [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 17 hours ago.
This post was edited and submitted for review 16 hours ago and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
Here is the problem:
Create a class named BankAccount, containing:
a constructor accepting a String corresponding to the name of the account holder.
a method, getBalance, that returns a double corresponding to the account balance.
a method withdraw that accepts a double, and deducts the amount from the account balance.
Write a class definition for a subclass, CheckingAccount, that contains:
a boolean instance variable, overdraft. (Having overdraft for a checking account allows one to write checks larger than the current balance).
a constructor that accepts a String and a boolean. The String parameter is used in the invocation of the superclass (BankAccount) constructor, while the boolean is used to initialize the overdraft instance variable.
a method, hasOverdraft, that returns a boolean. hasOverdraft returns true if the account supports overdraft.
a method, clearCheck, that accepts a double and returns a boolean. clearCheck will determine if the amount (of the check) can be cashed-- this will be the case if the amount is less than the balance in the account, or if the account allows overdraft. If the check can be cashed, clearCheck returns true, and also calls the withdraw method to update the account balance; otherwise, clearCheck returns false.
In the main method, create an object of type CheckingAccount, accepts input from the user to fill the information, and call all the methods of this object.
Currently, I have both the BankAccount and CheckingAccount done which leaves the main body to do. Unfortunately, I have no idea about how to do the Main Method/body for this assignment. Besides only a brief excerpt above, which will be bolded, I have no idea.
Below is what I have so far.
import java.util.Scanner;
//Main Class
public class S2W5PA {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.println("Enter Name of Account: ");
String name=input.nextLine();
CheckingAccount CA=new CheckingAccount(name, check);
}
}
//BankAccount Class
public class BankAccount {
private String name;
private double balance;
BankAccount(String name){
this.name=name;
}
public void setBalance(double balance) {
this.balance = balance;
}
public double getBalance() {
return balance;
}
public void withdraw(double amount){
this.balance-=amount;
}
public void deposit(double amount){
this.balance+=amount;
}
}
//CheckingAccount Class
public class CheckingAccount extends BankAccount {
public CheckingAccount(String name, boolean overdraft) {
super(name);
this.overdraft = overdraft;
}
public boolean hasOverdraft() {
return overdraft;
}
public boolean clearCheck(double amount) {
if (getBalance() >= amount || overdraft)
{
withdraw(amount);
return true;
}
return false;
}
private boolean overdraft;
}
I am trying to make sure I'm doing it correctly and not missing any details. I think most of the work is done but I feel like I am missing something.

Related

Access from state class to private fields of context class

I am confused about state pattern implementation. Under this pattern, we should extract state management into separate classes. At first glance it allows us to avoid big if ... else ... constructions inside domain entity and it really powerful advantage. We can move all condition checks into state classes and clear our domain entity class.
But how to modify the data encapsulated in the domain object without encapsulation principle violation?
For example, consider the Account entity. In a simplified way, it has two possible states - Active and Blocked and methods for money deposit and withdrawal.
Under the state pattern, we should delegate deposit and withdrawal responsibilities to state classes. UML diagram here.
But how can we modify the money and state fields from AccountState implementations? I see only the way where I have public setters for it. But it violates the encapsulation principle. With this approach, I can also change private fields to the public.
Code example:
class Account {
private int money;
private AccountState state;
public Account() {
this.money = 0;
this.state = new Active();
}
public void deposit(int amount) {
this.state.deposit(this, amount);
}
public void withdraw(int amount) {
this.state.withdraw(this, amount);
}
public int getMoney() {
return this.money;
}
public AccountState getState() {
return this.state;
}
}
interface AccountState {
public void deposit(Account account, int amount);
public void withdraw(Account account, int amount);
}
class Active implements AccountState {
public void deposit(Account account, int amount) {
// How to change account money and state without setters and public fields usage?
}
public void withdraw(Account account, int amount) {
if (account.getState() instanceof Blocked) {
throw new RuntimeException("Money could not be withdrawn. Account is blocked.");
}
if (account.getMoney() - amount <= 0) {
throw new RuntimeException("Money could not be withdrawn. Insufficient funds.");
}
// How to change account money and state without setters and public fields usage?
}
}
class Blocked implements AccountState {
public void deposit(Account account, int amount) {
// How to change account money and state without setters and public fields usage?
}
public void withdraw(Account account, int amount) {
if (account.getMoney() - amount <= 0) {
throw new RuntimeException("Money could not be withdrawn. Insufficient funds.");
}
// How to change account money and state without setters and public fields usage?
}
}
This is a very simplified example, but it well reflected my problem. Unfortunately, I couldn't found a good solution for it. All examples that I saw use either public setters or public fields. Also, I saw an example from the Refactoring to Patterns book by Joshua Kerievsky. He offers to use setters with package-level access (without access modifiers like private, public, or protected). So, we can change entity data from state classes located in the same package with the domain entity and can not do it from other packages. But this approach is using the language-specific feature - package-level access. In other languages like PHP, it wouldn't work. I'm looking for a conceptual solution.
Can anyone show a real production example solving this problem? I would really appreciate it.
Public setters (or actually setters in general regardless of access modifier) do not violate encapsulation. Encapsulation means we set up the class so only methods in the class with the variables can refer to the instance variables. In correctly encapsulated classes, callers are thus required to use these methods if they want to modify class fields.
To allow calls only from specific classes you could use reflection.
Example in Java:
How to get the caller class in Java
Example in PHP:
https://stackoverflow.com/a/6927569/724099
I would either:
Move money into AccountState (as the AccountState largely operates with money in this example)
Provide a method which manipulates Account in a way you prescribe. This may be through a method like Account#transact(String label, double amount), allowing you to manipulate the balance without exposing the member.
Remove AccountState as a redundant class, since the fields of a class are to represent the state of an object.
The second can be done through the function API as well, but do not confuse the mutability of a class member with breaking encapsulation; the purpose of encapsulation is to disallow unwanted behavior (like arbitrary math or access to internal collections). This prevents the class from entering an erroneous state.
There are many ways to solve this problem, depending on exactly what you need each state instance to do. In this specific example, I would pass the field value of money into the AccountState rather than the entire Account object.
Here is an example using an enum, but obviously that could be two separate classes with an interface instead.
public class Account {
private int balance = 0;
private AccountState currentState = AccountState.ACTIVE;
public int deposit(int amount) {
balance = currentState.deposit(balance, amount);
return balance;
}
public int withdraw(int amount) {
balance = currentState.withdraw(balance, amount);
return balance;
}
public AccountState activate() {
this.currentState = AccountState.ACTIVE;
return currentState;
}
public AccountState block() {
this.currentState = AccountState.BLOCKED;
return currentState;
}
enum AccountState {
ACTIVE {
#Override int deposit(int balance, int amount) {
return balance + amount;
}
#Override int withdraw(int balance, int amount) {
int newBalance = balance - amount;
if (newBalance >= 0) {
return newBalance;
}
throw new IllegalArgumentException("Withdrawal amount is greater than balance.");
}
},
BLOCKED {
#Override int deposit(int balance, int amount) {
throw new UnsupportedOperationException("Account is blocked.");
}
#Override int withdraw(int balance, int amount) {
throw new UnsupportedOperationException("Account is blocked.");
}
};
abstract int deposit(int balance, int amount);
abstract int withdraw(int balance, int amount);
}
}
One clue that the code in the OP will be difficult to apply OOP patterns to is that the business logic methods (deposit and withdraw) return void. It's difficult to do anything other than procedural programming with void methods. Make your methods return appropriate values and you will have an easier time composing classes that interact naturally.

What is the proper way to print to user in Java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
My computer science teachers have told me that I should not be printing strings from methods such as getters and that I should be printing from the main method to the user. I was wondering if it mattered where I print from and what is the proper way to structure my code.
For example:
public class Main {
public static void main(String[] args) throws IOException {
Bank bank = new Bank(20);
System.out.println(bank.getBalance());
}
}
public class Bank {
int balance;
public Bank(int balance){
this.balance = balance;
}
public String getBalance(){
return "You have $" + this.balance;
}
}
as opposed to how my teacher says I should write it
public class Main {
public static void main(String[] args) throws IOException {
Bank bank = new Bank(20);
System.out.println("You have $" + bank.getBalance());
}
}
public class Bank{
int balance;
public Bank(int balance){
this.balance = balance;
}
public int getBalance(){
return this.balance;
}
}
Your teacher is right.
You are not really printing anything in your getters, just that you are obscuring the data types. A balance of an account (not really a bank) is presumably a numeric type (int, long) and not a String.
In general, let your methods do one thing right. By printing something in your getter and returning is okay for debugging, but not advisable in general. And that's what your teacher means.
Writing classes that have well-defined and type-safe API is useful and important especially in Java.
Your teacher is correct.
The purpose of the getBalance method is to "get" the balance in a way that other parts of your application can use it. There are lots of ways that the balance could be used, including printing it (in various places / various ways) adding it to a spreadsheet, adding it to a total, etcetera.
If you design your getBalance() method to just format and print the balance (to standard output), then all of the other things require other methods ... for each other thing.
There is a principle in software engineering known as "separation of concerns". A class (or more generally, a module) should do the things that it needs to do, and leave the other things to the caller of the classes methods. In this case, we are talking about SoC at a fine-grained level ... but the principle applies at this level too.
The version your teacher would have you write makes more sense to me. As a user of your Java classes, I prefer getting the balance as a numeric and then use it any way I wish. Presenting the data as a USD string is obviously a valid use case, but not the only one I could think of. Suppose, as a client of your class, that I'd like to know how many euros, pounds or rupees I could get with my account, then the second implementation would suit me better.
Your teacher is probably suggesting that the Bank should not be responsible for how to display the balance as a string, since different people using the bank may want to display the balance differently.
One way to deal with this is by simply keeping the bank as your professor suggests, and just format it in your own way after you get the balance number.
Second way is to make your own formatter class that formats the string in the way you want like:
public class Main2
{
public Main2() {
Bank bank = new Bank(20);
System.out.println(BalanceFormat.formatBalance(bank.getBalance()));
}
public static void main(String[] args) {
new Main2();
}
}
class Bank {
private int balance;
public Bank(int balance) {
this.balance = balance;
}
public int getBalance() {
return balance;
}
}
class BalanceFormat
{
public static String formatBalance(int balance) {
return ("Your balance is $" + balance);
}
}
The third way to do this is via callbacks, this way you tell the bank how you want it to behave while it maintains its' defaults.
public class Main
{
public Main()
{
Bank bank = new Bank(20);
System.out.println(bank.getBalanceString());
Bank bank2 = new Bank(20, (balance) -> {
return ("Your balance is: $" + balance);
});
System.out.println(bank2.getBalanceString());
}
public static void main(String[] args)
{
new Main();
}
private class Bank
{
int balance;
BalanceStringCallback bankPrintBehavior = null;
public Bank(int balance, BalanceStringCallback callback)
{
this.bankPrintBehavior = callback;
this.balance = balance;
}
public Bank(int balance)
{
this.balance = balance;
}
public int getBalance()
{
return this.balance;
}
public String getBalanceString()
{
if (bankPrintBehavior == null) {
return String.valueOf(balance);
} else {
return (bankPrintBehavior.callback(balance));
}
}
}
#FunctionalInterface
private interface BalanceStringCallback
{
abstract String callback(int balance);
}
}
There are other ways, like creating your own subclass of Bank and make it know how to format in the way you like it(Although this makes changing how one bank behaves harder, whereas the third approach of callbacks also allows you to change the behavior on the fly), but those three ways are first that popped to mind.

Is there a way to inherit from two classes

My assignment:
Code a class called SeniorWorker which inherits from Employee class, in addition to name, salary, and overtimePay, it adds a double type data called meritPay which is calculated as 10% of the salary. It overrides earning() and toString methods to compute the total salary of SeniorWorker and return proper data of SeniorWorker, respectively.
Clarification: The assignment lets us use some example code from the book (Employee,RegularWorker,Manager, SeniorManager. java). My problem is that the SeniorWorker class inherits from the Employee class all those variable however the Employee class only includes the name variable and the rest of the variables except the meritPay are in the RegularWorker Class that why I'm wondering if I could inherit from both the Employee class and RegularWorker or do I need to do something else?
Code:
public class Employee {
private String name;
// Constructor
public Employee(String name ) {
this.name = name;
}
public String getName()
{ return name; }
public double earnings(){return 0.0;}
}
public class RegularWorker extends Employee {
protected double salary, overtimePay;
public RegularWorker( String name, double salary, double overtimePay) {
super( name ); // call superclass constructor
this.salary = salary;
this.overtimePay = overtimePay;
}
public double earnings() { return salary + overtimePay; } //override the method to return salary
public String toString() { //override the method to print the name
return "Regular worker: " + getName();
}
}
My Class:
So far i've just resorted to inheriting from the regularworker class(and it works) , however the assignment says i should inherit from employee class.
public class SeniorWorker extends RegularWorker {
public double meritPay;
public SeniorWorker(String name, double salary,double overtimePay, double meritPay)
{
super(name,salary,overtimePay);
this.meritPay = meritPay;
}
public double getMeritPay() {
return meritPay;
}
public void calculateMeritPay(){
meritPay = 0.10 * salary;
}
public double earnings() { return salary + overtimePay + meritPay; } //override the method to return salary
public String toString() { //override the method to print the name
return "Senior Worker: " + getName();
}
}
No, in java you can only inherit from one class. However, that class can inherit from another, and so on. You can extend multiple interfaces, which in java 8 could contain default method implementations (which could be default getters that return a predetermined value for the encapsulated attributes).
However, inheritance should only really be used for code sharing, and interfaces should only really be used for polymorphism.
Having said that, in your example, your RegularWorker is an Employee, so your SeniorWorker is a RegularWorker and is an Employee. Therefore, your SeniorWorker is inheriting (is extended from) Employee, as your assignment requests.
But, if you think about it, how can a senior worker also be a regular worker? They're not regular, they're senior. They may have been regular at one point in their career, but now they're senior, and not regular at all, despite having some stuff in common with regular employees. If you push the stuff from regularemployee up to employee, and have two descendants of employee, regular and senior, then you'll have sorted this mess out and probably earned extra points for being clever.

Get a protected attribute from another class

Hi I am a beginning programmer and I think I have a simple question but yet i can't find the answer. I hope you can help me:D I have four classes in total but what I need to solve is in class Person. I have a simple method that needs thePrice parameter from class Product. But it does not work because i can't get access to this parameter.
This is the method that the Person class uses to buy a product. The budget from a person has to be greater or equal to thePrice, if not > he can not buy the product. But he can only buy the product if he has not owned the product already.
public class Person{
private String name;
private double budget;
private ArrayList<Product> allPossessions;
private Product theProduct; //association with class product, I have all getters and setters etc.
// the method:::
public boolean Buy(Product p) {
if (hasProduct(null) == true) {
if (budget >= Product.getThePrice()) {
// getTheprice does not work, how do i get this working? How do i get this parameter from class product?
return true;
}
return false;
}
return false;
}
This is class Product where I need to have thePrice, to create the method.
public abstract class Product {
protected String Design;
protected int yearOfPurchase;
protected double thePrice;
}
Thank you for your time and forgive my broken english! Thank you:)
You should write a getter method for thePrice param inside Product class.
public double getPrice() {
return thePrice;
}

Constructor over methods in java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I want to know the exact scenario of using constructor over methods can anyone give me the exact example program for constructors over methods in java
They are not similar things to compare even.
Both serves completely different purposes and even you have to note that constructor wont return anything, not even void :)
If you see a basic tutorial on Constructor, mentioned
Constructor declarations look like method declarations—except that they use the name of the class and have no return type.
So you cannot choose one over them.
If you are looking/talking about setting variables of instance memebers, choose setter methods instead of variables.
Another scenoriao is some objects never complete without providing some basic info. In that cases you have to create a constructor like it should be built when necessary info passed in constructor.
Consider the below scenorio, where to create an employee class, He must have an employee Id
public class Employee {
String empId;
public Employee(String empId) {
this.empId = empId;
}
// Methods
public static void main(String[] args) {
Employee a = new Employee("green");
}
Consider the below scenorio, where to create an empty employee class, later he can assign employee Id
public class Employee {
private String empId;
public Employee() {
}
// Methods
public void setEmpId(String empId) {
this.empId = empId;
}
public static void main(String[] args) {
Employee a = new Employee(); //No error
a.setEmpId("SOMEX007");
}
}

Categories

Resources