I have class Shape2D, in that class I have method that calculate circle area circleArea, also I have class CircleArea where I store all atributes that I need for my method. Also, my class CircleArea extends class Shape2D. So, How I can implement my method from class Shape2D into class CircleArea.
This is my Shape2D class:
public class Shape2D {
public static void areaCircle(Circle c) {
double circleArea = Math.pow(c.getR(), 2) * Math.PI;
}
}
And this is my Circle class:
public class Circle extends Shape2D {
private double r;
public Circle() {
}
public double getR() {
return r;
}
public void setR(double r) {
this.r = r;
}
}
To implement one of the methods from the Shape2D class in the Circle class, you could do:
Shape2D.areaCircle(circleObject);
The above line can be called in the Circle class. Don't forget to pass in an actual circle object into the function.
You have a static method inside of 2D shape, meaning you can use it in any class without having 2DShape instantiated. This also means that you do not need the circle class to extend 2DShape to use this method, but I imagine you are going for that parent child relationship for the OO paradigm. If you don't want the method to be called from any class, remove static from the method. If you wish to call it statically inside of your Circle class constructor, first instantiate r to something, and then pass it into the static method call.
public class Circle extends Shape2D {
private double r;
public Circle() {
r=1;
Shape2D.areaCircle(this);
}
public double getR() {
return r;
}
public void setR(double r) {
this.r = r;
}
}
Note that your static function doesn't actually return anything, so it calculates the area and the value is lost. You can fix this inside of shape2D by changing the return type of circleArea to double in stead of void, and returning the result appropriately.
public static double areaCircle(Circle c) {
double circleArea = Math.pow(c.getR(), 2) * Math.PI;
return circleArea;
}
or non-statically, and protected in stead of public (either will work)
protected double areaCircle(Circle c) {
double circleArea = Math.pow(c.getR(), 2) * Math.PI;
return cricleArea;
}
If you wanted to do the same thing, but removed the static flag from the method, then you can use super to call parent methods.
public class Circle extends Shape2D {
private double r;
public Circle() {
r=1;
super.areaCircle(this);
}
public double getR() {
return r;
}
public void setR(double r) {
this.r = r;
}
}
Now if you wanted to actually store the area inside of this circleObject, I would create another attribute for the Circle class, and modify your constructor as such. Perhaps even adding a constructor that takes an int argument for radius (or in the future, an area with some way to differentiate the two that can get the radius value).
public class Circle extends Shape2D {
private double r;
private double area;
//Default Constructor
public Circle() {
r=1;
this.area = super.areaCircle(this);
}
//Radius constructor
public Circle(double rad) {
this.r = rad;
this.area = super.areaCircle(this);
}
public double getR() {
return r;
}
public void setR(double r) {
this.r = r;
}
}
It's also worth mentioning that you should look at the scope of these methods you create, and what you are trying to accomplish with them. For instance, you have your circleArea method defined as public, when it could be defined as protected and function similarly for this case. Protected means that the method can be used inside of the class, as well as all subclasses (children of the parent class, like circle). You can read information about these closures here. Also, when working with object inheritance, you should get into the habit of using the this keyword to reference which methods/attributes you actually wish to retrieve. Info on this keyword.
I realize this is a lot to take in, but if you have any questions feel free to comment!
Related
I have a superclass and two subclasses that extend it. I'd like to initialize a variable called radius which can be set freely in subclass A, but is always the same for subclass B. I could initialize the variable every time I create an object B, but I was wondering if it's possible to make the variable final and static in subclass B, while still being able to implement a getter in my superclass. I might implement more subclasses which have a radius that's either final or variable. If not I'm wondering what would be the most elegant solution for my problem. Here is some sample code which works, but isn't very great.
abstract class SuperClass {
public double getRadius() {
return this.radius;
}
protected double radius;
}
class A extends SuperClass{
public void setRadius(double radius) { // Would like to put this setter in SuperClass for future subclasses.
this.radius = radius;
}
}
class B extends SuperClass{
public B() {
radius = 0.2; //Want to make this static and final only for this subclass.
}
}
Making a variable final and static in one subclass, while keeping it
variable in others in Java
Technically, you cannot do it.
A field is either a static field or an instance field, not both.
As alternative, override getRadius() in the B class where you want to provide a different value :
#Override
public double getRadius() {
return 0.2;
}
And to make this constant respected, you should also override the setter in this B class:
#Override
public void setRadius(double radius) {
throw new UnsupportedOperationException();
}
Why dont you try this:
Make the Variable private in the superclass.
Have a getter and setter method in the superclass.
Override the setter method in the subclass so that is is not possible to change the variable.
Like that:
abstract class SuperClass {
private double radius;
public double getRadius() {
return this.radius;
}
public void setRadius(double radius) {
this.radius = radius;
}
}
class A extends SuperClass{
}
class B extends SuperClass{
public B() {
super.setRadius(0.2d);
}
#Override
public void setRadius(double radius) {
throw new UnsupportedOperationException("My Info Text");
}
}
Another approach would be to have the base class in its own package, with a protected setter:
package sandbox.radius.base;
public class Radius {
private double radius;
public double getRadius() {
return radius;
}
protected void setRadius(double radius) {
this.radius = radius;
}
}
Then implementations in a different package, exposes the setter only where appropriate, delegating to super:
package sandbox.radius;
import sandbox.radius.base.Radius;
public class FixedRadius extends Radius {
public FixedRadius() {
setRadius(0.2);
}
}
and
package sandbox.radius;
import sandbox.radius.base.Radius;
public class MutableRadius extends Radius {
public void setRadius(double radius) {
super.setRadius(radius);
}
}
So the API is cleaner:
public class RadiusApp {
public static void main(String[] args) {
FixedRadius fr = new FixedRadius();
fr.getRadius();
// fr.setRadius(1.0); //compile error
MutableRadius mr = new MutableRadius();
mr.getRadius();
mr.setRadius(1.0);
}
}
I am having difficulty extending the calCir class to the main class
I have a constructor that gives
class calCir {
double radius;
calCir(double r) {
radius = r;
}
double AreaCircle() {
return Math.PI * (radius * radius);
}
double CircumferenceCircle() {
return 2 * Math.PI * radius;
}
}
I would like to use Main extends calCir but get an error due to the constructor
class Main{
public static void main(String args[]) {
error: constructor calCir in class calCir cannot be applied to given types;
class Main extends calCir
Im fairly new to Java so im still confused as to how I would use inheritance
Here is the full code if needed
https://repl.it/NA5S/8
This error is due to following reason:
when you create a constructor for a class, there won't be any default constructor created for that class. so if you extend that class and if the subclass tries to call the no-arg constructor of its super class then there will be an compile-time error.
As stated here: Constructor in class cannot be applied to given types
You have created an explicit constructor for your class. Any explicitly defined constructor will eliminate the default no-args constructor that Java will use implicitly.
Here is the constructor you have created:
CalCir(double r) {
radius = r;}
In order to use inheritance as requested, you can do any of the following.
Remove the explicit constructor from the parent class.
Insert a second construction with no parameters into the parent class:
CalCir()
{
// Set the radius to default of zero
this(0);
}
Override the default constructor in the child class:
public class MainSubClass extends CalCir
{
public MainSubClass()
{
// Set the radius to default of zero
super(0);
}
public static void main(final String args[])
{
// Insert program here
}
}
First, it is meaningless to have Main extend CalCir in this case.
Second, go back to the specific question you asked.
When you have a class (e.g. Child) extend from another (e.g. Parent), in the ctor of Child, it ALWAYS needs to invoke constructor of its parent. If you are not EXPLICITLY invoking any, compiler will automatically assume you are invoking the no-arg constructor of parent.
e.g.
class Child extends Parent {
Child() {
// do something
}
}
is equivalent to
class Child extends Parent {
Child() {
super();
// do something
}
}
If in Parent, a constructor with arguments is declared, but there is no-arg ctor declared:
class Parent {
Parent(int foo) {...}
}
it is illegal for Child to invoke the no-arg ctor of Parent, because it simply does not exists.
So you need to explicitly tell the compiler which ctor you want to invoke:
class Child extends Parent {
Child() {
super(123);
// do something
}
}
Any particular reason why you need to extend CalcCir? Your CalCir has a constructor which requires 2 args, if you are to extend it to your main class, then you would have create a constructor in main like:
public Main(double radius) {
// define your params to parent here or have it passed in constructor...
super(param1, param2); // matching your super class
}
Based on the link you provided though, it seems to be more appropriate this way:
Your main class which contains your starting point:
public class Main {
public static void main(String[] args) {
Scanner b = new Scanner(System.in);
while (true) {
try {
System.out.println("Determining the area/perimeter of a 2D shape.");
System.out.println("Choose a shape:\n\nRectangle --> (Type a or rectangle)\nCircle --> (Type b or circle)");
String shape = b.nextLine();
if ((shape.equalsIgnoreCase("Rectangle")) || (shape.equalsIgnoreCase("a"))) {
System.out.println("Input Length");
double length = b.nextDouble();
System.out.println("Input width");
double width = b.nextDouble();
Shape rectangle = new Rectangle(length, width);
System.out.println("Area of rectangle is " + rectangle.getArea());
System.out.println("The perimeter is " + rectangle.getPerimeter());
if (length == width){
System.out.println("This is a special type of reactangle, a square!");
}
break;
} else if ((shape.equalsIgnoreCase("circle")) || (shape.equalsIgnoreCase("b"))) {
System.out.println("Input Radius");
double radius = b.nextDouble();
Shape circle = new Circle(radius);
System.out.println("Area of circle is " + circle.getArea());
System.out.println("The circumference is " + circle.getPerimeter());
break;
} else {
System.out.println("Not valid choice\n");
}
} catch (Exception e) {
System.out.println("Not valid choice\n");
}
}
}
}
Then your Circle and Rectangle classes:
public class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
#Override
double getArea() {
return Math.PI * (radius * radius);
}
#Override
double getPerimeter() {
return 2 * Math.PI * radius;
}
}
public class Rectangle extends Shape {
private double length;
private double width;
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
#Override
double getArea() {
return length * width;
}
#Override
double getPerimeter() {
return 2 * (length + width);
}
}
Of which both inherited from shape
public abstract class Shape {
abstract double getArea();
abstract double getPerimeter();
}
Please review the code below:
abstract class Shape {
protected double x;
protected double y;
public Shape(double x, double y) {
this.x = x;
this.y = y;
}
abstract protected void draw();
}
class Circle extends Shape {
public Circle(double x, double y, double r) {
super(x, y);
this.r = r;
}
protected double r;
protected void draw() {
System.out.println(String.format("Draw Circle. %f %f %f", x, y ,r));
}
}
class RenderEngine {
public static void draw1(Shape s) {
s.draw();
}
public static <T extends Shape> void draw2(T t) {
t.draw();
}
}
public class Runner {
#Test
public void run() {
Circle c = new Circle(1,2,3);
RenderEngine.draw1(c);
RenderEngine.draw2(c);
}
}
What's the difference between draw1() and draw2()? Which one is better? Does draw2() have more extensibility? Or does draw2() have better performance?
There is no difference in your scenario, because the type of the object being drawn is consumed internally in the drawX method.
It would make a difference if your method were to use T in some other context, such as returning the original back to the caller:
public static <T extends Shape> T draw2(T t) {
t.draw();
return t;
}
This makes a difference in situations when a subclass defines new methods on top of the base class. For example, if Circle defined
double radius() { return r;}
you could do the following:
double r = RenderEngine.draw1(c).radius();
This would be impossible with an implementation returning Shape.
Note: The above is to demonstrate the differences, not to suggest that the new implementation is more desirable than the original one.
draw2 will do the same thing as draw for things that are already shapes. But when it says T extends Shape, it allows it to take in a parameter that is not a shape. At that point, it will allow it to use the draw method without crashing, whether or not it's a shape, it just might not draw anything.
I like consolidating my code/classes as much as possible without each class itself getting messy. So I looked into using NestedClasses, though InnerClasses in this case because the InnerClass needs access the OuterClass's members.
Example
Lets say I have a program that calculates various shape attributes to shapes. So given a Rectangle Shape, it would find the Area/Perimeter from inputs of length and width.
I would first create an abstract class Shape, which has abstract methods getArea() and getPerimeter(). I would then create my subclass RectangleShape, extend the shape class, #Override those methods with the necessary logic.
Now there's a shape Rectangular Prism (Cube). It has the same variables/methods as RectangleShape does, but with one extra, height. In the past I would create another subclass of RectangleShape and go from there.
Is it better/not worse to use an InnerClass instead and have an abstract class PrismShape? I ask this because Prisms share the same methods, no matter the shape. If you're at all confused by the above I'm posting code below of what I'm saying.
Example Code
Shape Class
public abstract class Shape {
public abstract double getArea();
public abstract double getPerimeter();
}
PrismShape Class
public abstract class PrismShape{
public abstract double getVolume();
public abstract double getSurfaceArea();
public abstract double getLateralArea();
}
RectangleShape Class
import Abstract.Shape;
import Abstract.ShapePrism;
public class RectangleShape extends Shape{
//Variables Declared
private double _length, _width;
//Constructor
public RectangleShape(double _length, double _width) {
setLength(_length);
setWidth(_width);
}
//Getters and Setters
#Override
public double getArea() {
return getLength() * getWidth();
}
#Override
public double getPerimeter() {
return (2 * getLength())+ (2 * getWidth());
}
public double getLength() {
return _length;
}
private void setLength(double _length) {
this._length = _length;
}
public double getWidth() {
return _width;
}
private void setWidth(double _width) {
this._width = _width;
}
//Inner Class Prism
public class RecPrismShape extends PrismShape{
//Variables Declared
private double _height;
//Constructor
public RecPrismShape(double _height) {
setHeight(_height);
}
//Getters and Setters
#Override
public double getSurfaceArea(){
return (getLateralArea() + (2 * getArea()));
}
#Override
public double getVolume(){
return getArea() * getHeight();
}
#Override
public double getLateralArea(){
return getPerimeter() * getHeight();
}
public double getHeight() {
return _height;
}
private void setHeight(double _height) {
this._height = _height;
}
}
}
I'm open to criticism, still fairly new to Java. My thought process during this was I have 2d Shape attributes and 3d (Prism) shape attributes. The 3d Shapes derive their attributes from 2d shapes, but not visa versa. So for me at least having InnerClasses makes sense.
My own take on this: A public inner class seems most useful when the rest of the program has an object of the outer class, and it wants to create an object of the inner class that "belongs" to the outer class object in some way; that is, it's tightly associated with it.
The way you've arranged things, however, it means that if the client wants to create a RecPrismShape object, it has to first create a RectangleShape object that the prism object will belong to. Most likely, this is not going to be useful. That is, the client creates a RectangleShape rect just because it has to, in order to create a RecPrismShape, and the rect object wouldn't be useful to it in any other way.
I think a better idea would be to have a RecPrismShape object have a private RectangleShape object as one of its fields, but this would be an "implementation detail". That way, you'd get to reuse the RectangleShape code, which it seems like you're trying to do.
public class RecPrismShape extends RectangleShape {
private RectangleShape rect;
private double height;
public RecPrismShape(double length, double width, double height) {
rect = new RectangleShape(length, width);
this.height = height;
}
// and just one example of how you could use it
public double getVolume() {
return rect.getArea() * getHeight();
}
}
edit2
Sorry never mind I just added
public double cylinderSurfaceArea() {
return 2 * base.circleArea() + base.circleCirumference() * 2 * height;
}
}
With no error codes. This would be correct?
edit:
Thank you to all those who have answered. I have since changed my previous Cylinder class to read. Now I want to take it a step further and add
public double cylinderSurfaceArea() {
return 2 * Math.PI * radius * radius + 2 * Math.PI * radius * h;
}
However it now says that radius (or even r) returns an error "cannot find symbol - variable radius). Shouldn't the symbol be found/declared from the Circle class?
What I am trying to do is calculate the volume of a cylinder using a separate Circle.java class.
So for instance, I have the following so far for my circle.java
public class Circle {
public double radius;
public Circle(double r) {
radius = r;
}
public double circleArea() {
return Math.PI * radius * radius;
}
public double circleCirumference() {
return Math.PI * 2 * radius;
}
}
Now here are where the questions start. When making the Cylinder class do I start with:
public class Cylinder extends Circle {
If so, overall I have:
public class Cylinder extends Circle {
public Circle base;
public double height;
public Cylinder(double r, double h) {
height = h;
base = new Circle(r);
}
public double getVolume() {
return base.circleArea * height;
}
}
However, I keep getting an error after:
public Cylinder(double r, double h) {
Stating that:
constructor Circle in class Circle cannot be applied to given types; required:double; found: noarguments; reason:actual and formal arguments lists differ in length."
Can someone push me in the right direction? What am I doing wrong?
That happens because the first call of you constructor is implicit super()
Quote from the Java Tutorials:
If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass. If the super class does not have a no-argument constructor, you will get a compile-time error.
You need to make a parameterless constructor in your Circle class or change your Cylinder constructor like this:
public Cylinder(double r, double h) {
super(r);
height = h;
}
You're implicitly calling the super constructor with no argument, but there's no such constructor.
But you have a design problem : You're trying to use both composition and inheritance. One would be enough.
Using inheritance :
public class Cylinder extends Circle {
public double height;
public Cylinder(double r, double h) {
super(r);
height = h;
}
public double getVolume() {
return circleArea() * height;
}
}
Using composition (almost always better) :
public class Cylinder {
public Circle base;
public double height;
public Cylinder(double r, double h) {
height = h;
base = new Circle(r);
}
public double getVolume() {
return base.circleArea * height;
}
}
You don't need an explicit base field in Java when using inheritance. To initialise the base class (or "superclass"), you need to use the super statement in your child class constructor:
class Circle {
public Circle(double radius) {
// …
}
}
class Cylinder extends Circle {
public Cylinder(double radius, double height) {
super(radius); // calls the parent class constructor
// …
}
}
Alternately, you could use composition instead of inheritance - probably a better design in this case:
class Circle {
public Circle(double radius) { /* … */ }
}
class Cylinder { // no `extends` here
public Cylinder(Circle base, double height) {
// …
}
public Cylinder(double radius, double height) {
this(new Circle(radius)); // calls the above constructor
// …
}
}
(I'm omitting trivial assignments and fields in the above code sample for brevity.)
Problem 1:
The problem in your program is no default constructor present in your Circle. While creating the Cylinder object its looking for the default constructor in Circle.
if you modify your Circle as below it will work
class Circle {
public Circle(){
}
}
problem 2
There is "base.circleArea" method only present in Circle, you have forgot "()"
base.circleArea need to change to base.circleArea().
public class Cylinder extends Circle {
public double getVolume() {
return base.circleArea() * height;
}
}
Problem 3
Your Cylinder should be like below. You are already extended circle so no need to create variable Circle base inside Cylinder.
class Cylinder extends Circle {
public double height;
public Cylinder(double r, double h) {
super(r);
height = h;
}
public double getVolume() {
return circleArea * height;
}
}