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.
Related
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);
}
}
I need a bit of help here. so i have this. I was basically wondering when you create an array of object of a parent class, then change that object to a child class, can I access the methods of that child class and if not why. thanks for any help.
public class Racer {
private String name;
private int position;
// Constructor
public Racer()
{}
public Racer(String name)
{
this.name = name;
position = 0;
}
public String getName()
{
return name;
}
public int getPosition()
{
return position;
}
public void setPosition(int n)
{
position = n;
}
public void setName(String n){
this.name=n;
}
}
the child class
public class Spartiates extends Racer{
private int energy;
public Spartiates(){
super();
}
public Spartiates(String name){
setName(name);
setPosition(20);
energy=100;
}
public void setEnergy(int energy){
this.energy=energy;
}
public int getEnergy(){
return energy;
}
}
main class
public class demo{
public static void main(String[] args){
Racer [] player = new player[3];
for(int i=0; i<player.length; i++){
player[i] = new Spartiates();
}
System.out.println(player[1].getEnergy());
}
so here the problem the getEnergy method doesn't work so I was wondering why. If anybody can help it would be very much appreciated. thanks
This is discussed here:
Is it possible to call subclasses' methods on a superclass object?
Along with all the reasons why doing something like this is probably never a good idea :).
You'll have to cast it to an instance of the subclass. If you plan on having a mixed array of object instances you'd need to first check the type:
System.out.println(((Racer)player[1]).getEnergy());
You need either define the function in the superclass or cast the object to the subclass.
If you intend the array to hold ONLY elements of the subclass Spartiates, then declare it as such.
Otherwise, if it needs to hold objects of both type, there only way to do this is to check with instanceof.
if (player[1] instanceof Spartiates)
System.out.println(((Spartiates)player[1]).getEnergy());
else
// handle other types
The reason energy is 0 is because you are calling your empty (no arg) constructor:
player[i] = new Spartiates();
which does not initialize the energy variable (so it will be 0 by default). You only set the variable to 100 in the constructor which takes in a String, namely here:
public Spartiates(String name){
setName(name);
setPosition(20);
energy=100;
}
So either call that constructor in the for loop with some string as an argument, or call your setEnergy() setter with some value after creating the object with the empty constructor.
Also, this is wrong:
Racer [] player = new player[3];
It should read:
Racer [] player = new Racer[3];
or:
Racer [] player = new Spartiates[3];
Am trying to use Enum as Constants for readability as below .
Public enum x { test1 , test2 , test3 }
I want to pass this enum into a method and use it as a int value as shown
private void (int type)
{
switch(int)
{
case enum.X:
// do somthing
break;
}
} ;
Can we use enum here as its more clearer than using a int value .( like switch 1 etc) . Is it possible to use this way.?
Yes, you should be able to use an enum in a switch statement in Java:
public enum SomeEnum { FOO, BAR, BAZ };
// in a class...
private void something(SomeEnum s) {
switch (s) {
case FOO:
// do something
break;
case BAR:
// do something else
break;
}
}
Not sure I understand how int values tie into this, but you can have fields/methods on an enum like in a normal Java class, and can use these to hold int (or any other type) values as on any other POJO.
Here's an example in which we declare a constructor for an enum class, so that you can pass in values for internal variables at the time each instance of the enum is constructed. To help you follow what's going on: First we declare the items in the enum - each declaration invokes the constructor, so we can pass in instance variables here. Then the code for the enum class follows, as with a normal Java class.
public enum AnotherEnum {
ONE(1, "un"), TWO(2, "deux"), THREE(3, "trois"), FIFTY_SEVEN(57, "cinquante-sept");
private final int someInt;
private final String french;
private AnotherEnum(int i, String s) {
this.someInt = i;
this.french = s;
}
public int getSomeInt() {
return this.someInt;
}
public String getFrench() {
return this.french;
}
}
So for example, System.out.println(AnotherEnum.TWO.getSomeInt()) would print 2, and System.out.println(AnotherEnum.FIFTY_SEVEN.getFrench()) would print cinquante-sept.
No, you cannot say:
case Enumerator.ordinal():
But you could say:
switch(EnumObject.values()[intVar]) {
case Enumerator1:
...
}
Another way you can do this by doing a little more work with you enum class.
public enum Foo {
X (1),
Y (2);
private int value;
Foo (int value)
{
this.value = value;
}
}
Now all you need to do is:
switch (int)
{
case Foo.X: doSomething ();break;
case Foo.Y: doSomething ();break;
}
in an interface, I store constants in this way (I'd like to know what you think of this practice). This is just a dummy example.
interface HttpConstants {
/** 2XX: generally "OK" */
public static final int HTTP_OK = 200;
public static final int HTTP_CREATED = 201;
public static final int HTTP_ACCEPTED = 202;
public static final int HTTP_NOT_AUTHORITATIVE = 203;
public static final int HTTP_NO_CONTENT = 204;
public static final int HTTP_RESET = 205;
public static final int HTTP_PARTIAL = 206;
...
}
Is there a way I can iterate over all constants declared in this interface ?
Using reflection:
Field[] interfaceFields=HttpConstants.class.getFields();
for(Field f:interfaceFields) {
//do something
}
But anyway, if you can redesign your class, I would recomend you to handle a static enum constants construction. So, suposing your class will contain always an int value for every constant:
enum HttpConstants {
HTTP_OK(200), HTTP_CREATED(201), HTTP_ACCEPTED(202),
HTTP_NOT_AUTHORITATIVE(203),HTTP_NO_CONTENT(204),
HTTP_RESET(205), HTTP_PARTIAL(206) /* ... */;
private int value;
HttpConstants(int aValue) {
value=aValue;
}
public int getValue() {
return value;
}
}
Then, to loop on it:
for(HttpConstants val: HttpConstants.values()) {
int value=val.getValue();
//...
}
Thus, avoiding the access to the reflection API.
I would create these constants as an enumeration. Enums in Java can have their own fields and methods, which very convenient for your case. So I would do this the following way:
enum HttpConstant {
HTTP_OK(200),
HTTP_CREATED(201),
HTTP_ACCEPTED(202),
HTTP_NOT_AUTHORITATIVE(203),
HTTP_NO_CONTENT(204),
HTTP_RESET(205),
HTTP_PARTIAL(206);
private final int id;
HttpConstant(int id) {
this.id = id;
}
int getId() {
return id;
}
}
Now the iteration is easy:
for (HttpConstant constant : HttpConstant.values()) {
//Do something with the constant
}
This way it is also easy to add associate some new values with the constants, you just have to add new fields.
Right now you may use reflection:
Field[] interfaceFields = HttpConstants.class.getFields();
for (Field field : interfaceFields) {
int constant = field.getInt(null);
//Do something with the field
}
However, it is better to use the approach with enums because with reflection coding errors result in runtime exceptions instead of compile-time errors.
for(Field f : HttpConstants.class.getFields()){
int constant = f.getInt(null);
}
public enum HttpConstant {
/** 2XX: generally "OK" */
HTTP_OK(200).
HTTP_CREATED(201),
HTTP_ACCEPTED(202),
HTTP_NOT_AUTHORITATIVE(203),
HTTP_NO_CONTENT(204),
HTTP_RESET(205),
HTTP_PARTIAL(206);
private int code;
private HttpConstant(int code) {
this.code = code;
}
public int getCode() {
return code;
}
}
with HttpConstant.values().
Well usually when i have something like that i make a Map in the interface that has the keys - constant names with values constant - values.
And that's how i can iterate over them.
I'd like to know what you think of this practice
Consider using an enum instead of an interface with constants.
enum HttpResultCode {
HTTP_OK(200),
HTTP_CREATED(201),
HTTP_ACCEPTED(202),
HTTP_NOT_AUTHORITATIVE(203),
HTTP_NO_CONTENT(204),
HTTP_RESET(205),
HTTP_PARTIAL(206);
private final int code;
private HttpResultCode(int code) {
this.code = code;
}
public int getCode(int code) {
return code;
}
public static HttpResultCode forCode(int code) {
for (HttpResultCode e : HttpResultCode.values()) {
if (e.code == code) {
return e;
}
}
throw new IllegalArgumentException("Invalid code: " + code);
}
}
Why won't this class compile?
class Exam {
private int score;
// constructor initializes score to 99
public void Exam() {
score = 99;
}
// returns the current value of score
private int getScore() {
return score;
}
// returns the String representation of the Object
public String toString() {
return "The score is " + getScore();
}
}
Your constructor shouldn't have a return type. Not even void.
public Exam() {
score = 99;
}
A construct should not contain the void keyword:
public Exam() {
score = 99;
}
A constructor returns a reference the the newly created object. But you don't have to write it. So thinking it is void is wrong as well.
Constructors don't need return types. Remove void and you should be set.
In a constructor you don't use void.
Write the constructor as:
public Exam() {
score = 99;
}
The main problem is the missing package declaration.
package yourpkg;
class Exam {
Additionally, the return type on the for Exam() makes it a function instead of a constructor and will result in a warning.
Just a suggestion not related to the concrete problem:
private int score;
// returns the current value of score
private int getScore() {
return score;
}
There is no point in having that getScore() if your going to keep it private. Make it public.
Also, always use the #Override annotation whenever your intention is to override some method. Compiler will let you known in case you are failing to do so. That means bug prevention.
e.g.
// returns the String representation of the Object
#Override
public String toString() {
return "The score is " + getScore();
}