Why will objects now be created from my class - java

An error points to the word "new" when I try to compile this program. I'm trying to create 2 objects from the carOrder class and I'm havin troubles! I've had this problem with other programs before and I'm not sure why and it's killing me, please help!
import java.text.DecimalFormat;
import java.util.Scanner;
public class CarOrder
private String buyer;
private String carType;
private double cost;
private int quantity;
private boolean taxStatus;
private double discountedCost;
private double taxAmount;
// Default Constructor
public void carOrder()
{
}
// Constructor
public void CarOrder(String buy, String car, double cos, int quan, boolean tax)
{
buyer = buy;
carType = car;
cost = cos;
quantity = quan;
taxStatus = tax;
}
// Sets the company buying cars
public void setBuyer(String buy)
{
buyer = buy;
}
// Sets the car type being purchased
public void setCarType(String car)
{
carType = car;
}
// Sets cost of the cars being purchased
public void setCost(double cos)
{
cost = cos;
}
// Sets the quantity of cars being purchased
public void setQuantity(int quan)
{
quantity = quan;
}
// Sets tax status for the cars
public void setTaxStatus(boolean tax)
{
taxStatus = tax;
}
// Returns name of buyer to user
public String getBuyer()
{
return buyer;
}
// Returns type of car to user
public String getCarType()
{
return carType;
}
// Returns cost to user
public double getCost()
{
return cost;
}
// Returns quantity of cars to user
public int getQuantity()
{
return quantity;
}
// Returns tax status to user
public boolean getTaxStatus()
{
return taxStatus;
}
// Returns discounted cost to user
public double getDiscountedCost()
{
if (quantity > 10)
if (quantity > 20)
discountedCost = cost - cost * .10;
else
discountedCost = cost - cost * .05;
else
discountedCost = cost;
return discountedCost;
}
// Returns tax amount to users
public double getTaxAmount()
{
taxAmount = cost * .0625;
return taxAmount;
}
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
CarOrder speedy = new CarOrder("Speedy Rental", "Mini Cooper", 22150, 15, true);
CarOrder zip = new CarOrder("Zip Car Co.", "Ford Fusion", 27495, 6, true);
System.out.println("Enter first Buyer");
String buyer1 = keyboard.nextLine();
}
}

public void CarOrder(String buy, String car, double cos, int quan, boolean tax)
{
should be
public CarOrder(String buy, String car, double cos, int quan, boolean tax)
{
Constructor's don't have a return type, not even void.
Currently, you have a method named CarOrder in your class as it has a return type as void, which voilates the rules of custructor. If you remove void, then it'd a constructor as it has the same name as your class.
Same applies to your constructor with no-argsaswell.
public void CarOrder()
should be
public CarOrder()

you are missing a "{" right after public class CarOrder ... :)

When you don't declare a constructor, Java provides a default constructor that have no arguments. As you declared CarOrder(String buy, String car, double cos, int quan, boolean tax), the default constructor is not created anymore. You made a method called carOrder, that probably was an attempt to make a constructor with no arguments, but it has two problems:
it has a return type (void) and constructor doesn't have one
the name is different from the class (cardOrder isn't the same as CarOrder, since Java is case sensitive)
If you want to make a new CarOrder() call, just add the following code:
public CarOrder() {
//insert your implementation here
}

A constructor with a return type is treated as a method by the compiler.

Related

Why am I getting this "NoSuchMethodError" in my code?

Everytime I run my code, I get this error below
Exception in thread "main" java.lang.NoSuchMethodError: 'void Car.<init>(java.lang.String, java.lang.String, double, double, double)'
at DimaweaJeshuaAssignment11.setUpCars(DimaweaJeshuaAssignment11.java:48)
at DimaweaJeshuaAssignment11.main(DimaweaJeshuaAssignment11.java:11)
I looked to see if my constructor in my Car class was correct, and it was, but I'm stuck and can't figure out what the problem is. This is my code below
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
public class DimaweaJeshuaAssignment11 {
public static void main(String[] args) throws IOException {
// create an array of 5 Car objects
Car[] cars = new Car[5];
// set up the cars
setUpCars(cars);
// output the car details to file
writeCarDetailsToFile(cars);
// display the cars at the start of simulation
System.out.println("Cars at start of simulation");
printCars(cars);
int milesTraveled = 0;
boolean allCarsHaveGas = true;
// loop that continues until at least one of the cars has run out of gas
while(allCarsHaveGas) {
milesTraveled++; // increment the miles traveled
// loop to decrement the gallons after traveling 1 mile
for(int i=0;i<cars.length;i++) {
cars[i].updateFuel(1);
if(cars[i].getFuelGauge().getGallons() == 0) { // check if any of cars have run out of gas, update allCarsHaveGas to false
allCarsHaveGas = false;
}
}
}
// display the car details at the end of simulation
System.out.println("Cars at end of simulation");
printCars(cars);
// loop to display the first car that ran out of gas
for(int i = 0; i < cars.length; i++) {
if(cars[i].getFuelGauge().getGallons() == 0) {
System.out.println("\n"+cars[i].getOwner()+"'s car ran out of has after "+ milesTraveled +" miles");
break;
}
}
}
// method to set up the cars for the simulation based on the given information
public static void setUpCars(Car[] cars) {
cars[0] = new Car("Shrek", "Toyota Tundra", 15, 6, 20000);
cars[1] = new Car("Fiona", "Audi Q7", 21, 10, 8270);
cars[2] = new Car("Donkey", "Jeep CJ5", 14, 5, 11800);
cars[3] = new Car("Farquaad", "Smart Car", 42, 4, 710);
cars[4] = new Car("Dragon", "Chevy Suburban", 12, 30, 10800);
}
// method to display the details of the car in the array
public static void printCars(Car[] cars) {
System.out.println("----------------------------------------------------------------------------------------");
System.out.printf("%-20s%-20s%20s%20s\n","Owner","Brand","MPG","Current Gallons", "Mileage");
System.out.println("----------------------------------------------------------------------------------------");
for(int i=0;i<cars.length;i++)
System.out.printf("%-20s%-20s%20.2f%20.2f\n",cars[i].getOwner(),cars[i].getBrand(),cars[i].getFuelEconomy(),cars[i].getFuelGauge().getGallons(), cars[i].getMileage());
System.out.println();
}
// method to display the details of cars in the array to file
public static void writeCarDetailsToFile(Car[] cars) throws IOException {
// setup the file reference variable to refer to the text file
File filename = new File("Assignment11.txt");
// Create the file that the cars will be written to
PrintWriter resultsFile = new PrintWriter(filename);
// Write the details for each car to the file
for(int i=0;i<cars.length;i++) {
resultsFile.println(cars[i].getOwner());
resultsFile.println(cars[i].getBrand());
resultsFile.println(cars[i].getFuelEconomy());
resultsFile.println(cars[i].getFuelGauge().getGallons());
}
resultsFile.close();
}
}
class Car {
// attributes
private String owner;
private String brand;
private double milesPerGallon;
private FuelGauge fuelGauge;
private double mileage;
// constructor to initialize fields to specified values
public Car(String owner, String brand, double milesPerGallon, double gallons, double mileage) {
this.owner = owner;
this.brand = brand;
this.milesPerGallon = milesPerGallon;
fuelGauge = new FuelGauge();
fuelGauge.setGallons(gallons);
this.mileage = mileage;
}
// getters
public String getOwner() {
return owner;
}
public String getBrand() {
return brand;
}
public double getFuelEconomy() {
return milesPerGallon;
}
public FuelGauge getFuelGauge() {
return fuelGauge;
}
public double getMileage() {
return mileage;
}
// update the fuel of the car based on the miles traveled
public void updateFuel(double milesTraveled) {
double gallonsUsed = milesTraveled/milesPerGallon; // compute the gallons used for traveling milesTraveled
fuelGauge.decrementGallons(gallonsUsed); // decrement the gallons used
}
}
class FuelGauge {
// attribute
private double gallons;
// default constructor that initialize gallons to 0
public FuelGauge() {
}
// setter
public void setGallons(double gallons) {
this.gallons = gallons;
}
// getter
public double getGallons() {
return gallons;
}
// method to decrement the gallons by gallons used
public void decrementGallons(double gallonsUsed) {
if(gallonsUsed <= gallons) { // gallonsUsed <= gallons, decrement gallonsUsed from gallons
gallons -= gallonsUsed;
} else // gallonsUsed > gallons, set gallons to 0
gallons = 0;
}
}

Implementing different predicates for different types of employees

I'm new to using predicates and not sure if I'm understanding it properly. I have an abstract employee class in which hourly and salary employee's are created separately. My issue relies in my EmployeePredicate.java class where I am unsure how to check whether it is an hourly employee and to return true or false.
I need to create a different predicate for all of the following conditions:
All employees, Hourly Only, Salary Only and Fulltime Only.
So far I am only trying to get the "Hourly Only" Predicate to work properly first and think I could figure out the rest after that. I am unsure what to put after the 'p' to check which type of employee it is. What I have currently is:
public static Predicate<Employee> isHourlyEmployee() {
return p -> p.
}
I also have the statement double avgSalary = calculateAveragePay(employees, null); and am unsure what to replace null with as it should be a predicate based off my calculateAveragePay function above in main.
Main.java
package homework04;
import java.util.function.Predicate;
public class Main {
public static double calculateAveragePay(Employee[] employees, Predicate<Employee> pred) {
double sum = 0.0;
int count = 0;
for(Employee e : employees) {
if(!pred.test(e)) {
continue;
}
sum += e.calculatePay();
count++;
}
return sum / count;
}
public static void main(String[] args) {
//The list of employees to calculate.
Employee[] employees = {
new HourlyEmployee("John Smith", 80, 18.00),
new HourlyEmployee("Jane Doe", 77, 20.00),
new SalaryEmployee("Bob Miller", 85, 40000.00),
new HourlyEmployee("Alice Davis", 40, 12.50),
new SalaryEmployee("Frank Frink", 70, 35000.00),
new HourlyEmployee("Chris Williams", 95, 25.00)
};
//The average pay for both types of employee.
double avgSalary = calculateAveragePay(employees, null);
double avgHourly = calculateAveragePay(employees, null);
//The bonus to be added to employee pay.
//double bonus = Math.abs(avgSalary - avgHourly);
//Print the average pay
System.out.println("===== Average Pay =====");
}
}
Employee.java
package homework04;
import java.util.function.Predicate;
abstract class Employee {
private String name;
private int hoursWorked;
public Employee(String name, int hoursWorked) {
this.name = name;
this.hoursWorked = hoursWorked;
}
public int getHoursWorked() {
return hoursWorked;
}
public String getName() {
return name;
}
public abstract double calculatePay();
}
HourlyEmployee.java
package homework04;
public class HourlyEmployee extends Employee {
private double hourlyPay;
public HourlyEmployee(String name, int hoursWorked, double hourlyPay) {
super(name, hoursWorked);
this.hourlyPay = hourlyPay;
}
#Override
public double calculatePay() {
return getHoursWorked() * hourlyPay;
}
}
SalaryEmployee.java
package homework04;
public class SalaryEmployee extends Employee {
private static final int NUM_PAY_PERIODS = 26;
private double salary;
public SalaryEmployee(String name, int hoursWorked, double salary) {
super(name, hoursWorked);
this.salary = salary;
}
#Override
public double calculatePay() {
return salary / NUM_PAY_PERIODS;
}
}
EmployeePredicate.java
package homework04;
import java.util.function.Predicate;
public class EmployeePredicate {
public static Predicate<Employee> isHourlyEmployee() {
return p -> p.
}
}
You're looking for:
return p -> p instanceof HourlyEmployee;
but I wouldn't suggest the approach of creating a predicate for each Employee type in your EmployeePredicate factory class, instead just pass in the behavior when calling the calculateAveragePay method i.e.
double avgSalary = calculateAveragePay(employees, p -> p instanceof SalaryEmployee);
double avgHourly = calculateAveragePay(employees, p -> p instanceof HourlyEmployee);
Nevertheless, if you want to proceed with your factory class of Predicate methods because you feel it provides better readability then you can do:
public class EmployeePredicate {
public static Predicate<Employee> isHourlyEmployee() {
return p -> p instanceof HourlyEmployee;
}
}
Then the method calls to calculateAveragePay become:
double avgSalary = calculateAveragePay(employees, EmployeePredicate.isSalaryEmployee()); // create the isSalaryEmployee method
double avgHourly = calculateAveragePay(employees, EmployeePredicate.isHourlyEmployee());
As an aside, you could use the stream API to perform the calculateAveragePay making it more readable.
public static double calculateAveragePay(Employee[] employees, Predicate<Employee> pred) {
return Arrays.stream(employees)
.filter(pred)
.mapToDouble(e -> e.calculatePay())
.average().orElse(0);
}

Subclasses and Superclasses

I'm trying to build a program that has certain requirements, the main being I have a class, and then make a subclass that adds a feature. I create the class DVD, and then I create the subclass.
I'm adding a method to add the year to the list, as well as a restocking fee which will be added to the final inventory value that prints. I built the subclass, created the overriding methods, but it is not being added to the output displayed. Not only that, but it is placing the input year in the wrong place. I am not getting any errors, it just acts like the subclass doesn't exist, even though my DVD class says that some of the methods are being overridden.
I'm thinking I must be missing something where I am supposed to call the new method, and maybe I read the resource wrong, but it sounded like I only needed to call the DVD class, and the methods I wanted overridden would be overridden automatically. I'd prefer to just add this information to the superclass, but it is a requirement for an assignment.
So I'm wondering how do I actually go about calling these override methods when I need them to add these new features? I keep seeing resources telling me how to create them, but not actually implement them.
From my main method, I call the dvd class and then print it. however, it only prints what's in the original dvd class, except for the odd addition of adding the year to where the product ID should be.
public class DVD {
String name;
int id;
int items;
double cost;
//default constructor
public DVD() {
name = "";
id = 0;
items = 0;
cost = 0.0;
}//end default constructor
//constructor to initialize object
public DVD(String dvdName, int itemNum, int quantity, double price) {
name = dvdName;
id = itemNum;
items = quantity;
cost = price;
}//end constructor
//method to calculate value
public double getInventoryValue() {
return items * cost;
}
//method to set name
public void setdvdName(String dvdName){
this.name = dvdName;
}
//method to get name
public String getName(){
return name;
}
//method to set id
public void setitemNum( int itemNum){
this.id = itemNum;
}
//method to get id
public int getId(){
return id;
}
//method to set items
public void setquantity(int quantity){
this.items = quantity;
}
//method to get items
public int getItems(){
return items;
}
//method to set cost
public void setprice( double price){
this.cost = price;
}
//method to get cost
public double getCost(){
return cost;
}
/**
*
* #return
*/
public String toString() {
return "DVD Name: " + getName() +
"ID: " + getId() +
"Items: " + getItems() +
"Cost: " + getCost() +
"Total Value: " +getInventoryValue();
}
}
-
public class ExtendedDVD extends DVD{
double restockFee;
int year;
public ExtendedDVD(){
year = 0;
}
public ExtendedDVD(int year) {
this.year = year;
}
public void setRestockFee(){
this.restockFee = 0.05;
}
public double getRestockFee(){
return restockFee;
}
public void setYear(){
this.year = 0;
}
public int getYear(){
return year;
}
#Override
public double getInventoryValue(){
double value1 = super.getInventoryValue();
double value = restockFee * value1;
double totalInventoryValue = value + super.getInventoryValue();
return totalInventoryValue;
}
#Override
public String toString(){
return super.toString() + "Year" + getYear();
}
}
}
public class Inventory {
DVD[] inventory = new DVD[5];
int current = 0;
private int len;
public Inventory(int len){
inventory = new DVD[len];
}
public double calculateTotalInventory() {
double totalValue = 0;
for ( int j = 0; j < inventory.length; j++ )
totalValue += inventory[j].getInventoryValue();
return totalValue;
}
/**
*
* #param dvd
* #throws Exception
*/
public void addDVD(DVD dvd) throws Exception {
if (current < inventory.length) {
inventory[current++]=dvd;
}else {
Exception myException = new Exception();
throw myException;
}
}
void sort() {
for (DVD inventory1 : inventory) {
len = current;
}
for (int i=0; i<len;i++) {
for(int j=i;j<len;j++) {
if (inventory[i].getName().compareTo(inventory[j].getName())>0) {
DVD temp = inventory[j];
inventory[j] = inventory[i];
inventory[i] = temp;
}
}
}
}
public int getNumberOfItems() {
return current;
}
public void printInventory() {
System.out.println("Current Inventory:");
for(int i=0;i<current;i++) {
System.out.println(inventory[i]);
}
System.out.println("The total value of the inventory is:"+calculateTotalInventory());
}
}
-
public class inventoryprogram1 {
/**
* #param args the command line arguments
*/
public static void main(String[] args){
boolean finish = false;
String dvdName;
int itemNum;
int quantity;
double price;
int year = 0;
Inventory inventory = new Inventory(5);
while (!finish) {
Scanner input = new Scanner(System.in); // Initialize the scanner
System.out.print("Please enter name of DVD: ");
dvdName = input.nextLine();
if (dvdName.equals("stop")) {
System.out.println("Exiting Program");
break;
} else {
System.out.print("Please enter Product Number: ");
itemNum = input.nextInt();
System.out.print("Please enter units: ");
quantity = input.nextInt();
System.out.print("Please enter price of DVD: ");
price = input.nextDouble();
System.out.print("Please enter production year: ");
itemNum = input.nextInt();
DVD dvd= new DVD(dvdName,itemNum,quantity,price);
try {
inventory.addDVD(dvd);
}catch( Exception e) {
System.out.println("Inventory is full.");
break;
}
System.out.println("DVD: " + dvd);
}//end else
}
inventory.sort();
inventory.printInventory();
}
}
if you want to use the new methods that you wrote in ExtendedDVD you need to instantiate that class you are still calling the original dvd class so you will still get those methods.
for example
DVD dvd = new DVD(dvdName, itemNum, quantity, price);
and
DVD Dvd = new ExtendedDVD(dvdName, itemNum, quantity, price);
are two different things
also if you look in your main method you are assigning itemNum twice that is why it is showing you the year
In the main method you just instantiate a DVD object, not an ExtendedDVD object.
replace
DVD dvd= new DVD(dvdName,itemNum,quantity,price);
by something like
DVD dvd= new ExtendedDVD(year);
And obviously, you may want another constructor in ExtendedDVD

java Error Message: Missing Method Body Or Declare Abstract, how to fix this?

hello I get the error message: Missing Method Body Or Declare Abstract, how to fix this, what does this mean?
my code:
public class Mobile
{
// type of phone
private String phonetype;
// size of screen in inches
private int screensize;
// memory card capacity
private int memorycardcapacity;
// name of present service provider
private String mobileServiceProvider;
// type of contract with service provider
private int mobileTypeOfContract;
// camera resolution in megapixels
private int cameraresolution;
// the percentage of charge left on the phone
private int chargeUp;
// wether the phone has GPS or not
private int switchedOnFor;
// to simulate using phone for a period of time
private int charge;
// checks the phones remaining charge
private String provider;
// simulates changing the provider
private String GPS;
// instance variables - replace the example below with your own
private int cost;
// declares cost of the item
// The constructor method
public Mobile(String mobilephonetype, int mobilescreensize,
int mobilememorycardcapacity, String mobileServiceProvider, int mobileTypeOfContract, int mobilecameraresolution, String mobileGPS, int chargeUp,int switchedOnFor, String changeProvider,int getBalance, int cost,int price) {
// initialise the class attributes from the one given as parameters in your constructor.
}
/**
* Other constructor
*/
public Mobile (int cost){
price = 1000;
// initialise cost(?) attribute that actually doesn't seem to exist?
}
/**
*returns a field price.
*/
public int getcost()
{
return balance;
}
/**
*return the amount of change due for orders of mobiles.
*/
public int getBalance()
{
return balance;
}
/**
* Receive an amount of money from a customer.
*/
public void cost (int price)
{
balance = balance + amount;
}
//this.serviceprovider = newserviceprovider;
//this.typeofcontract = 12;
//this.checkcharge = checkcharge;
//this.changeProvider = giffgaff;
//Mobile samsungPhone = new Mobile(
// "Samsung" // String mobilephonetype
//, 1024 // intmobilescreensize
//, 2 // intmobilememorycardcapacity
//, 8 // intmobilecameraresolution
//, "GPS" //String mobileGPS
//, "verizon" // String newserviceprovider
//, "100" // intchargeUp
//, "25" // intswitchedOnFor
//, "25" // intcheckCharge
//, "giffgaff"// String changeProvider
//);
//typeofcontract = 12;
//checkcharge = checkcharge;
//Mutator for newserviceprovider
public void setmobileServiceProvider(String newmobileServiceProvider)
{
mobileServiceProvider = newmobileServiceProvider;
}
//Mutator for contracttype
public void setmobileTypeOfContract(int newmobileTypeOfContract)
{
mobileTypeOfContract = newmobileTypeOfContract;
}
//Mutator for chargeUp
public void setchargeUp(int chargeUp)
{
this.chargeUp = chargeUp;
}
//Mutator to simulate using phone for a period of time
public void switchedOnFor(int switchedOnFor)
{
this.switchedOnFor = switchedOnFor;
}
//Accessor for type of phone
public String getType()
{
return phonetype;
}
//Accessor for provider
public String getprovider()
{
return mobileServiceProvider;
}
//Accessor for contract type
public int getContractType()
{
return mobileTypeOfContract;
}
//Accessor for charge
public int getCharge()
{
return chargeUp;
}
//Accessor which checks the phones remaining charge
public int checkCharge()
{
return checkCharge;
}
// simulates changing the provider
public void changeProvider()
{
provider = changeProvider;
}
//returns the amount of change due for orders of mobiles.
public int Balance()
{
return balance;
}
// A method to display the state of the object to the screen
public void displayMobileDetails() {
System.out.println("phonetype: " + phonetype);
System.out.println("screensize: " + screensize);
System.out.println("memorycardcapacity: " + memorycardcapacity);
System.out.println("cameraresolution: " + cameraresolution);
System.out.println("GPS: " + GPS);
System.out.println("mobileServiceProvider: " + mobileServiceProvider);
System.out.println("mobileTypeOfContract: " + mobileTypeOfContract );
}
/**
* The mymobile class implements an application that
* simply displays "new Mobile!" to the standard output.
*/
public class mymobile {
public void main(String[] args) {
System.out.println("new Mobile!"); //Display the string.
}
}
public static void buildPhones(){
Mobile Samsung = new Mobile("Samsung",3,4,"verizon",8,12,"GPS",100,25,"giffgaff");
Mobile Blackberry = new Mobile("Samsung",3,4,"verizon",8,12,"GPS",100,25,"giffgaff");
}
public static void main(String[] args) {
buildPhones();
}
}
any answers or replies and help would be greatly appreciated as I cant get it to compile like it did before with no syntax errors.
Check constructor declared on line 42. It doesn't have a body.
public Mobile (int cost); {
price = 1000;
// initialise cost(?) attribute that actually doesn't seem to exist?
}
Additionally, price and a number of other fields are not declared anywhere.
remove ; from
public Mobile (int cost); {
public Mobile (int cost); {
price = 1000;
// initialise cost(?) attribute that actually doesn't seem to exist?
}
Here, you left a semicolon, delete it.
public Mobile (int cost){
price = 1000;
// initialise cost(?) attribute that actually doesn't seem to exist?
}

Method Retrieval and Inheritance Confusion

Ok,so I am getting a lot of trouble, I am still learning Java and my book has set me a task that I find common over the net, the part that I am stuck on is...
I must create a bank account program, an account holder is given a savings account (which has an interest rate and no overdraft facility), and a checking account (which has an overfraft facility of £100 and no interest).
I am not implementing the overdraft yet and am only half way to getting the withdraw and deposit function ready but my question is with the interest, I have defined in my superclass the savings account balance and the checking account balance so when working out my interest in the savings account class I cannot reference savebalance as I have made it private. I am trying to use the set.name method but i am clearly doing it wrong....
A big smile and a thank you for any one who can help or give advice!
Superclass is as follows:
public class BankDetails
{
private String customer;
private String accountno;
private double savebalance;
private double checkbalance;
//Constructor Methods
public BankDetails(String customerIn, String accountnoIn, double savebalanceIn, double checkbalanceIn)
{
customer = customerIn;
accountno = accountnoIn;
savebalance = savebalanceIn;
checkbalance = checkbalanceIn;
}
// Get name
public String getcustomername()
{
return (customer);
}
// Get account number
public String getaccountnumber()
{
return (accountno);
}
public double getcheckbalanceamount()
{
return (checkbalance);
}
public double getsavebalanceamount()
{
return (savebalance);
}
public void savewithdraw(double savewithdrawAmountIn)
{
savebalance = savebalance - savewithdrawAmountIn;
}
public void checkwithdraw(double checkwithdrawAmountIn)
{
checkbalance = checkbalance - checkwithdrawAmountIn;
}
public void savedeposit(double savedepositAmountIn)
{
savebalance = savebalance - savedepositAmountIn;
}
public void checkdeposit(double checkdepositAmountIn)
{
checkbalance = checkbalance - checkdepositAmountIn;
}
} // End Class BankDetails
Sub Class is as follows:
import java.util.*;
public class Savings extends BankDetails
{
private String saveaccount;
private double interest;
public Savings(String customerIn, String accountnoIn, float interestIn,
String saveaccountIn, double savebalanceIn)
{
super (customerIn, accountnoIn, savebalanceIn, interestIn);
saveaccount = saveaccountIn;
interest = interestIn;
}
public String getsaveaccountno()
{
return (saveaccount);
}
public double getinterestamount()
{
return (interest);
}
public void interestamount(String[] args)
{
BankDetails.getsavebalanceamount(savebalance);
interest = (savebalance / 100) * 1.75;
}
}
Use the superclass's getSaveBalance() method to access the balance (which is suspiciously-named, since you have a savings account class, but keep the balance elsewhere).
(Currently it's getsavebalanceamount(), I assume a renaming to keep with Java conventions.)
I'd recommend using consistent CamelCase when naming your getters and setters, e.g., getInterestAmount(), getSaveAccountNo(), etc.
I recommend against commenting simple getters/setters, but if you do, use Javadoc conventions, e.g.:
/** Returns current savings account balance. */
public double getSaveBalance() { ... etc ... }
I also recommend avoid unnecessary parentheses, as currently in your getters, e.g.:
public double getSaveBalance() {
return saveBalance; // No parens required.
}
I suggest you do something like this,
interface Account{
int getAccountNumber();
float getBalance();
}
public class SavingAccount implements Account, Interest{
int accountNumber;
public int getAccountNumber(){
return accountNumber;
}
float balance;
public float getBalance(){
return balance;
}
float savingInterestRate;
public float getInterestRate(){
return savingInterestRate;
}
}
public class CheckingAccount implements Account, OverDraft{
int accountNumber;
public int getAccountNumber(){
return accountNumber;
}
float balance;
public float getBalance(){
return balance;
}
}
interface Interest{
float getInterestRate();
}
interface OverDraft{
....
}

Categories

Resources