Trying to get default value from the data definition class - java

Please consider two classes :
Data Definition Class :
public class A {
private int amount = 1000;
public A(int amount){
this.amount = amount
}
public int getAmount(){
return amount ;
}
}
Main Class :
public class B {
public static void main (String arg[]){
A a = new A(2000);
System.out.println("Amount:"+a.getAmount());
}
}
Since I am passing 2000 to the constructor, I am getting 2000 in the output. But I would like to keep a option of if the user doesn't specifiy any amount, it should print
the default value which is 1000 as mentioned in the private variable in data definition class.
Is there a way I can accomplish my task using the constructor?

public class A {
private int amount;
public A() {
amount = 1000;
}
public A(int amount) {
this.amount = amount;
}
public int getAmount() {
return amount;
}
}

You just need to create an empty constructor
public A(){
}
And in your main you will be able to do this:
A a = new A();

You can provide default constructor along with the one argument constructor you mentioned. This way user don't have to pass the amount if he don't want to while creating the object.

Create an empty constructor
public class A {
private int amount = 1000;
public A(){
}
public A(int amount){
this.amount = amount;
}
public int getAmount(){
return this.amount;
}
}

Related

Java calling method in another class

I am trying to create a Java class with certain number of pizzas that decreases in number
if someone steals it.
I have two classes.
class House where pizza is,
public class House {
private static int totalPizzas;
public House() {
totalPizzas = totalPizzas;
}
public int getTotalPizzas() {
return totalPizzas;
}
public static void setTotalPizzas(int totalPizzas) {
totalPizzas = totalPizzas - Thief.stealPizza(House stolenPizza);
}
}
and class Thief that steals the pizza.
public class Thief {
private String name;
private int age;
public Thief() {
name = "abc";
age = 11;
}
public static void stealPizza(House stolenPizza) {
???????
}
}
My main concern is the ??????? part where I feel like I should set stolenPizza to certain
integers but
stolenPizza = 1;
certainly does not work.
Could someone give me a bit of advice on how I should approach this?
Thank you very much for reading.
One way to do it would be to do something like:
public class Thief {
private String name;
private int age;
public Thief() {
name = "abc";
age = 11;
}
public static void stealPizza() {
House.setTotalPizzas(House.totalPizzas - 1);
}
}
public class House {
private static int totalPizzas;
public House() {
totalPizzas = totalPizzas;
}
public int getTotalPizzas() {
return totalPizzas;
}
public static void setTotalPizzas(int totalPizzas) {
House.totalPizzas = totalPizzas;
}
}
Your constructor is missing something if I understand your code right:
Your code
public House() {
totalPizzas = totalPizzas;
}
will set the amount of totalPizzas on itself without assigning any "real" integer value to it. Try
public House(int totalPizzas) {
totalPizzas = totalPizzas;
}
so that you actually can assign a number of Pizzas to the house when calling the constructor, for example:
House house = new House (12);
if you want to have 12 Pizzas in the house.

Check value in subclass before sending it to private superclass variable

I somehow need to check the value of a variable amount being received in the subclass before sending it to the superclass.
This is what I have for my superclass
//superclass
public class Account
{
private double balance;
public Account( double amount )
{
balance = amount;
}
public Account()
{
this(0.0);
}
public void deposit( double amount )
{
balance += amount;
}
public void withdraw( double amount )
{
balance -= amount;
}
public double getBalance()
{
return balance;
}
}
This is what I have for my subclass
public class SafeAccount extends Account
{
public SafeAccount(double amount)
{
// something to check if amount is positive before sending it to
super
// if it's not positive, use no argument constructor to set balance ==
0.0
}
}
I think I am supposed to use "this(amount)" to somehow check it, but I'm not exactly sure how that will work.
super() must be the first statement in a constructor body so you cannot perform checks before it.
Simple work around:
public class SafeAccount extends Account
{
public SafeAccount(double amount)
{
super(Math.max(0.0, amount));
}
}
If you really must use the no arg constructor a more complex work around would be:
public class Account {
Account() {
}
Account(double x) {
}
}
public class SafeAccount extends Account {
private SafeAccount() {
}
private SafeAccount(double amount) {
super(amount);
}
public static SafeAccount boo(double x) {
if (x < 0.0) {
return new SafeAccount();
}
return new SafeAccount(x);
}
}
Use private constructors in your subclass to prevent instantion from constructor and supply a factory method that does the checks you want.
You can use following statement
class SafeAccount extends Account {
public SafeAccount(int balance) {
super(balance > 0? balance: 0);
}
}
But in general such Inheritance hierarchy needs to be rechecked for correctness of design.

How can I create an array of instances accessible in a class?

I am writing a code that create an array of instances of Account object in another class (Bank).
I am initializing the array inside the main method, but it is not accessible inside the Bank class.
What I want to do is create 4 instances of the Account class and to be able to perform all tasks inside the Bank class methods. Is there a way that I can do this?
this is my code
Account.java
package question1;
import java.util.Date;
public class Account {
public int AccountNum;
public double BALANCE;
public Date OPENDATE;
public String OwnerName;
public Account() {
// TODO Auto-generated constructor stub
}
public Account(int accnum, double balance, Date opendate, String ownername) {
this.AccountNum = accnum;
this.BALANCE = balance;
this.OPENDATE = opendate;
this.OwnerName = ownername;
}
public int getAccountNum() {
return AccountNum;
}
public void setAccountNum(int accountNum) {
AccountNum = accountNum;
}
public double getBALANCE() {
return BALANCE;
}
public void setBALANCE(double bALANCE) {
BALANCE = bALANCE;
}
public Date getOPENDATE() {
return OPENDATE;
}
public void setOPENDATE(Date oPENDATE) {
OPENDATE = oPENDATE;
}
public String getOwnerName() {
return OwnerName;
}
public void setOwnerName(String ownerName) {
OwnerName = ownerName;
}
public double yearlyInterest(double balace) {
return balace;
}
}
Bank.java
package question1;
public class Bank {
public static void main(String[] args) {
Account[] acc = new Account[4];
for(int i = 0 ; i<acc.length; i++){
acc[i] = new Account();
System.out.println(acc[i].toString());
}
/// how to continue form here ??
}
}
Call the constructor of the Account class. Now you can set all arguments as desired. Afterwards, you can add the instance to any array or collection.
List<Account> accounts = new ArrayList<Account>(4);
Account myAccount = new Account(123, 100.5, new Date(), "dev leb");
accounts.add(myAccount);
You probably want to have a property of an Account array in your class.
You can set your property in the class body:
public class Bank {
//Set your property here.
private Account[] _acc;
//Initialize in ctor.
public Bank() {
_acc = new Account[4];
}
//....
//You can then use it as a property in your code.
//If needed outside the class, set up setter and getter methods,
//avoiding violating encapsulation.
public Account[] getAcc(){
return _acc;
}
public void setAcc(Account acc){
this._acc = acc;
}
//If you need this to be used inside main, then you must instantiate a
//Bank in main and then make all the appropriate operations there.
public static void main(String[] args) {
Bank bank = new Bank();
Account[] bankAccounts = bank.getAcc();
//....
}
}
My suggestion though is that you use an ArrayList instead:
Set the property:
private List<Account> acc;
And in constructor:
acc = new List();
In order to add an account in a class method:
acc.add(new Account());
In order to retrieve an element by indexing:
acc.get(0);
for more information, look at the ArrayList JavaDoc.
If you are not able to understand why your array that is defined inside the main is not accessible inside your Bank class, then I suggest you search more about Object-Oriented programming, Class definition, instantiation and properties accessibility and manipulation and static methods in Java.

Private access errors

I'm having trouble with a problem I'm working on for class.
The errors occurring are
TC1.java:17: error: myQuantity has private access in CheckItem
items[i].myQuantity=quantities[i];
and
TC1.java:20: error: myPrice has private access in CheckItem
a[i]=items[i].myPrice*((items[i].mySalesTax\100)+1);
This is the code I currently have.
public class CheckItem
{
private double myPrice,
mySalesTax;
private int myQuantity = 1;
public CheckItem( double price, double salesTax )
{
myPrice = price;
mySalesTax = salesTax;
}
public int getQuantity()
{
return myQuantity;
}
public void setQuantity( int qty )
{
myQuantity = qty;
}
public double lineItemTotal()
{
return roundMoney((myPrice*myQuantity)*((mySalesTax/100)+1));
}
public static double roundMoney( double amount )
{
return (int)(100 * amount + 0.5) / 100.0;
}
public static void setQuantities( CheckItem[] items, int[] quantities )
{
for (int i=0;i<quantities.length;i++){
items[i].myQuantity=quantities[i];
}
}
public static double[] lineItemTotals( CheckItem[] items )
{
double[] a=new double[items.length];
for (int i=0;i<items.length;i++){
a[i]=items[i].myPrice*((items[i].mySalesTax/100)+1);
}
return a;
}
}
The problem is that static methods can't access private instance variables. Define getters and setters for those variables, and use them:
items[i].setQuantity(quantities[i]);
a[i]=items[i].getPrice()*((items[i].getSalesTax()\100)+1);
and it will work.
This code compiles fine. If you are trying to access private members outside this class you would get private access error during compilation. In that case standard fix is to provide setters and/or getters.
** EDIT **
Seems like there is confusion about allowed access. You can NOT access any instance variables from static methods/context DIRECTLY! But you CAN access instance variables via instance itself as shown here:
class Test {
private int s = 123;
void instPrint() {
System.out.println(s); // fine
}
static void statPrint(Test ss) {
System.out.println(ss.s); // this is fine too!
// System.out.println(s); // does not compile obviously
}
}
This is the same case as in the code above. This has nothing to do with access modifiers because it's all happening in the same class.
Your code declares these two member variables in class CheckItem with the private scope. This means no other classes can access them directly on a CheckItem instance:
private double myPrice,
mySalesTax;
If you want class TC1 to be able to read or modify them, declare them in CheckItem.java as public. Alternatively, and generally a better practice, you could add public methods to CheckItem.java to allow other classes to access their values:
public double getMyPrice() {
return this.myPrice;
}
public void setMyPrice(double price) {
this.myPrice = price;
}
public double getMySalesTax() {
return this.mySalesTax;
}
public void setMySalesTax(double st) {
this.mySalesTax = st;
}
public int getMyQuantity() {
return this.myQuantity;
}
public void setMyQuantity(int newQty) {
this.myQuantity = newQty;
}
Then, in TC1.java you'd use these methods instead of direct access:
items[i].setMyQuantity(quantities[i]);
and
a[i]=items[i].getMyPrice()*((items[i].getMySalesTax()\100)+1);

Returning a String for a Super class' abstract method to display

The abstract method statement (in the super class) must be implemented to return a string representation of a statement.
So I've done the following:
public abstract String statement(); //The abstract method in my super class
..and the method in my subclass:
//#Override
public String statement()
{
return String.format("Account no %d has balance R%d and minimum balance R%d", accountNumber,balance,getMinBalance());
}
My main class just calls the Account class (the super class in question) as follows:
new SavingsAccount(Integer.toString(ao[i]),ao[i+1],ao[a]); //ao being the array which contains the values.
However, the console just terminates without displaying anything (I'm also not familiar with implementation).
Here's the full code:
Main:
public class AccountList
{
public static void main(String[] args)
{
int[] ao = {00000,0,0,12345,500,250,23456,230,-50,34567,340,500,45678,-320,-50,56789,-320,-500};
for(int i=0;i<ao.length;i=i+3)
{
int a = i+2;
if(ao[a]>=0)
{
new SavingsAccount(Integer.toString(ao[i]),ao[i+1],ao[a]);
}
if(ao[a]<=0)
{
new ChequeAccount(Integer.toString(ao[i]),ao[i+1],ao[a]);
}
}
}
}
Super class:
public abstract class Account implements InterestAccount
{
static String accountNumber;
int balance;
public Account()
{
accountNumber = "00000";
balance = 0;
//statement();
}
public Account(String accountNumber,int balance)
{
setAccountNum(accountNumber);
setBalance(balance);
}
public void setAccountNum(String accNum)
{
accountNumber = accNum;
}
public void setBalance(int balance)
{
this.balance = balance;
}
public String getAccountNumber()
{
return accountNumber;
}
public int getBalance()
{
return balance;
}
public abstract String statement();
}
One of the sub-classes:
public class SavingsAccount extends Account
{
int minBalance;
public SavingsAccount()
{
super();
minBalance = 0;
}
public SavingsAccount(String accountNum,int minBalance,int balance)
{
super(accountNum,balance);
setMinBalance(minBalance);
}
public void setMinBalance(int minBalance)
{
this.minBalance = minBalance;
}
public int getMinBalance()
{
return minBalance;
}
#Override
public int calculateInterest(int value) {
if(minBalance>balance)
{
return 0;
}
else
{
return (minBalance*balance)/100;
}
}
//#Override
public String statement()
{
return String.format("Account no %d has balance R%d and minimum balance R%d", accountNumber,balance,getMinBalance());
}
}
You never calls the method statement.
1) create a new SavingsAccount object
new SavingsAccount(Integer.toString(ao[i]),ao[i+1],ao[a]);
2) Constructor class got call by above statement
public SavingsAccount(String accountNum,int minBalance,int balance)
{
super(accountNum,balance);
setMinBalance(minBalance);
}
3) Subclass then call superclass method
public Account(String accountNumber,int balance)
{
setAccountNum(accountNumber);
setBalance(balance);
}
4) SetBalance is called
public void setBalance(int balance)
{
this.balance = balance;
}
5) setMinBalance called
public void setMinBalance(int minBalance)
{
this.minBalance = minBalance;
}
6) End of create object SavingsAccount
No single statement calling the method statement
It might help to know more of your code, but from what I see, there are some possible cases:
Your code runs and terminates without an error. Reason you don't see anything is, there is nothing written to the standard output stream (e.g. via System.out.println()).
Your code has some internal problems, which cause an exception, which again is not shown due to a broken logging mechanism.
In any case, use a debugger to step through you code and determine which parts run perfectly and if any fail. It might help to extract some local variables, give them proper meaningful names and watch their contents during execution.

Categories

Resources