My Object isn't being called in my main function - java

I am trying to call my object via the main function. Since it needs static reference , but I somehow can't get to do it. Can someone please tell me what am I doing wrong?
private double checking;
private double saving;
public BankDisplay(double checking,double saving) // Constructor for subclass
{
checking=1000;
saving=1000;
}
public void setChecking(double checking){
this.checking=checking;
}
public double getChecking(){
return checking;
}
public void setSaving(double saving){
this.saving= saving;
}
public double getSaving(){
return saving;
}
BankDisplay checking1=new BankDisplay(checking, saving);
BankDisplay savings1= new BankDisplay(checking,saving);
When I am trying to print the object checking1 and saving1 in main it is showing "cant have a non static reference for a static function".

public BankDisplay(double checking,double saving) // Constructor for subclass
{
this.checking=checking;
this.saving=saving;
}
There is an error in constructor.
public static void main(String[] args){
BankingDisplay d1 = new BankingDisplay(100.15,200.15);
System.out.println(d1.getChecking());
}

Your constructor's method is wrong, it should be:
public BankDisplay(double checking,double saving) // Constructor for subclass
{
this.checking = checking;
this.saving = saving;
}
You also should have a toString() function in your class for you to appropriately print objects.
Such as:
public String toString() {
return String.format("Checking: %s\nSavings: %s\n", this.checking, this.saving);
}
Use like this:
System.out.println(checking1.toString());

public class BankDisplay {
private double checking;
private double saving;
public BankDisplay(double checking,double saving) // Constructor for subclass
{
this.checking= checking;
this.saving= saving;
}
public void setChecking(double checking){
this.checking=checking;
}
public double getChecking(){
return checking;
}
public void setSaving(double saving){
this.saving= saving;
}
public double getSaving(){
return saving;
}
}
public class Main {
public static void main(String[]args){
BankDisplay account1 = new BankDisplay(1000,100);
System.out.println(account1.getChecking());
}
}
This should fix your issue :D you needed this in your constructor because you were setting the constructors values, not your private variables.

Related

How to update static variable by passing the parameters of the same variable and nonstatic ones into static function in java?

package staticassignment3;
public class Booking {
private String customerEmail;
private int seatsRequired;
private static int seatsAvailable;
private boolean isBooked;
static {
seatsAvailable = 400;
}
public Booking(String customerEmail, int seatsRequired) {
this.customerEmail = customerEmail;
this.seatsRequired = seatsRequired;
}
public String getCustomerEmail() {
return this.customerEmail;
}
public void setCustomerEmail(String customerEmail) {
this.customerEmail= customerEmail;
}
public int getSeatsRequired() {
return this.seatsRequired;
}
public void setSeatsRequired(int seatsRequired) {
this.seatsRequired = seatsRequired;
}
public static int getSeatsAvailable() {
return Booking.seatsAvailable;
}
public static void setSeatsAvailable(int seatsAvailable) {
Booking.seatsAvailable = Booking.seatsAvailable - this.seatsRequired;
}
public boolean isBooked() {
if(Booking.seatsAvailable>= this.seatsRequired) {
Booking.setSeatsAvailable(seatsAvailable);
this.isBooked = true;
}
else {
this.isBooked = false;
}
return isBooked;
}
}
In the above Booking class, I want to update the static variable seatsAvailable by using the static method setSeatsAvailable but I am passing a nonstatic variable in it i.e this.seatsRequired which is not permitted. Is there any alternative to update the seatsAvailable without changing the code so much?
package staticassignment3;
public class Tester {
public static void main(String[] args) {
Booking booking1 = new Booking("jack#email.com", 100);
Booking booking2 = new Booking("jill#email.com", 350);
Booking[] bookings = { booking1, booking2 };
for (Booking booking : bookings) {
if (booking.isBooked()) {
System.out.println(booking.getSeatsRequired()+" seats successfully booked for "+booking.getCustomerEmail());
} else {
System.out.println("Sorry "+booking.getCustomerEmail()+", required number of seats are not available!");
System.out.println("Seats available: "+Booking.getSeatsAvailable());
}
}
}
}
in above Booking class i want to update seatsAvailable static variable by using setSeatsAvailable static method but i am passing nonstatic varible in it i.e this.seatsRequired which is not permitted.is there any alternate to achive the updated seatsAvailable static varibale without doing major changes in code
When calling a static method, there is no assocated object instance. So, it is not valid to use this inside a static method, since this refers to the current object (but you have none).
Specfically, this method isn't correct:
public static void setSeatsAvailable(int seatsAvailable) {
Booking.seatsAvailable = Booking.seatsAvailable - this.seatsRequired;
}
If you want to keep the method static, you could pass an additional parameter to the method – an instance of Booking – and then replace this.seatsRequired with booking.seatsRequired, like this:
public static void setSeatsAvailable(int seatsAvailable, Booking booking) {
Booking.seatsAvailable = Booking.seatsAvailable - booking.seatsRequired;
}

Do I avoid the risk of privacy leaks, if I set the instance variables to private?

I am working on a Java assignment. My professor wrote: Warning: Be sure to set the attributes of the Class in such a way to avoid the risk of any privacy leaks. I am getting confused with it. My understanding towards privacy leaks is always to use a copy constructor, but how can instance variables get privacy leaked? Is this why we always set instance variables to private?
Here is an Example in DemoClass variables are private which can not be accessed directly. You can only get these variables with getters and setters
public class DemoClass {
// you can not get these variable directly
private String stringValue;
private int integerValue;
public DemoClass(String stringValue, int integerValue) {
this.stringValue = stringValue;
this.integerValue = integerValue;
}
public void setStringValue(String stringValue) {
this.stringValue = stringValue;
}
public void setIntegerValue(int integerValue) {
this.integerValue = integerValue;
}
public String getStringValue() {
return stringValue;
}
public int getIntegerValue() {
return integerValue;
}
}
class Main {
public static void main(String[] args) {
DemoClass demoClass =new DemoClass("My String Value",120);
System.out.println(demoClass.getIntegerValue());
System.out.println(demoClass.getStringValue());
}
}
If this is your main code then the answer would be yes, that's why we set any variable except global variables to private.
class Demo {
private String Var = "100";
void Meth(String str) {
System.out.println(str + Var);
}
}
class Main {
public static void main(String[] args) {
Demo demo1 = new Demo();
demo1.Meth("10 x 10 = ");
System.out.println(demo1.Var);//Error. This variable is set to private so it cannot be accessed.
}
}
The privacy or control of your variables can only be accesed by the superclass/control block of the variable.

how to create a copy constructor to a subclass

i am trying to write a class which has an array of a subclass in the same project, and when i am trying to write a method that will add a new object to the array on condition that this object is not already in the array, and also if the specific cell is free, so the object will enter to the array.
but the problem is that i need to insert a variable to this method which is the copy constructor's object.
the problem is that in the subclass i don't know how to write the copy constructor.
so i will give a short example of 2 classes and you will show me how to write a copy constructor with them :
public class Food
{
private String _foodName;
public Food(String foodName)
{
_foodName=foodName;
}
public String getFoodName()
{
return _foodName;
}
public void showName()
{
System.out.println("The food's name is: " +_getFoodName());
}
}
public class Apple extends Food
{
private int _numOfApples;
public Apple(String name, int numOfApples)
{
super(name);
_numOfApples=numOfApples;
}
public Apple(Apple other)
{
????
}
}
how does the copy constructor should looks like ?
thank you for your help :)
By invoking the other constructor. Like,
public Apple(Apple other) {
this(other.getFoodName(), other._numOfApples);
}
I cannot help you properly because i cannot understand entirely what you are trying to do but at least i can help you correct some mistakes in your code:
public class Food
{
private String food;
public Food(String foodName)
{
food = foodName;
}
public String getFoodName()
{
return food;
}
public void showName()
{
System.out.println("The food's name is: " + getFoodName());
}
}
public class Apple extends Food
{
private int numOfApples;
public Apple(String name, int numberOfApples)
{
super(food);
numOfApples=numberOfApples;
}
public Apple(Apple copy)
{
this.name = copy.name;
this.numOfApples = copy.numOfApples;
}
}
Hope this helps.

toString not outputting, simple hierarchy class program

I have two interfaces and two classes, Order class is parent of CoffeeBagOrder, There is no compiler error it just isn't displaying and I can't see why not
Order class:
public abstract class Order implements OrderInterface {
//variables
final static double SALES_TAX = 0.1; //not initialised by constructor
int unitWeight, numberOfUnits;
public Order() {
unitWeight=0;
numberOfUnits=0;
}
public Order(int unitWeight, int numberOfUnits) {
unitWeight=unitWeight;
numberOfUnits=numberOfUnits;
}
public void numberOfItems(int number) {
numberOfUnits=number;
}
public void unitWeight(int weight) {
unitWeight=weight;
}
}
CoffeeBagOrder class
public class CoffeeBagOrder extends Order implements Sales {
final static double PRICE_PER_KG = 5.55;
double salesBeforeTax;
double tax;
double totalSales;
public CoffeeBagOrder() {
}
public CoffeeBagOrder(int unitWeight, int numberOfUnits) {
super(unitWeight,numberOfUnits);
}
public double calculateSalesBeforeTax() {
salesBeforeTax= unitWeight*numberOfUnits*5.50;
return salesBeforeTax;
}
public double calculateSalesTax() {
tax=salesBeforeTax*0.10;
return tax;
}
public double calculateTotalSales() {
totalSales=salesBeforeTax+tax;
return totalSales;
}
//Override
public String toString() {
return "Price before tax: "+calculateSalesBeforeTax()+"\nTax: "+calculateSalesTax()+"\nTotal price: "+calculateTotalSales();
}
}
main
import java.util.Scanner;
public class Tester {
public static void main (String[] args) {
Scanner sc= new Scanner(System.in);
System.out.print("Enter number of bags sold: ");
int unitWeight=sc.nextInt();
System.out.print("Enter weight of bags in kilograms: ");
int numberOfUnits=sc.nextInt();
CoffeeBagOrder customer=new CoffeeBagOrder(unitWeight,numberOfUnits);
customer.toString();
}
}
I have omitted the interfaces but they are followed accordingly , thanks in advance, also I am unsure if I have efficiently written the constructors as they are both the same?
Change your Order class constructor like below (check this.):
public Order(int unitWeight, int numberOfUnits) {
this.unitWeight=unitWeight;
this.numberOfUnits=numberOfUnits;
}
You were not updating class field in constructor! It was assigning the parameter to itself.
And modify toString in CoffeeBagOrder like below (check annotation):
#Override
public String toString() {
return "Price before tax: "+calculateSalesBeforeTax()+"\nTax: "+calculateSalesTax()+"\nTotal price: "+calculateTotalSales();
}
Always use #Override annotation when you intend to override, to take it effect, which is best practice rather than calling toString() explicitly.
And print using
System.out.println(customer);

Calling an external class object from function on main class

I am writing a program that keeps track of different transactions
done over time. I have a main class, and also another class named
CheckingAccount.java.
I have a main class formatted this way.
public class Main
{
public static void main (String[] args)
{
CheckingAccount c = new CheckingAccount(bal);
--line of code---
--line of code---
--line of code---
}
public static int getTransCode()
{
--line of code---
}
public static double getTransAmt()
{
--line of code---
}
public static void processCheck(double trAm, int tCode, boolean monthCh)
{
double curCharge=0.15;
CheckingAccount.setBalance(trAm,tCode,curCharge,monthCh);
CheckingAccount.setServiceCharge(curCharge);
}
public static void processDeposit(double trAm, int tCode, boolean monthCh)
{
double curCharge=0.10;
CheckingAccount.setBalance(trAm,tCode,curCharge,monthCh);
CheckingAccount.setServiceCharge(curCharge);
}
}
This is my CheckingAccount.java
public class CheckingAccount
{
private double balance;
private double totalServiceCharge;
public CheckingAccount(double initialBalance)
{
balance = initialBalance;
totalServiceCharge = totalServiceCharge;
}
public double getBalance()
{
return balance;
}
public void setBalance(double tAm, int Code, double charge, boolean mChrg)
{
if(tCode == 1)
balance = (balance - tAm) - charge;
else //if(tCode == 2)
balance = (balance + tAm) - charge;
}
public double getServiceCharge()
{
return totalServiceCharge;
}
public void setServiceCharge(double currentServiceCharge)
{
totalServiceCharge = totalServiceCharge+currentServiceCharge;
}
}
So the lines I can't get to work are CheckingAccount.setBalance() and CheckingAccount.setServiceCharge() inside the functions on my main class. What I'm trying to do is to call the the methods I created (setBalance, and setServiceCharge) in my class, from functions that I created on my main class (processCheck, and processDeposit).
But I cannot get it to run, I keep running with these error messages.
non-static method setBalance(double,int,double,boolean) cannot be referenced from a static context
CheckingAccount.setBalance(trAm,tCode,curCharge,monthCh);
You are calling your setBalance through classname which is wrong.... setBalance() method is non-static, so it is defined to specific instance of the class, not for a class..
**CheckingAccount.setBalance(trAm,tCode,curCharge,monthCh);
CheckingAccount.setServiceCharge(curCharge);**
You need to create an instance of CheckingAccount to call the method..
Secondly, in your constructor of CheckingAccount class, you haven't passed any argument for totalService, but you are setting one with an unknown variable..
You will get a compiler error there..
Either you need to initialize your totalServiceCharge with a fixed value or, you can pass it as an argument from main.. And change your constructor as below..
public CheckingAccount(double initialBalance, ** double totalServiceCharge)
{
balance = initialBalance;
this.totalServiceCharge = totalServiceCharge;
}
Then from main, call it like this: -
CheckingAccount ca = new CheckingAccount(bal, totalServiceCharge);
One of the possible solution is:
You need to create object for CheckingAccount before calling method.
Example:
public static void processDeposit(double trAm, int tCode, boolean monthCh)
{
double curCharge=0.10;
CheckingAccount ca = new CheckingAccount();
ca.setBalance(trAm,tCode,curCharge,monthCh);
ca.setServiceCharge(curCharge);**
}
Another way is, change setBalance method as static method.
public static void setBalance(double tAm, int Code, double charge, boolean mChrg)
{
if(tCode == 1)
balance = (balance - tAm) - charge;
else //if(tCode == 2)
balance = (balance + tAm) - charge;
}
I think first approach makes more sense than second approach.
CheckingAccount.setBalance and CheckingAccount.setServiceCharge are not static methods (and in this context, they shouldn't be).
You need to pass a reference of the account to your methods...
public static void processCheck(CheckingAccount ca, double trAm, int tCode, boolean monthCh)
{
double curCharge=0.15;
ca.setBalance(trAm,tCode,curCharge,monthCh);
ca.setServiceCharge(curCharge);**
}
public static void processDeposit(CheckingAccount ca, double trAm, int tCode, boolean monthCh)
{
double curCharge=0.10;
ca.setBalance(trAm,tCode,curCharge,monthCh);
ca.setServiceCharge(curCharge);
}
The you would be able to do something like...
public static void main (String[] args)
{
CheckingAccount c = new CheckingAccount(bal);
processCheck(ca, 100.0, 1, false);
}

Categories