Why is my java EXTENDS not working? - java

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

Related

how to new an unknown object in abstract class

I would like to use a builder pattern to create an unknown object
how to do that?
my code like this:
public abstract class abstractA<T extends GameApplication<T>>{
public static class Builder<T> {
private JPanel panel = new JPanel();
private JFrame frame = new JFrame();
private int height = 0, width = 0;
private int x = 0,y = 0;
private Color backgroundColor = Color.BLUE;
public Builder setFrameHeightWidth(int height, int weight) {
this.height = height;
this.width = weight;
return this;
}
public Builder setLocation(int x, int y) {
this.x = x;
this.y = y;
return this;
}
public Builder setbackground(Color color) {
this.backgroundColor = color;
return this;
}
public T Build(){
//error here
return new T ;
}
}
I want to use it like this:
class RealA extends abstractA{
public static void main(String[] argv){
RealA a = abstractA.builder
.setLocation(100,200)
.setFrameHeightWidth(500,600)
.build();
}
}
and I can't create a generics object, but I need this. How to do that?
You can sort of do (something like) this if you let the builder know the kind of thing it is building (by passing it a class) and then get it to create the instance using reflection (e.g. the classes newInstance method).
This assumes all sub classes have a zero-argument constructor. (It can be modified to use a constructor with arguments, but each sub-class would need a constructor with the same signature)
For example...
public class Stack {
static abstract class Common {
protected String name;
public void setName(String name) {
this.name = name;
}
public abstract void doSomething();
}
static class Solid1 extends Common {
#Override
public void doSomething() {
System.out.println("Solid1's implementation: name=" + name);
}
}
static class Solid2 extends Common {
#Override
public void doSomething() {
System.out.println("Solid2's implementation: name=" + name);
}
}
static class Builder<T extends Common> {
private final Class<T> clazz;
private String name;
public Builder(Class<T> clazz) {
this.clazz = clazz;
}
public Builder<T> setName(String name) {
this.name = name;
return this;
}
public T build() {
T t;
try {
t = clazz.newInstance();
} catch (Exception e) {
throw new RuntimeException("Bad things have happened!");
}
t.setName(name);
return t;
}
}
public static void main(String[] args) {
Solid1 solid1 = new Builder<>(Solid1.class).setName("[NAME]").build();
Solid2 solid2 = new Builder<>(Solid2.class).setName("[NAME]").build();
solid1.doSomething();
solid2.doSomething();
}
}
Output...
Solid1's implementation: name=[NAME]
Solid2's implementation: name=[NAME]
Not sure how useful this is...

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

Builder pattern with inheritance support generics issue

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.

Pass enum class as parameter to method in java

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.

basic constructor usage in java

For whatever reason, I cannot find this question anywhere else, nor can I find the answer online. If I have the following:
package temp1;
public class MainClass {
public static void main(String[] args) {
}
public MainClass(int radius_x, int area_x, int circumference_x) {
int radius = radius_x;
int area = area_x;
int circumference = circumference_x;
}
}
Assuming that this is even correct usage, then how would I actually use the variables defined in the constructor here? They only work inside of the constructor thanks to scope.
You are correct that the code you supply makes little sense. A more common scenario is to use the constructor to initialize a few instance variables, which can then be used throughout the class.
public class MainClass {
private int radius;
private int area;
private int circumference;
public static void main(String[] args) {
}
public MainClass(int radius_x, int area_x, int circumference_x) {
this.radius = radius_x;
this.area = area_x;
this.circumference = circumference_x;
}
}
One way to re-use the arguments of your constructor is to have instance variables assigned with your constructor's arguments' values.
As such:
package temp1;
public class MainClass {
private int radiusX;
private int areaX;
private int circumferenceX;
public static void main(String[] args) {
}
public MainClass(int radius_x, int area_x, int circumference_x) {
this.radiusX = radius_x;
this.areaX = area_x;
this.circumferenceX = circumference_x;
}
// TODO getters [and setters] for instance variables
}
package temp1;
public class MainClass {
int radius ;
int area;
int circumference;
public static void main(String[] args) {
}
public MainClass(int radius_x, int area_x, int circumference_x) {
this.radius = radius_x;
this.area = area_x;
this.circumference = circumference_x;
}
}
You created a constructor, but the variables inside are only local to the constructor itself and not outside of it. To do this, you need class member fields:
public class MainClass {
private int radius;
private int area;
private int circumference;
public static void main(String[] args) throws Exception {
MainClass m = new MainClass(5, 6, 7);
System.out.println("The radius is " + m.getRadius());
}
public MainClass(int radius_x, int area_x, int circumference_x) {
radius = radius_x;
area = area_x;
circumference = circumference_x;
}
public int getRadius() {
return radius;
}
public void setRadius(int radius) {
this.radius = radius;
}
public int getArea() {
return area;
}
public void setArea(int area) {
this.area = area;
}
public int getCircumference() {
return circumference;
}
public void setCircumference(int circumference) {
this.circumference = circumference;
}
}
Keep in mind also there is no need to pass in area_x and circumference_x Those can be derived from radius_x. That's assuming you are being faithful to the meanings of the terms rather than just playing around with variables to learn the language.

Categories