Is it possible to declare variables in a constructor [Java] - 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;
}
}

Related

Java parent's private attribute inside child constructor

The title says it all, I got a class in which the variables of the constructor must be private.
public class AdMedia {
private String name;
private int price;
public AdMedia(){}
public AdMedia(String name, int price) {
this.name = name;
this.price = price;
}
that comes with public getter setter of the variables of course.
Now the problem comes right after I try to make a child class named Magazine. The class should inherit the name and price but the price is constant for every object initiation. so they won't be on the constructor as the name.
public class Magazine extends AdMedia {
private int area;
private String position;
private String topics;
public Magazine() {}
public Magazine(String name, int size, String position, String topic){
super();
this.size = size;
this.position = position;
this.topic = topic;
}
that also comes with its own getter setter too.
I try to put the price inside the constructor but the constructor demand a passed parameter. Using super(name) also notifies that none of parent constructor have such shape.
This complicates me when I'm trying to get the name using parent class method getName() which might require some downcasting I guess?
I had try to search for the solution but most require me to change the variable's accessibility into protected . Would there be no other way to do it in private ?
EDIT :
I forgot to mention that the result by doing what I wrote above is the unability to access Magazine name, so when I try to downcast-get the name, what returned is a null.
You could write your child constructor either as
public Magazine(String name, int size, String position, String topic){
super();
setName(name);
setPrice(100); // 100 is your constant price
this.size = size;
this.position = position;
this.topic = topic;
}
or as
public Magazine(String name, int size, String position, String topic){
super(name, 100); // 100 is your constant price
this.size = size;
this.position = position;
this.topic = topic;
}
Both ways would however open the possibility to change the price later:
Magazine m = new Magazine("name", 50, "position", "topic");
m.setPrice(10);
If you need to prevent this, you should also override the setPrice() setter:
public class Magazine extends AdMedia {
...
#Override
public void setPrice(int price) {
// what to do here?
// * you could either silently ignore
// (which might surprise some users expecting to be able to change the price)
// * throw an UnsupportedOperationException
// (which might surprise other users which are not prepared to handle such an exception)
}
}

How do I call methods within a constructor?

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);
}
}

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.

Java - Using Accessor and Mutator methods

I am working on a homework assignment. I am confused on how it should be done.
The question is:
Create a class called IDCard that contains a person's name, ID number,
and the name of a file containing the person's photogrpah. Write
accessor and mutator methods for each of these fields. Add the
following two overloaded constructors to the class:
public IDCard() public IDCard(String n, int ID, String filename)
Test your program by creating different ojbects using these two
constructors and printing out their values on the console using the
accessor and mutator methods.
I have re-written this so far:
public class IDCard {
String Name, FileName;
int ID;
public static void main(String[] args) {
}
public IDCard()
{
this.Name = getName();
this.FileName = getFileName();
this.ID = getID();
}
public IDCard(String n, int ID, String filename)
{
}
public String getName()
{
return "Jack Smith";
}
public String getFileName()
{
return "Jack.jpg";
}
public int getID()
{
return 555;
}
}
Let's go over the basics:
"Accessor" and "Mutator" are just fancy names fot a getter and a setter.
A getter, "Accessor", returns a class's variable or its value. A setter, "Mutator", sets a class variable pointer or its value.
So first you need to set up a class with some variables to get/set:
public class IDCard
{
private String mName;
private String mFileName;
private int mID;
}
But oh no! If you instantiate this class the default values for these variables will be meaningless.
B.T.W. "instantiate" is a fancy word for doing:
IDCard test = new IDCard();
So - let's set up a default constructor, this is the method being called when you "instantiate" a class.
public IDCard()
{
mName = "";
mFileName = "";
mID = -1;
}
But what if we do know the values we wanna give our variables? So let's make another constructor, one that takes parameters:
public IDCard(String name, int ID, String filename)
{
mName = name;
mID = ID;
mFileName = filename;
}
Wow - this is nice. But stupid. Because we have no way of accessing (=reading) the values of our variables. So let's add a getter, and while we're at it, add a setter as well:
public String getName()
{
return mName;
}
public void setName( String name )
{
mName = name;
}
Nice. Now we can access mName. Add the rest of the accessors and mutators and you're now a certified Java newbie.
Good luck.
You need to remove the static from your accessor methods - these methods need to be instance methods and access the instance variables
public class IDCard {
public String name, fileName;
public int id;
public IDCard(final String name, final String fileName, final int id) {
this.name = name;
this.fileName = fileName
this.id = id;
}
public String getName() {
return name;
}
}
You can the create an IDCard and use the accessor like this:
final IDCard card = new IDCard();
card.getName();
Each time you call new a new instance of the IDCard will be created and it will have it's own copies of the 3 variables.
If you use the static keyword then those variables are common across every instance of IDCard.
A couple of things to bear in mind:
don't add useless comments - they add code clutter and nothing else.
conform to naming conventions, use lower case of variable names - name not Name.

how to set method become array?

I have a class file name serializedObject, I will like to call this class file in another class file and use it's method.
I want to declare the class file became and array to being use in another class file.
Then I declare something like below:
serializedObject[] setData = new serializedObject[10];
and use it into a for loop
for(int i=0; i<clientInfo.length; i++)
{
double locationX = clientInfo[i].getLocation().getX();
double locationY = clientInfo[i].getLocation().getY();
String name = clientInfo[i].getName();
double mood = clientInfo[i].getMood();
double hunger = clientInfo[i].getHunger();
double chargestate = clientInfo[i].getChargestate();
setData[i].setAll(locationX, locationY, name, mood, hunger, chargestate);
System.out.println(setData[i].getName());
}
In the serializedObject class I have the set method and also get method,
but seems like not work for this. What can i do instead of this way to get an array method?
Thanks for any comment and help.
The system seems like cant really set my value into the method,
i cant get the any value from the
System.out.println(setData[i].getName());
but the system doesn't have any compile error.
Here will be my serializedObject class file
public class serializedObject
{
public static double locationX;
public static double locationY;
public static String name;
public static double mood;
public static double hunger;
public static double chargestate;
public serializedObject()
{
}
public void setAll(double locationX,double locationY, String name,double mood,double hunger, double chargestate)
{
this.locationX = locationX;
this.locationY = locationY;
this.name = name;
this.mood = mood;
this.hunger = hunger;
this.chargestate = chargestate;
}
public String getName()
{
return this.name;
}
public double getLocationX()
{
return this.locationX;
}
public double getLocationY()
{
return this.locationY;
}
public double getMood()
{
return this.mood;
}
public double getHunger()
{
return this.hunger;
}
public double getChargestate()
{
return this.chargestate;
}
}
Note that this serializedObject[] setData = new serializedObject[10]; will just create the array. All elements are still null thus calling methods on those elements (like getName()) will result in a NullPointerException. You'd have to initialize the elements first: setData [0] = new serializedObject(); then you call call methods on the element.
First of all, by convention, the initial letter of a class name should be capitalized as such, SerializedObject. In your for-loop, you'll need to do the following:
for(int i = 0; i < clientInfo.length; i++)
{
// Construct new serialized object
setData[i] = new SerializedObject();
// Extract client information
double locationX = clientInfo[i].getLocation().getX();
double locationY = clientInfo[i].getLocation().getY();
String name = clientInfo[i].getName();
double mood = clientInfo[i].getMood();
double hunger = clientInfo[i].getHunger();
double chargestate = clientInfo[i].getChargestate();
// Store information in serialized object
setData[i].setAll(locationX, locationY, name, mood, hunger, chargestate);
// Add serialized object to array
System.out.println(setData[i].getName());
}
Note: At the moment, your program should be throwing a NullPointerException, which should have let you know that the elements within setData are null.
public static double locationX;
public static double locationY;
public static String name;
public static double mood;
public static double hunger;
public static double chargestate;
These properties are all static. That means they will be shared between all instances of serializedObject. Therefore, if you do setAll on one instance, it will seem to change every other instance.
You should make these instance members:
public double locationX;
public double locationY;
public String name;
public double mood;
public double hunger;
public double chargestate;
Fields should usually not be public, but that's a separate discussion.

Categories

Resources