How to access an inner enum classes overwritten methods? - java

What code is needed for the main to access the getPrice() method ?
I can access the public enum type with the built in values(); function
but cant figure out how to print the prices , thanks
public enum Drink {
GUINNESS(Type.STOUT),
COLA(Type.COLA);
private Type type;
private Drink(Type type) {
this.type = type;
}
private enum Type {
STOUT {
#Override
public double getPrice() {
return 4.0;
}
},
COLA {
#Override
public double getPrice() {
return 2.0;
}
};
public abstract double getPrice();
}
}

You have to add a getter for the price in the Drink enum.
public double getPrice() {
return type.getPrice();
}
And then you can do:
Drink cola = Drink.COLA;
double price = cola.getPrice();

You can't access the private inner enum outside the public enum, you can however delegate the method:
public enum Drink {
GUINNESS(Type.STOUT),
COLA(Type.COLA);
private Type type;
private Drink(Type type) {
this.type = type;
}
public double getPrice() {
return type.getPrice();
}
private enum Type {
STOUT {
#Override
public double getPrice() {
return 4.0;
}
},
COLA {
#Override
public double getPrice() {
return 2.0;
}
};
public abstract double getPrice();
}
}
You define the same method in the enum Drink:
public double getPrice() {
return type.getPrice();
}

You can't, since another class can't see the nested enum at all. You could add a delegating copy to the top-level enum.

Related

Trying to create an object from an interface

My assignment for uni has clear instructions and they want me to create a dish by utilizing an interface. But I can't even create a proper test-dish without an error, what am I doing wrong?
DishTypes as enum:
(This can't be changed at all)
public enum DishType {
STARTER, MAIN_DISH, DESSERT, OTHER;
}
Interface Dish:
(For the interface the classes and names can't be changed/deleted as per instructions, only their body and return-statements)
public interface Dish {
String getName();
double getBasePrice();
DishType getDishType();
static Dish createDish(String name, double basePrice, DishType type) {
return createDish(name,basePrice,type);
}
}
And here is the class I created on my own to be able to implement a dish:
public class DishImplementation implements Dish {
public String name;
private double basePrice;
private DishType type;
public DishImplementation(String name, double basePrice, DishType type) {
this.name = name;
this.basePrice = basePrice;
this.type = type;
}
#Override
public String getName() {
return name;
}
#Override
public double getBasePrice() {
return basePrice;
}
#Override
public DishType getDishType() {
return type;
}
Now if I try to create a test-dish using my Test class I always get an error:
public class Test {
public static void main(String[] args) {
Dish d1 = Dish.createDish("a",1.0, DishType.MAIN_DISH);
System.out.println(d1.getName());
}
}
How do I get the console to actually show me the name of my test-dish?
Your createDish(...) method should return an object instead of recursively invoking itself.
Here is how you'd do it.
public interface Dish {
String getName();
double getBasePrice();
DishType getDishType();
static Dish createDish(String name, double basePrice, DishType type) {
return new DishImplementation(name,basePrice,type);
}
}

get some object of one class and use in another class

I want to use some object of one class and use in other class,but i can not
for example :
class 1:
public class Value {
private double radious;
private double lenght;
public void setRadious(double radious) {
this.radious = radious;
}
public void setLenght(double lenght) {
this.lenght = lenght;
}
}
question : how can I use just radious of class 1 in class 2???
class 2:
public class calculateArea
{
private Value value;
public double area()
{
return 3.14*radious*radious;
}
}
Create getters for both the values and access them in your second class.
Something like
public double getRadious() {
return this.radious;
}
public double getLenght() {
return this.lenght;
}
When working on OOP, ask yourself what code goes where and how many classes you have to make?
For your scenario, you can use aggregation or composition which is to declare the object of one class in another and then you can call the methods of the declared object using dot notation with getter setter methods. So it will go like this.
public class Value
{
private double radious;
private double lenght;
public void setRadious(double radious)
{
this.radious = radious;
}
public double getRadious() {
return this.radious;
}
public double getLenght() {
return this.lenght;
}
public void setLenght(double lenght)
{
this.lenght = lenght;
}
}
Class # 2
public class calculateArea
{
private Value value = new Value();
public calculateArea(double rad) {
value.setRadius(rad);
}
public double area()
{
return 3.14*value.getRadious()*value.getRadious();
}
}
Also, you need to set the value of radius before using it.
Make a getter Method for radious:
public double getRadious(){
return radious;
}
In the "Main Class":
Value v = new Value();
v.setRadious(2.5);/*Set the Radious value*/
public double area()
{
return 3.14*v.getRadious()*v.getRadious();
}
Add getters to class Value.
public class Value {
public double radious;
public double lenght;
public void setRadious(double radious) {
this.radious = radious;
}
public void setLenght(double lenght) {
this.lenght = lenght;
}
public double getLenght() {
return this.lenght;
}
public double getRadious() {
return this.radious;
}
}
Make an instance of class 1
public class calculateArea{
public Value;
calculateArea(){
value = new Value();
}
public double area(){
value.setRadious(2.34);//or set ACCORDINGLY
return 3.14 * value.radious * value.radious;
}
}
Declare getters and setters for Value-class:
public class Value {
private double radious;
private double lenght;
public Value(double radious, double length) {
this.radious = radious;
this.length = length;
}
public void setRadious(double radious) {
this.radious = radious;
}
public void setLenght(double lenght) {
this.lenght = lenght;
}
public double getRadious() {
return this.radious;
}
public double getLength() {
return this.length;
}
}
Instantiate the object with some variables:
Value value = new Value(2.0,3.0);
Add Constructor to CalculateArea class:
public class calculateArea {
private Value value;
public calculateArea(Value value) {
this.value = value;
}
public double area()
{
return 3.14*value.getRadious()*value.getRadious();
}
}
Instantiate:
calculateArea cArea= new calculateArea(value);
And print result to console in main() method:
System.out.println(cArea.area());

How to reference a extended subclass in java?

I am currently working on a project for java and the teacher isn't very great at explaining himself.
Currently I'm stuck trying to reference an extended Class in java to get the balance. (i'm trying to edit the balance so that it can be displayed and changed in the array.
my main account looks like this
public class Account {
private String name;
private double quantity, price;
private double rate;
private Asset[] Asset;
}
The account that is extended is
abstract public class Asset {
String symbol;
public String getSymbol() {
return symbol;
}
protected Asset(String symbol) {
this.symbol = symbol;
}
}
The extensions look like so;
public class Cash extends Asset {
private double Quantity;
public Cash(double Quantity, String symbol) {
super(symbol);
this.Quantity = Quantity;
}
#Override
public String getSymbol() {
return super.getSymbol(); //To change body of generated methods, choose Tools | Templates.
}
public double getQuantity() {
return Quantity;
}
public void setQuantity(double Quantity) {
this.Quantity = Quantity;
}
}
Now lets say I have a test instance created of class Account.
How would I be able to edit the Cash value from the Class account? (Main arg)
Here are the other extensions I have too just for reference.
public class Stock extends Asset {
private String name;
private double quantity, rate;
public Stock(String name, double quantity, double rate, String symbol) {
super(symbol);
this.name = name;
this.quantity = quantity;
this.rate = rate;
}
#Override
public String getSymbol() {
return super.getSymbol(); //To change body of generated methods, choose Tools | Templates.
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getQuantity() {
return quantity;
}
public void setQuantity(double quantity) {
this.quantity = quantity;
}
public double getRate() {
return rate;
}
public void setRate(double rate) {
this.rate = rate;
}
}
If it helps, how would I be able to change the values in the extended classes?
I've tried
Asset[0] = new Cash(25000.00,string);
but that's only helpful in putting the value manually.
Apologies for any mistakes, I'm pretty new to coding and java in general.
The way you named your Asset array is confusing, java is case sensitive so name it for example:
private Asset[] asset;
You need to get a reference of the right type through casting before you can access it's own methods. You can do for example:
if (asset[0] instanceof Cash) {
Cash cash = (Cash)asset[0];
// Then you can access the setQuantity method
cash.setQuantity(25000.00);
}

interface,abstract and classes

I am trying to complete the Appendix attached Appendix. I just want to know if I am coding it correctly according to the Appendix and that I am using the correct approach. I am not sure if I did the correct thing under interest(). Where I called the super classes is that correct?
public interface LoanInterest {
double interest();
String getName();
String toString();
} //end of LoanInterest
public abstract class Student implements LoanInterest {
private String name;
private String studentNumber;
private double feesOwed;
public Student(String nm, String num, double amt) {
name = nm;
studentNumber = num;
feesOwed = amt;
}
public double getFeesOwed() {
return feesOwed;
}
public String getStudentNumber() {
return studentNumber;
}
public String getName() {
return name;
}
public String toString() {
String msg;
msg = String.format("%s\t%s\t%.2f", name, getStudentNumber(), getFeesOwed());
return msg;
}
} //end of Student
public class UnderGrad extends Student {
public UnderGrad(String nm, String num, double amt) {
super(nm, num, amt);
}
public double interest() {
return super.getFeesOwed() + (super.getFeesOwed() * 0.14);
}
} //end of UnderGrad
public class PostGrad extends Student {
private String diploma;
public PostGrad(String nm, String num, double amt) {
super(nm, num, amt);
}
public String getDiploma() {
return diploma;
}
public double interest() {
return super.getFeesOwed() + (super.getFeesOwed() * 0.14);
}
} //end of PostGrad
You don't need to call super.methodName, since you do not override them in PostGrad or UnderGrad, but it is not "wrong" either.
So you can write:
public double interest() {
return getFeesOwed() + (getFeesOwed() * 0.14);
}
And if you would override them, you most likely want to use them too, so again no super.
The super keyword is normally used, if a method is overridden to add some additional functionality to it, without completely rewriting the code of the overridden method.

Java creating objects within objects

I'm trying to create a Pizza menu. I have 3 classes,
PizzaBase (with get / set methods for the thickness of the base
[either thin or deeppan])
PizzaTopping, again with get / set methods
for the type of topping
Pizza, where my cost variable is stored and
used across the 3 classes using inheritance.
As a cost variable is used for the base, the topping and the overall pizza itself.
Now my question is this, how would I go about creating a Pizza object, which in turn creates 1 base object, and a few toppings objects, each with a price?
I can work out how to calculate an overall price, I'm just a bit stuck creating objects within objects.
public class PizzaTopping extends Pizza{
private String topping;
public String getTopping(){
return this.topping;
}
public void setTopping( String topping ){
this.topping = topping;
}
}
public class PizzaBase extends Pizza{
private String base;
public void setBase( String base ){
this.base = base;
}
public String getBase(){
return this.base;
}
}
public class Pizza {
private double cost;
public void setCost( double cost ){
this.cost = Math.abs(cost);
}
public double getCost(){
return this.cost;
}
public void makingPizza(){
PizzaBase b = new PizzaBase();
}
}
Replace the Pizza class with CostableItem class:
public class CostableItem {
private double cost;
public void setCost( double cost ){
this.cost = Math.abs(cost);
}
public double getCost(){
return this.cost;
}
}
Then extend it in both toppings and base:
public class PizzaBase extends CostableItem {...}
public class PizzaTopping extends CostableItem {...}
After that create a class called Pizza that has one base and multiple toppings:
public class Pizza{
private PizzaBase base;
private ArrayList<PizzaToppings> toppings;
//..
}
You don't need inheritance for this at all. At the most you might need an interface. So I would design it this way:
public interface PricedItem {
double getCost(); //double is suitable for our purposes
}
Since you want to calculate cost, everything that is a priced item should have a getCost() method. This will apply to your PizzaTopping, PizzaBase, and Pizza class:
public class PizzaTopping implements PricedItem
private String name;
private double cost;
public PizzaTopping(String name, double cost) {
this.name = name;
this.cost = cost;
}
...
#Override
public double getCost() {
return cost;
}
}
More or less the same thing for PizzaBase:
public class PizzaBase implements PricedItem {
private double cost;
...
}
Your Pizza class will also implement PricedItem. But what is also important is that you will have a collection of PizzaTopping instances; there is no inheritance here!
public class Pizza implements PricedItem {
private double cost;
private PizzaBase base;
private List<PizzaTopping> toppings;
public Pizza(double cost, PizzaBase base) {
this.cost = cost;
this.base = base;
toppings = new ArrayList<PizzaTopping>();
}
...
public void addTopping(PizzaTopping topping) {
//left as an exercise to the reader :)
}
#Override
public double getCost() {
//this is left as an exercise to the reader :)
return totalCost;
}
}

Categories