How do I call methods within a constructor? - java

Below is part of my code for class Range, and a constructor in a separate class called Tree. In this constructor, I am trying to instantiate the objects in class range over to my tree class. When I try to compile my constructor in the tree class, it says the methods I am trying to call cannot be referenced from a static context. Am I going about this the right way? I'm pretty sure this is quite an easy fix but I can't figure it out. Thanks
public class Range{
int low, high;
public Range(int plow, int phigh){
low = plow;
high = phigh;
}
public int getLow(){
return low;
}
public int getHigh(){
return high;
}
public class Tree {
String name;
public Tree(String pname, int plow, int phigh) {
name = pname;
Range.getHigh() = phigh; <---where error message is
Range.getLow() = plow;
}
}

Your code has two problems: first, getLow() and getHigh() are instance methods, not class methods. However, you call them by Range.getLow() and Range.getHigh(), meaning that you call them on the class Range. This is not allowed. First you have to create an instance of the class:
ran = new Range(...)
and then you call the methods on this instance:
ran.getHigh();
ran.getLow();
The other problem with your code is that you are trying to assing values to method calls:
Range.getHigh() = phigh;
This is not possible in Java. Java methods return values and you cannot assign to a value. That is, the method getHigh() and getLow() are meant to read the high and low value of a range, not set them. Setting these values is, in the case of the class Range, only possible by calling the constructor.
What you probably wanted to do, is add a member variable of type Range to the Tree class, and then set that variable in the constructor:
ran = new Range(plow, phigh);

You have to make an Object of Range before you can call its methods
public Tree(String pname, int plow, int phigh){
name = pname;
Range ran = new Range(phigh, plow);
}

use setter to set variable
public class Range{
static int low, high;
public Range(int plow, int phigh){
low = plow;
high = phigh;
}
public static int getLow(){
return low;
}
public static int getHigh(){
return high;
}
public static void setLow(int low) {
Range.low = low;
}
public static void setHigh(int high) {
Range.high = high;
}
and then call static methods to set values or get
public class Tree{
String name;
public Tree(String pname, int plow, int phigh){
name = pname;
Range.setHigh(phigh); //---where error message is
Range.setLow(plow);
}
}

Related

Create tasks[] an array of task

My current problem is that I am assigned to created a program that should within the private fields assign tasks[] an array of task. Then within the constructor, that creates the task[] array, giving it the capacity of INITIAL_CAPAITY, and setting numTasks to zero.
I am new and confused on I can tackle this problem
I have tried declaring it within the constructor but there has been no luck.
Task.java
public class Task {
private String name;
private int priority;
private int estMinsToComplete;
public Task(String name, int priority, int estMinsToComplete) {
this.name=name;
this.priority=priority;
this.estMinsToComplete = estMinsToComplete;
}
public String getName() {
return name;
}
public int getPriority() {
return priority;
}
public int getEstMinsToComplete() {
return estMinsToComplete;
}
public void setName(String name) {
this.name = name;
}
public void setEstMinsToComplete(int newestMinsToComplete) {
this.estMinsToComplete = newestMinsToComplete;
}
public String toString() {
return name+","+priority+","+estMinsToComplete;
}
public void increasePriority(int amount) {
if(amount>0) {
this.priority+=amount;
}
}
public void decreasePriority(int amount) {
if (amount>priority) {
this.priority=0;
}
else {
this.priority-=amount;
}
}
}
HoneyDoList.java
public class HoneyDoList extends Task{
private String[] tasks;
//this issue to my knowledge is the line of code above this
private int numTasks;
private int INITIAL_CAPACITY = 5;
public HoneyDoList(String tasks, int numTasks, int INITIAL_CAPACITY,int estMinsToComplete, String name,int priority) {
super(name,priority,estMinsToComplete);
numTasks = 0;
tasks = new String[]{name,priority,estMinsToComplete};
//as well as here^^^^^^^^
}
My expected result is to be able to print out the list through honeydo class. I need to manipulate the code a bit more after adding a few other methods.
Your problem is that your constructor parameter tasks has the same name as that field of your class.
So you assign to the method parameter in your constructor, not to the field. And luckily those two different "tasks" entities have different types, otherwise you would not even notice that something is wrong.
Solution: use
this.tasks = new String...
within the body of the constructor!
And the real answer: you have to pay a lot attention to such subtle details. And by using different names for different things you avoid a whole class of issues!
Also note: it sounds a bit strange that a class named Task contains a list of tasks, which are then strings. The overall design is a bit weird...

How do you implement an enum in an object class - Java?

This is my first time using enum in a class. I want to create a Pizza class so the user can create a Pizza object and then set the size, get the size, set the number of cheese etc.. Pizza() is the default constructor to initialize a Pizza object with no arguments. Thanks!!
package PizzaPackage;
public class Pizza {
private enum PizzaSize {
small, medium, large }
protected int numcheese;
protected int numpep;
protected int numham;
Pizza(){
PizzaSize newpizza= PizzaSize.medium; //Is this correct?
numcheese = 1;
numpep =0;
numham=0;
}
public int getnumcheese() {
return this.numcheese;
}
public int getnumpep() {
return this.numpep;
}
public int getnumham() {
return this.numham;
}
public void setSize(PizzaSize newpizza){
//???
}
public PizzaSize getSize(){
//???
}
}
Not quite.
PizzaSize is an enum, and you have declared that properly.
However, you are mistakening that PizzaSize enum for an instance member that holds this value for any particular instance of a Pizza.
You should create an additional private member variable, called private pizzaSize, and your constructor should be doing
this.pizzaSize = PizzaSize.medium;
Then, in your getSize() method, you should be returning this.pizzaSize;
Additionally, your setSize(PizzaSize newpizza) should contain this.pizzaSize = newpizza
Although you have created Enum, you forgot to have it as a instance member just like your other instance members numcheese, numpep etc.
PizzaSize newpizza;
Declare that as a member and use it.
package PizzaPackage;
public class Pizza {
private enum PizzaSize {
small, medium, large }
protected int numcheese;
protected int numpep;
protected int numham;
PizzaSize newpizza;
Pizza(){
newpizza= PizzaSize.medium; //Is this correct?
numcheese = 1;
numpep =0;
numham=0;
}
public int getnumcheese() {
return this.numcheese;
}
public int getnumpep() {
return this.numpep;
}
public int getnumham() {
return this.numham;
}
public void setSize(PizzaSize newpizza){
this.PizzaSize newpizza = newpizza;
}
public PizzaSize getSize(){
return newpizza;
}
}
//Is this correct?
Pizza(){
PizzaSize newpizza= PizzaSize.medium; //Is this correct?
numcheese = 1;
numpep =0;
numham=0;
}
Not really. Because you are restricting the scope of your PizzaSize to this constructor only. That variable of type PizzaSize no more accessible outside of constructor.
There are 2 possible solutions:
change type of your pizzasize field to PizzaSize
use ordinal method of enum values: pizzasize = newpizza.ordinal(); - it returns index of enum value in original enum.

Is it possible to declare variables in a constructor [Java]

I have been tasked to declare variables in a constructor but I am not sure how I can go about with this. The request states:
"In the constructor, create the Startrek Asteroids Resort given in the Appendix(see below)"
Lucozade,3,10
Fanta,5,2
Sprite,1,100
Coco,1,1
And here is my constructor:
public Asteroid(String nam, int rat, int cap)
{
name = nam;
rating = rat;
capacity = cap;
}
I had considered creating a text file and creating a method to read the data but I'm not sure if this is what they want.
If you want to save the parameters that are passed in you can just have variables that are declared in your class before hand and save them to these variables.
public class Asteroid {
private String name;
private int rat;
private int cap;
public Asteroid(String name, int rat, int cap) {
this.name = name;
this.rat = rat;
this.cap = cap;
}
}

Strange runtime error declaring instance of class Java

I'm making a game in java and consistenetly get the strangest bug. I have a class called weapon. Then I create an instance of it called primary. After I create an instance and call it secondary. for some strange reason, primary gets overwritten with secondary's values. My instructor and I both looked at it and couldn't figure it out. Here's the code:
public class weapon {
static String type;
static String name;
static int weight;
static int damage;
static int dodge;
weapon(String c, String n, int w, int da, int dod) {
type = c;
name = n;
weight = w;
damage = da;
dodge = dod;
}
//getters
String getType(){
return type;
}
String getName(){
return name;
}
Integer getWeight(){
return weight;
}
Integer getDamage(){
return damage;
}
Integer getDodge(){
return dodge;
}
//setters
void setType(String c){
c=type;
}
void setName(String n){
n=name;
}
void setWeight(Integer w){
w=weight;
}
void setDamage(Integer da){
damage=da;
}
void setDodge(Integer dod){
dodge=dod;
}
}
/*At the top of my main class I create both instances like this because the instances are created in if statements and I need to access them.*/
weapon primary;
weapon secondary;
//I create primary like this earlier in the code like this
primary = new weapon("primary","sword", 8, 6, -1);
//and then when I run this I get the output "sword" "Heavy Sword".
System.out.println(primary.getName());
secondary = new weapon("secondary", "huge sword", 9, 7, -2);
System.out.println(primary.getName());
All your member variables are defined as static :
static String type;
static String name;
static int weight;
static int damage;
static int dodge;
That's why the values of the second instance override the first (since static members are class veriables - there is a single copy of them across all instances of the class).
Removing the static keyword would solve the problem.
All the properties of your Weapon class are static, which means they are shared among all instances you create.
Remove static to make them instance variables instead, and you should be fine.
You have created a class with class wide variables rather than variables that are different for each object created.
Instead use:
public class weapon {
private String type;
private String name;
private int weight;
private int damage;
private int dodge;
weapon(String c, String n, int w, int da, int dod) {
I would suggest you use the following pattern when you define classes to help ensure your "class fields" and "object fields" are well described
public class <name-of-class> {
// Class fields
<private|public|protected> [final] static ....
// Object fields
private ...
All the member variables are declared as static. When you declare a member variable as static all the objects of that class shares the same copy of those variables. If one object changes value on a variable, it changes for other objects as well.
Simply remove the static keyword.
Weapon appears to be a bean class, it' better to encapsulate if properly with private member variable and public getter/setters.

How to increment a field member in a java class each time a new one is instantiated

VERY new to Java, so I am feeling like a child right now. The joys of learning a new language I guess.
Here is my Invoice Class:
public class Invoice {
//member inits
private int numberOfInvoices = 0;
private String companyName;
private double amountDue;
private String chargeDate;
private static int invoiceNumber = 0;
//constructor
public Invoice(String _companyName, double _amountDue, String _chargeDate)
{
numberOfInvoices++;
companyName = _companyName;
amountDue = _amountDue;
chargeDate = _chargeDate;
invoiceNumber = numberOfInvoices;
}
//getters
public String getCompanyName()
{
return companyName;
}
public double getAmountDue()
{
return amountDue;
}
public String getChargeDate()
{
return chargeDate;
}
public int getInvoiceNumber()
{
invoiceNumber = numberOfInvoices + 1;
return invoiceNumber;
}
//setters
public void setCompanyName(String _companyName)
{
companyName = _companyName;
}
public void setAmountDue(double _amountDue)
{
amountDue = _amountDue;
}
public void setChargeDate(String _chargeDate)
{
chargeDate = _chargeDate;
}
//helpers
public int incrementInvoices()
{
return numberOfInvoices++;
}
}
And here is the main method where I am trying to create three of these invoices, but increment the invoice number each time a new one is created.
public class InvoiceCreator {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Invoice invoice1 = new Invoice("Amazing Software", 5000.00, "January 18, 2009");
System.out.println(invoice1);
Invoice invoice2 = new Invoice("Best Programs", 4000.00, "February 18, 2009");
System.out.println(invoice2);
Invoice invoice3 = new Invoice("Champion Code", 3000.00, "March 18, 2009");
System.out.println(invoice3);
}
}
I'm also new to the IDE (netbeans), but through debugging and looking at each of the classes I created, all the fields are being initialized correctly, but the invoiceNumber = 1 on every one of them.
What am I doing incorrectly here?
You need to use a static field to generate incremental invoice numbers, not store the individual invoice numbers.
Try this:
public class Invoice {
//member inits
private static int nextInvoiceNumber = 0;
private String companyName;
private double amountDue;
private String chargeDate;
private int invoiceNumber = 0;
//constructor
public Invoice(String _companyName, double _amountDue, String _chargeDate)
{
invoiceNumber = nextInvoiceNumber;
nextInvoiceNumber++;
companyName = _companyName;
amountDue = _amountDue;
chargeDate = _chargeDate;
}
....
Declare numberOfInvoices to be static, so that there is a single value for the entire class, rather than a separate value for each instance.
private static int numberOfInvoices = 0;
You declared invoiceNumber as static, but numberOfInvoices is not static. In your constructor you are incrementing the number of invoices - which, being non-static, is initialised to 0 every time you create an instance of it. Then you assign this value to your invoice number.
The simple fix for your case is to declare the numberOfInvoices as static and invoiceNumber as non static:
private static int numberOfInvoices = 0;
private int invoiceNumber;
then you'll get the desired behaviour.
At the same time, it's worth noting that this implementation is ok for the purpose of learning the language, however it will not work for a production system, because the number will still be reset to 0 when the application exits and is restarted. In a production system, you would want to keep this number in a database or external file somewhere. You would then need to ensure that it's incremented in a thread-safe manner. In a production system, your logic would be something like this:
private int invoiceNumber;
private Object sync;
public Invoice(...) {
synchronised(sync) {
invoiceNumber = loadLastInvoiceNumberFromStorage();
invoiceNumber++;
writeLastInvoiceNumberFromStorage(invoiceNumber);
}
...
}
numberOfInvoices should be static. invoiceNumber should not be static. And you should synchronize the access to this field. See also: What is the best way to increase number of locks?
numberOfInvoices isn't the static member.
You currently increment an instance property and set it to the static property.
I suspect you want the opposite.
You could use a static field numberOfInvoices in your class, and increment it in the constructor.
Then you could have a static getter for the field.
numberOfInvoices will always be 0 when a new object is created. So, everytime you increment it and assign it to invoiceNumber, invoiceNumber gets the value 1. Instead, why dont you directly increment invoiceNumber .
use
private static int numberOfInvoices = 0;
Reason:
Static variables are related to class while nonstatic variables are related to object. As in this case you are storing the count of the object of the class so this is related to class. Thus you have to store it as static variable ( also called class variable)
For more details see here
You should declare your numberOfInvoices member as a static member :
private static int numberOfInvoices = 0;
This way all Invoice instance will share this member. If you don't declare it each Invoice instance will have their own value.

Categories

Resources