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());
Related
I implemented pattern based on this answer
I have the following asbtract config:
public abstract class AbstractConfig {
public static abstract class Builder<B extends Builder<B>> {
private int calories = 0;
public Builder() {
}
public B setCalories(int calories) {
this.calories = calories;
return (B) this;
}
public abstract AbstractConfig build();
}
private int calories = 0;
protected AbstractConfig(final Builder builder) {
calories = builder.calories;
}
}
And I have the following concrete config:
public class DialogConfig extends AbstractConfig {
public static class DialogConfigBuilder<B extends DialogConfigBuilder<B>> extends Builder<B> {
private double width;
private double height;
public DialogConfigBuilder() {
//does nothing.
}
public B setWidth(final double value) {
width = value;
return (B) this;
}
public B setHeight(final double value) {
height = value;
return (B) this;
}
public DialogConfig build() {
return new DialogConfig(this);
}
}
private final double width;
private final double height;
protected DialogConfig(final DialogConfigBuilder builder) {
super(builder);
width = builder.width;
height = builder.height;
}
public double getWidth() {
return width;
}
public double getHeight() {
return height;
}
}
And this is how I use it
DialogConfig config = new DialogConfig.DialogConfigBuilder()
.setWidth(0)
.setCalories(0)
.setHeight(0) //X LINE
.build();
At X line I get - Can't find symbol method setHeight. What is my mistake?
EDIT - I will have and a ExtendedDialogConfig that must extend DialogConfig and etc. I mean there will be other subclasses.
You would first change setCalories() to:
public Builder<B> setCalories(int calories) {
this.calories = calories;
return this;
}
to get rid of that cast and the warning. And now look at this closely. You return a Builder. This code doesn't know about future subclasses. It only returns an instance of that base builder.
As a consequence, when you have that chained call:
.setHeight(0) .build();
that would return that base builder. To then call build() - which would build an abstract configuration. But you want to assign that to a more specific DialogConfig. Thus the error.
A (ugly) workaround:
DialogConfig.DialogConfigBuilder<?> builder = new DialogConfig.DialogConfigBuilder<>().setHeight(0);
builder.setCalories(0);
...config = builder.build();
And a solution - by again reworking setCalories():
#SuppressWarnings("unchecked")
public <T extends B> T setCalories(int calories) {
this.calories = calories;
return (T) this;
}
Fixes the compile error; and allows chaining the setCalories() call as well. Final exercise of getting rid of the cast/suppress is left as exercise to the reader.
And for the record - the "complete" solution, including all adaptions to get rid of raw types and other warnings:
abstract class AbstractConfig {
public static abstract class Builder<B extends Builder<B>> {
private int calories = 0;
#SuppressWarnings("unchecked")
public <T extends B> T setCalories(int calories) {
this.calories = calories;
return (T) this;
}
public abstract AbstractConfig build();
}
private int calories = 0;
public int getCalories() { return calories; }
protected <B extends Builder<B>> AbstractConfig(final Builder<B> builder) {
calories = builder.calories;
}
}
final class DialogConfig extends AbstractConfig {
public static class DialogConfigBuilder<B extends DialogConfigBuilder<B>> extends Builder<B> {
private double width;
private double height;
public DialogConfigBuilder<B> setWidth(final double value) {
width = value;
return this;
}
public DialogConfigBuilder<B> setHeight(final double value) {
height = value;
return this;
}
public DialogConfig build() {
return new DialogConfig(this);
}
}
private final double width;
private final double height;
protected <B extends DialogConfigBuilder<B>> DialogConfig(final DialogConfigBuilder<B> builder) {
super(builder);
width = builder.width;
height = builder.height;
}
public double getWidth() { return width; }
public double getHeight() { return height; }
}
public class Builders {
public static void main(String[] args) {
DialogConfig config = new DialogConfig.DialogConfigBuilder<>().setHeight(0).setCalories(0).build();
System.out.println(config);
}
}
I found my mistake. This is how I used DialogConfigBuilder
DialogConfig config = new DialogConfig.DialogConfigBuilder()
.setWidth(0)
.setCalories(0)
.setHeight(0) //X LINE
.build();
This is how I should use DialogConfigBuilder
DialogConfig config = new DialogConfig.DialogConfigBuilder<>()
.setWidth(0)
.setCalories(0)
.setHeight(0) //X LINE
.build();
Pay attention to <> in the second case.
I understand that I do not have anything in my main method yet so nothing will execute, that is the second part to the assignment.
My question is, I'm getting an error in the computeDiscount method where I'm calling the computeNumCases method. The error i'm getting is
variable numCases might not have been initialized
so I need help figuring that error out.
Also, help in the computeCost method would be very helpful as well.
public class Customer {
private String customerLastName;
private String candyType;
private int numCandyBars;
private double costPerBar;
private int NUMBERPERCASE = 12;
public static void main(String[] args) {
}
public Customer() {
}
public Customer(String name, String type, int numCandyBars, double costPerBar) {
//this.name = name;
candyType = type;
this.numCandyBars = numCandyBars;
this.costPerBar = costPerBar;
}
public static double getCostPerBar(double costPerBar) {
return costPerBar;
}
public static int getNumCandyBars(int numCandyBars) {
return numCandyBars;
}
public String getCandyType() {
return candyType;
}
public String GetCustomerLastName() {
return customerLastName;
}
public void setCustomerLastName(String name) {
this.customerLastName = name;
}
public void setNumCandyBars(int num) {
this.numCandyBars = num;
}
public void setCandyType(String candyType) {
this.candyType = candyType;
}
public void setCostPerBar(double cost) {
costPerBar = cost;
}
public int computeNumCases(int numCases) {
numCases = numCandyBars / NUMBERPERCASE;
return numCases;
}
public int computeNumIndividuals(int numIndividuals) {
numIndividuals = numCandyBars % NUMBERPERCASE;
return numIndividuals;
}
public int computeDiscount(int discount) {
int numCases = computeNumCases(numCases);
if (numCases < 20)
discount = 100;
else if (numCases < 50)
discount = 85;
else
discount = 75;
return discount;
}
public double computeCost(double totalCost) {
return computeNumCases(numCases) * getCostPerBar(costPerBar) * (NUMBERPERCASE * discount / 100.00) + computeNumIndividuals(numIndividuals) * getCostPerBar(costPerBar);
}
}
I have two different Enums:
public enum A {
mass(10); // many other values omitted for clarity
private final int m;
private A(int m) { this.m = m; }
public int value() { return this.m; }
}
public enum B {
mass(100); // many other values omitted for clarity
private final int m;
private B(int m) { this.m = m; }
public int value() { return this.m; }
}
and want to pass enum class as parameter to my function. From other answers that I found on SO, it is suggested that I can pass Class, but I am not sure how to correctly detect and use A or B enum in the function body:
public int mass(Class<?> clazz) {
// Is it the best way? How to avoid a bunch of ifs?
if (clazz == A.class) return A.mass.value();
if (clazz == B.class) return B.mass.value();
}
Not sure what you're trying to accomplish buddy but you seem to be in need of polymorphism. Try using an interface with Enums like this:
public enum A implements MassProvider {
MASS(10);
private int mass;
A(int mass) {
this.mass = mass;
}
#Override
public int getMass() {
return mass;
}
}
public enum B implements MassProvider {
MASS(100);
private int mass;
B(int mass) {
this.mass = mass;
}
#Override
public int getMass() {
return mass;
}
}
public interface MassProvider {
int getMass();
}
public static int mass(MassProvider p) {
return p.getMass();
}
Basically instead of passing a class to the mass method you pass a MassProvider that is implemented by both enums.
I'm just getting into java and have a program I need to write with a Class and ClassDriver. I'm supposed to write a program to calculate the total for cheesecake orders (four different kinds) based on price and count. The price given for each is constant. The count is based on user input. There can be only one subTotal method to calculate the subtotal of all the cheesecakes bought.
I'm not sure of the concept I need to do for this and I've been trying to do this for some hours now. Please help as soon as you are able to.
public class CheesecakeOrder {
private final double PLAIN_CHEESECAKE_PRICE=10.0;
private final double MARBLE_CHEESECAKE_PRICE=15.0;
private final double CHOCO_CHIP_CHEESECAKE_PRICE=18.0;
private final double VARIETY_CHEESECAKE_PRICE=22.0;
private final double SCHOOL_SHARE_RATE=.12;
private int plainCheesecakeCount=0;
private int marbleCheesecakeCount=0;
private int chocoChipCheesecakeCount=0;
private int varietyCheesecakeCount=0;
public double getPLAIN_CHEESECAKE_PRICE()
{
return PLAIN_CHEESECAKE_PRICE;
}
public double getMARBLE_CHEESECAKE_PRICE()
{
return MARBLE_CHEESECAKE_PRICE;
}
public double getCHOCO_CHIP_CHEESECAKE_PRICE()
{
return CHOCO_CHIP_CHEESECAKE_PRICE;
}
public double getVARIETY_CHEESECAKE_PRICE()
{
return VARIETY_CHEESECAKE_PRICE;
}
public int getPlainCheesecakeCount()
{
return plainCheesecakeCount;
}
public int getMarbleCheesecakeCount()
{
return marbleCheesecakeCount;
}
public int getChocoChipCheesecakeCount()
{
return chocoChipCheesecakeCount;
}
public int getVarietyCheesecakeCount()
{
return varietyCheesecakeCount;
}
public void setPlainCheesecake(int plainCheesecakeCount)
{
this.plainCheesecakeCount=plainCheesecakeCount;
}
public void setMarbleCheesecake(int marbleCheesecakeCount)
{
this.marbleCheesecakeCount=marbleCheesecakeCount;
}
public void setChocoChipCheesecakeCount(int chocoChipCheesecakeCount)
{
this.chocoChipCheesecakeCount=chocoChipCheesecakeCount;
}
public void setVarietyCheesecakeCount(int varietyCheesecakeCount)
{
this.varietyCheesecakeCount=varietyCheesecakeCount;
}
public double calculateSubTotal()
{
double subTotal;
subTotal = price * count;
return subTotal;
}
public double calculateDonation()
{
double donation;
donation = (calculateSubTotal()*SCHOOL_SHARE_RATE);
return donation;
}
public double calculateTotal()
{
double total;
total = donation+calculateSubTotal();
return total;
}
}
Try using a method that uses variable arguments as its parameter. Find the argument count from the passed variable, then loop through and calculate each one until you reach the end of the collection.
I hava a Super Class Ball with extender OvalBall. With following being my code I am getting a error message telling me I can't use the child class OvalBall. can anyone help explain please?
public class Ball
{
private double diameter;
private String colour;
public Ball(double d, String c)
{
this.diameter = d;
this.colour = c;
}
public void setDiameter(double d)
{
this.diameter = d;
}
public double getDiameter()
{
return this.diameter;
}
public void setColour(String c)
{
this.colour = c;
}
public String getColour()
{
return colour;
}
public double bounce()
{
double height = diameter * 2;
return height;
}
public void roll()
{
System.out.println("wheeee");
}
public class OvalBall extends Ball
{
private double secondDiameter;
public void setSecondDiameter(double sd)
{
this.secondDiameter = sd;
}
public double getSecondDiameter()
{
return this.secondDiameter;
}
}
}
public class Main
{
public static void main(String[] args)
{
OvalBall na = new OvalBall(4,"blue",4);
na.setSDiameter(10);
System.out.println(na.bounce());
}
}
Feel free to change anything.
Thanks
You need to define OvalBall either as static or in its own file.
Maybe OvalBall din't implement the constructor class of hi base class
That's why you can't create a object of OvalBall.
class Ball {//This is you base class contructor
//Child class contructor
public class OvalBall extends Ball
{
public OvalBall(double d, String c)
{
base(d,c);
}
}
And when you make nested classes in java there is a different. way to create an object instance instead of other languages Like C#.
Try in this way. or use my code as example
public class Main
{
public static void main(String[] args)
{
Ball.OvalBall na = na.new OvalBall(4,"blue",4);
na.setSDiameter(10);
System.out.println(na.bounce());
}
}