Circle class multiple constructors - java

I am trying modify the class Circle to include a third constructor for constructing a Circle instance with two arguments - a double for radius and a String for color. Also Modify the main class to construct an instance of Circle using this constructor. I am having trouble with this, i keep getting the message that constructor Circle is never used. Please have a look at the code.
public class Circle {
private double radius;
private String color;
public Circle() {
radius = 1.0;
color = "red";
}
public Circle(double r) {
radius = r;
color = "Blue";
}
public Circle(double r, String c) {
radius = r;
color =c;
}
public double getRadius() {
return radius;
}
public void setRadius(double newRadius) {
radius = newRadius;
}
public String getColor()
{
return color;
}
public void setColor(String newColor) {
color=newColor;
}
public double getArea() {
return radius*radius*Math.PI;
}
}
public class Main {
public static void main(String[] args) {
Circle c1 = new Circle();
System.out.println("The circle has radius of " + c1.getRadius());
System.out.println("and area of " + c1.getArea());
Circle c2 = new Circle(2.5);
System.out.println("The circle has radius of " + c2.getRadius());
System.out.println("and area of " + c2.getArea());
Circle c3 = new Circle(0.5);
c3.setColor("Green");
System.out.println("The circle has radius of "
+ c3.getRadius());
System.out.println("and area of " + c3.getArea());
System.out.println("color is: " + c3.getColor());
Circle c5 = new Circle();
c5.setRadius(500.0);
System.out.println("radius is: " + c5.getRadius());
c5.setColor("Yellow");
System.out.println("color is: " + c5.getColor());
}
}

Well, you aren't using it, so the message should hardly be a surprise. Just stick in a call to the two-argument constructor somewhere (e.g., Circle c3 = new Circle(0.5, "Green");), and the message should go away. Of course, if you change all the instance creations to the two-argument constructor, you'll then get the warning for the zero- and one-argument versions.
Alternatively, you can change your constructor definitions:
public class Circle {
public Circle() {
this(1.0, "red");
}
public Circle(double r) {
this(r, "Blue");
}
public Circle(double r, String c) {
radius = r;
color = c;
}
...
}
I have to say, though, that it's weird to have the default value for the color be "red" when you use a default radius and "Blue" when you specify a radius. I would recommend against that, in which case I'd change the first constructor to:
public Circle() {
this(1.0);
}
You might also want to look at using an enum for your colors, to avoid problems with case differences (like "red" vs. "Red"). You can always convert between an enum value and a String using the built-in enum methods name() and valueOf(String).

Related

android Override a function in subclass

I make a class Figure then two subclasses from it. Figure super class have a method named are(). this is the all class.
public class Figure
{
public double a, b;
public Figure(double a,double b) {
this.a = a;
this.b = b;
}
public double are() {
return 0;
}
}
public class Rectangle extends Figure
{
Rectangle(double a, double b) {
super(a,b);
}
double area (){
return this.a*this.b;
}
}
class Triangle extends Figure
{
Triangle(double a, double b) {
super(a,b);
}
// override area for right triangle
double area () {
return a * b / 2;
}
}
to easy print outpute I make
public void toastM(String str) {
Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT).show();
}
now I use this code
Figure f = new Figure(10, 10);
Rectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(10, 8);
Figure figref;
figref = r;
toastM("are..... " + figref.are());
figref = t;
toastM("are..... " + figref.are());
figref = f;
toastM("are..... " + figref.are());
expected values are 45 40 0
but it come 0 0 0
The parent class has a method called
double are()
the child classes
double area()
so it's not overridden
The functions you are overriding in both Rectangle and Triangle are called area AND NOT are as in the Figure class
You are calling the are() function of the super class Figure, not the area() function the subclass.

Difference between Static and Non-Static methods/Subroutines

I was reading a java book, where I came across this statement:
So, every subroutine is contained either in a class or in an object
I'm really confused why does it say "class or in an object"
I would like some explanation.
Let's try this example
public class Demo {
public static void classMethod() {
System.out.println("Call to static method");
}
public void objectMethod() {
System.out.println("Call to object method");
}
public static void main(String[] args) {
Demo demo = null;
demo.classMethod();
//demo.objectMethod();// throws NPE if uncommented
}
}
This code will work (even if the demo variable is null) because static method classMethod is contained within the class Demo. The commented line will throw a NullPointerException because the method objectMethod is not contained in the class but in the object so will need an instance of Demo class to call it.
Subroutine is a method written inside a class. We use them to do various tasks. That statement states that these methods/subroutines are written in an object or a class.
If we have an object instantiated, it will create new methods for every non-static method for that object which were defined in the class of the object. Hence those non-static methods/subroutines are in the object.
But if the class is a static class, we can't have any objects from it. But we can use subroutines/methods of that class. So, they are in a Class
That's what your statement says.
EDIT:
I thought to give an example for this.
public class ExampleClass {
public String getNonStaticString() {
return "This String is From Non-Static Method";
}
public static String getStaticString() {
return "This String is From Static Method"
}
}
Then, if you need to get the static String, all you have to do is
String staticString = ExampleClass.getStaticString();
Note that I havn't created an object from the ExampleClass Here. I just used the method.
But, if you need to get the String from the non-static method, you should instantiate an object first.
ExampleClass exampleObject = new ExampleClass();
String nonStaticString = exampleObject.getNonStaticString();
static methods also known as class method. Static method associated only with the class and not with any specific instance of that class(object).
So, every subroutine is contained either in a class or in an object
The statement is technically not 100% correct.
First of all, subroutines in java are commonly called methods. The following two terms are often used interchangeably:
Method: A subroutine working with an object instance, this.
Function: A subroutine not working with an object instance.
Here is an example scenario which should you get an idea what that means:
public class Circle {
//region static code
//we cannot call "this" in a static context, main(String[]) is no exception here
public static void main(String[] args) {
Circle a = new Circle(0, 0, 10);
Circle b = new Circle(10, 10, 2);
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("circumference of a = " + a.getCircumference());
System.out.println("circumference of b = " + b.getCircumference());
System.out.println("area of a = " + a.getArea());
System.out.println("area of b = " + b.getArea());
System.out.println("distance of a, b = " + distance(a, b));
System.out.println("a, b intersect = " + (intersects(a, b) ? "yes" : "no"));
}
//we cannot call "this" in a static context, but we have the circles a, b as parameters we can use to calculate their distance
public static double distance(Circle a, Circle b) {
return Math.sqrt(squared(a.x - b.x) + squared(a.y - b.y));
}
//we cannot call "this" in a static context, but we have the circles a, b as parameters we can use to check for an intersection
public static boolean intersects(Circle a, Circle b) {
return a.radius + b.radius > distance(a, b);
}
//we cannot call "this" in a static context, but we have the number x as parameter we can use to calculate the square of
public static double squared(double x) {
return x * x;
}
//we cannot call "this" in a static context, but we have the number radius as parameter we can use to check if its value is in range
public static void checkRadius(double radius) {
if(radius < 0) {
throw new IllegalArgumentException("radius must be >= 0");
}
}
//endregion
//region member / instance code
private double x;
private double y;
private double radius;
public Circle(double x, double y, double radius) {
checkRadius(radius);
this.x = x;
this.y = y;
this.radius = radius;
}
//region getters and setters
//we may refer to the instance variables with or without "this", sometimes it is necessary to clarify - see: setX(double)
public double getX() {
return x;
}
//we may refer to the instance variables with or without "this", but in this case we have two variables with name "x"
//if we write "x", the parameter is taken. for the circle's x coordinate, we need to clarify with "this.x"
public void setX(double x) {
this.x = x;
}
public double getY() {
return y;
}
public void setY(double y) {
this.y = y;
}
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
checkRadius(radius);
this.radius = radius;
}
//endregion
//we may refer to the instance variables with or without "this", sometimes it is necessary to clarify - see: setX(double)
public double getCircumference() {
return 2 * Math.PI * radius;
}
public double getArea() {
return Math.PI * squared(radius);
}
//we may refer to the instance variables with or without "this", sometimes it is necessary to clarify - see: setX(double)
#Override
public String toString() {
return "circle at [" + x + ", " + y + "] with radius " + radius;
}
//endregion
}
Output:
a = circle at [0.0, 0.0] with radius 10.0
b = circle at [10.0, 10.0] with radius 2.0
circumference of a = 62.83185307179586
circumference of b = 12.566370614359172
area of a = 314.1592653589793
area of b = 12.566370614359172
distance of a, b = 14.142135623730951
a, b intersect = no

Accessing composed objects in Java

New to Java.
I have an instance player1 of the Player class below.
Player player1 = new Player(0,0);
Inside the Player class I have composed an object coordinate of type Coord (defined below). When I instantiate player1 above "Player is at coordinate 0,0" is displayed as expected.
public class Player extends Entity {
public Coord coordinate;
public Player(int x, int y) {
Coord coordinate = new Coord(x,y);
System.out.println(“Player is at coordinate “ + coordinate.getX() + “,”
+ coordinate.getY());
}
}
The Coord class is defined as follows.
public class Coord {
private int x;
private int y;
public Coord(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
}
The problem arises when I try to access obj and its respective methods after I instantiate player1. When I try to access coordinate I get a NullPointerException error.
Player player1 = new Player(0,0);
System.out.println(“Player is at coordinate “ + player1.coordinate.getX() +
“,” + player1.coordinate.getY());
What am I doing wrong?
You aren't making Coord obj; a field of your class. That could be as simple as something like
public class Player extends Entity {
Coord obj;
public Player(int x, int y) {
obj = new Coord(x,y);
System.out.println(“Player is at coordinate “ + obj.getX() + “,”
+ obj.getY());
}
}
Note that obj is a terrible field name, and that it has default level access permission here. One way to improve that might be something like
public class Player extends Entity {
private Coord coordinates;
public Player(int x, int y) {
coordinates = new Coord(x,y);
System.out.println(“Player is at coordinate “ + obj.getX() + “,”
+ obj.getY());
}
public Coord getCoordinates() {
return coordinates;
}
}
Then you could use it like
Player player1 = new Player(0,0);
System.out.println(“Player is at coordinate “
+ player1.getCoordinates().getX()
+ “,” + player1.getCoordinates().getY());
You might also override toString() in the Coord class, then you could say
System.out.println(“Player is at coordinate “
+ player1.getCoordinates());

Classes and Objects. Getting 0.0 as answer when calculating price. - JAVA

I'm working out a question from a labsheet but i'm only getting 0.0 as answer when running the program. I can't find out what's wrong please help.
The question:
Implement a class Pizza with attribute diameter (in cm), cost_sq_cm (cost per square cm) and area. Its methods are:
• Constructor to create an object of type Pizza with a given diameter and given price_sq_cm.
• Mutator and accessor methods for diameter and cost_sq_cm.
• calcArea to calculate the area of a given pizza.
• getPrice to calculate and return the price of a pizza.
Write a class TestPizza with a main method that declares an object of type Pizza with a user inputted diameter and user-­‐inputted cost_sq_cm of a circular pizza, and display the price of the pizza.
The Pizza class:
package Number3;
public class Pizza {
private int diameter;
private float cost_sq_cm;
private double area;
private double price;
public Pizza() //default constructor
{
diameter = 0;
cost_sq_cm = 0;
area = 0;
price = 0;
}
public Pizza(int d,float cost,double a,double p) //overloaded constructor
{
d = diameter;
cost = cost_sq_cm;
a = area;
p = price;
}
public void Constructor() //method
{
Pizza P = new Pizza();
}
public void setDiameter(int d) //mutator
{
d = diameter;
}
public int getDiameter() //accessor
{
return diameter;
}
public void setCost(float c)
{
c = cost_sq_cm;
}
public float getCost()
{
return cost_sq_cm;
}
public double calcArea()
{
area = 3.142 * (diameter * diameter);
return area;
}
public double getPrice()
{
price = area * cost_sq_cm;
return price;
}
public void display()
{
System.out.print("The area is: "+this.price);
}
}
TestPizza:
package Number3;
import java.util.Scanner;
public class TestPizza {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
float area = 0;
Pizza P = new Pizza();
int d; float c,a = 0;
System.out.print("Enter a value for the diameter: ");
d = input.nextInt();
P.setDiameter(d);
System.out.print("Enter a value for the cost: ");
c = input.nextFloat();
P.setCost(c);
P.display();
}
}
I'm new to JAVA. Please be lenient.
You should multiply cost per square centimeter times area to get price. You'll get zero if either one is equal to zero. I see where you've set diameter, but not area.
You set diameter, but you don't calculate area when you set it.
public void setDiameter(int d) //mutator; lose this comment. worthless clutter.
{
d = diameter;
area = calcArea();
}
I'd recommend following the Java idiom. Don't write a display() method; better to override toString().
I'd write it this way:
package cruft;
import java.text.DecimalFormat;
import java.text.NumberFormat;
/**
* Pizza
* #author Michael
* #link https://stackoverflow.com/questions/28658669/classes-and-objects-getting-0-0-as-answer-when-calculating-price-java
* #since 2/22/2015 12:27 PM
*/
public class Pizza {
private static final int DEFAULT_DIAMETER = 38;
private static final double DEFAULT_COST = 15.0;
private static final double DEFAULT_COST_PER_AREA = 0.013226; // 15 euro for a 38 cm diameter pizza
private static final NumberFormat DEFAULT_FORMAT = new DecimalFormat("#.####");
private final int diameter;
private final double costPerArea;
private final double price;
public static void main(String[] args) {
int diameter = ((args.length > 0) ? Integer.valueOf(args[0]) : DEFAULT_DIAMETER);
double costPerArea = ((args.length > 1) ? Double.valueOf(args[1]) : DEFAULT_COST_PER_AREA);
Pizza pizza = new Pizza(diameter, costPerArea);
System.out.println(pizza);
}
public Pizza(int diameter, double costPerArea) {
if (diameter <= 0) throw new IllegalArgumentException("diameter must be positive");
if (costPerArea <= 0) throw new IllegalArgumentException("cost per area must be positive");
this.diameter = diameter;
this.costPerArea = costPerArea;
this.price = this.costPerArea*this.calculateArea();
}
public double getPrice() {
return price;
}
private double calculateArea() {
return Math.PI*this.diameter*this.diameter/4.0;
}
#Override
public String toString() {
final StringBuilder sb = new StringBuilder("Pizza{");
sb.append("diameter=").append(diameter);
sb.append(", costPerArea=").append(DEFAULT_FORMAT.format(costPerArea));
sb.append(", price=").append(NumberFormat.getCurrencyInstance().format(getPrice()));
sb.append('}');
return sb.toString();
}
}
For setting a field or another value it is
variable = value;
so
diameter = d;
It looks like your setCost and setDiameter methods need to be changed,
From
d = diameter;
To
this.diameter = d;
Instead of:
System.out.print("The area is: "+this.price);
Use:
System.out.print("The area is: "+this.getPrice());
You need to calculate area as well. So in your main method call it like:
P.calcArea();//to calculate area
You initialised price as 0, when you called new Pizza() and you never called getPrice which is where you calculate the price.
Also change your setter for cost from:
public void setCost(float c) {
c = cost_sq_cm;
}
To
public void setCost(float c) {
cost_sq_cm = c;
}

Java inheritance how to take user input and pass it to sub-sub class?

This is my first ever post here so bear with me please! I have a program that I need to write. Here are the instructions: create a class called areaExcersice in that class you will have a super class called shapes then below it twoDimensionalShapes followed by sub sub class circle and square under the twoDimensionalShapes. In circle extends twoDimensionalShapes, I will pass the user input of radius for example:
System.out.print("what is the radius");
and then
radius = input.nextDouble()
already know how to create and assign classes in a hierarchy system, however, I have no idea how I'm gonna call my circle class under the twiDimensionalShapes. I have to create an if statement so the user can select which shape to choose so something like this "press 1 for circle or 2 for square" and on my
if(user_input == 1){
Here is my question how would I call circle class under twodDimensionalShapes to find the area and pass on radius? Thanks this is all i need to know please if you can just point me out in the good direction i already have created an instance for ex
Circle c = new Circle
Then in my if statement i would do c.getArea() but then where would I put my radius that is asked from the user?
One of my pet peeves with these kinds of projects is they explicitly ask you to create classes when there is no need for them. This only confuses students who can't figure out why they're doing something because there really isn't a reason to do it. You've given no reason to have a Shape class. In the real world I'd take that as an excuse to get rid of it. Since you're required to have one I'm inventing a reason for it to exist: color. This way you can see what Shape might be useful for. If you say "I don't need color" I say "you don't need Shape". See how that works?
I'm using a dirty little trick here called static inner classes so this all works in one file. If you copy this at least take the static of the classes and move them into their own files.
import java.util.Scanner;
public class AreaExcersice {
public static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Choose 1 for circle or 2 for square:");
int userInput = Integer.parseInt( input.nextLine() );
TwoDimensionalShape twoDShape = null;
if (userInput == 1) {
System.out.println("Enter a radius for circle:");
int radius = Integer.parseInt( input.nextLine() );
twoDShape = new Circle("Blue", radius, radius, radius);
} else if (userInput == 2) {
System.out.println("Enter a length for the sides of the square");
int side = Integer.parseInt( input.nextLine() );
twoDShape = new Rectange("Green", 0, 0, side, side);
} else {
System.out.println("Invalid input.");
}
if (twoDShape != null) {
System.out.println( twoDShape.toString() );
}
}
public static abstract class Shape {
String color;
public Shape(String color) {
this.color = color;
}
public abstract String toString();
}
public static abstract class TwoDimensionalShape extends Shape {
int x;
int y;
public TwoDimensionalShape(String color, int x, int y) {
super(color);
this.x = x;
this.y = y;
}
public abstract double getArea();
}
public static class Circle extends TwoDimensionalShape {
int radius;
public Circle(String color, int x, int y, int radius) {
super(color, x, y);
this.radius = radius;
}
#Override
public double getArea() {
return Math.PI * Math.pow(radius, 2);
}
#Override
public String toString() {
return color + " circle at " + x + ", " + y + " with radius " +
radius + " and area of " + getArea();
}
}
public static class Rectange extends TwoDimensionalShape {
int height;
int width;
public Rectange(String color, int x, int y, int height, int width) {
super(color, x, y);
this.height = height;
this.width = width;
}
#Override
public double getArea() {
return width * height;
}
#Override
public String toString() {
return color + " rectange at " + x + ", " + y + " with height " +
height + ", width " + width + " and area of " + getArea();
}
}
}
Displays:
Choose 1 for circle or 2 for square:
1
Enter a radius for circle:
20
Blue circle at 20, 20 with radius 20 and area of 1256.6370614359173
This maybe overkill but it should be clearly showing you what an inheritance structure can do for you. Each class only has implementation code particular to it. Nothing is duplicated. Instead it's shared. Any questions?
You could move anything that's common amongst all of your Shape or TwoDimensionalShape subclasses so that they can be referenced generically:
public abstract class Shape<T extends TwoDimensionalShape> {
public abstract String getName(); // Get the name of the shape for display purposes
public abstract double getArea(); // Get the surface area of this Shape
}
public abstract class TwoDimensionalShape<T extends TwoDimensionalShape> extends Shape<T> {
private double area = 0;
public double getArea() {
return this.area;
}
protected void setArea(double area) {
this.area = area;
}
}
public class Circle extends TwoDimensionalShape<Circle> {
public Circle ( double radius ) {
setArea( Math.PI * Math.pow(radius, 2) );
}
public String getName() {
return "Circle";
}
}
public class Square extends TwoDimensionalShape<Square> {
public Square ( double width, double height ) {
setArea( width * height );
}
public String getName() {
return "Square";
}
}
So the point of having TwoDimensionalShapes is a bit obscure, but we can guess that it defines methods like "getArea()" without implementing them. Each class that extends TwoDimensionalShapes has to implement its own area calculation.
I don't think things like "setArea(double area)" are very useful; areas are not so difficult to calculate that we need to store them, and storing them causes other problems.
So we end up with something like these:
public TwoDShape extends Shape // I have no use for Shape in this example...
{
public double getArea(); // this is an abstract method, hope you've covered those.
}
public Circle extends TwoDShape
{
private double radius;
public Cirlcle(double givenRadius) { radius = givenRadius; }
public double getArea() { return PI*radius*radius; }
}
I've left out a great deal. The getArea() should insure the radius is not 0 and do something like throw an exception if it is, for instance.
Now, to use this, you might have:
public class Main
{
public static void main(String ... arguments)
{
Circle c = new Circle(4.0);
System.out.println("Radius of 4 gives area of " + c.getArea();
}
}
Now, I'll leave Square to you to do, it will be quite similar to Circle. Let us know how it goes. After you've done Square, you'll be able to do something like:
public Main
{
public static void main(String ... arguments)
{
Shape[] shapes = new Shape[3];
shapes[0] = new Circle(4.0);
shapes[1] = new Square(5.0);
shapes[2] = new Square(6.0);
for (shape : shapes)
{
System.out.println("Area is " + shape.getArea());
}
}
}
Thanks guys! You guys are all awesome!! I have not yet covered abstract classes but your explicit code showed me the way! Something clicked on me and alas! i saw the light beaming across the room! I idolize you programmers as well as admire you because someday i will become a professional just like you guys. I am striving to achieve deep knowledge within the programming field and this is just the start. Again thank you so much for clearing my head and pointing me in the right direction! It feels so good to complete a program on your own and have it output correctly and thanks Stack Overflow and all its respective members!I am a noob and first time posting here so i might get down voted for answering in an incorrect format.

Categories

Resources