Abstract classes in java not taking any value - java

I am having a problem with abstract classes, the code runs but it won't take any value , it prints "0.0" everywhere, I'm thinking it is an acces problem.I have to make an abstract base class called "Point" where i declare the 3 coordinates of a point, then i have to calculate the area , volume and center point of a cube and a sphere .Also if something doesn't look good, needs formating, or don't understand a word, please tell me.Thank you.
//this is the base class
public abstract class Punct
{
public double x,y,z;
Punct(double x,double y, double z)
{
this.x=x;
this.y=y;
this.z=z;
}
public double getX()
{
return x;
}
public double getY()
{
return y;
}
public double getZ()
{
return z;
}
}
Then the sphere
//This is the sphere class that extends the Point class
public class Sfera extends Punct
{
private double aria,volumul,raza,centrul;
Sfera(double x, double y, double z,double aria,double volumul,
double centrul,double raza)
{
super(x, y, z);
this.aria=aria;
this.volumul=volumul;
this.centrul=centrul;
this.raza=raza;
}
public double getRaza(Punct p1,Punct p2)
{
raza=Math.sqrt(Math.pow(p2.x-p1.x,2)+Math.pow(p2.y-p1.y, 2)+Math.pow(p2.z-p1.z, 2));
return raza;
}
public double getAria()
{
aria=4*Math.PI*raza*raza;
return aria;
}
public double getVolumul()
{
volumul=4/3*Math.PI*raza*raza*raza;
return volumul;
}
public double getCentrul(Punct p1)
{
return centrul;
}
}
The Cube
//this is the cube
public class Cub extends Punct
{
double latura,aria,volumul,centrul;
Cub(double x, double y, double z,double latura, double aria,double volumul, double centrul)
{
super(x, y, z);
this.latura=latura;
this.aria=aria;
this.volumul=volumul;
this.centrul=centrul;
}
public double getLatura(Punct p1,Punct p2)
{
latura=Math.sqrt(Math.pow(p2.x-p1.x,2)+Math.pow(p2.y-p1.y, 2)+Math.pow(p2.z-p1.z, 2));
return latura;
}
public double getAria()
{
aria=6*Math.pow(latura, 2);
return aria;
}
public double getVolumul()
{
volumul=latura*latura*latura;
return volumul;
}
}
And the Test Class where i have the main
//this is the Test class
public class TestTema
{
public static void main(String[] args_)
{
Punct p1=new Punct(2, 2, 2) {};
Sfera obSfera=new Sfera(1,2,3,1,1,1,1);
System.out.println("Raza sfera:" + obSfera.getRaza(p1,p1));
System.out.println("Aria sfera=" + obSfera.getAria());
System.out.println("Volum sfera= " +obSfera.getVolumul());
// System.out.println("Centrul= "+obSfera.getSuprafata());
Cub obCub=new Cub(1,2,3,1,1,1,1);
System.out.println("Lungime latura cub:"+obCub.getLatura(p1,p1));
System.out.println("Aria cubului="+obCub.getAria());
System.out.println("Volumul cubului="+obCub.getVolumul());
// System.out.println("Suprafata="+obCub.getCentrul());
}
}

Your design is really wrong. Sfera has a method getRaza() that computes the distance between two points. There's no reason to use a Sphere to compute the distance betwwen two points. This should be an instance method of Punct, that should take another point as argument.
But there's worse: instead of just computing the distance between two points, it stores this distance in the Sphere, overwriting its previous raza (not sure why a sphere has a distance):
raza=Math.sqrt(Math.pow(p2.x-p1.x,2)+Math.pow(p2.y-p1.y, 2)+Math.pow(p2.z-p1.z, 2));
You made the same mistake in several other methods: get methods should not change the state of the object.
Now, let's see your code. You start by calling
obSfera.getRaza(p1,p1)
That computes the distance between p1 and itself, so the answer is 0, and this distance is stored in the Sphere (as explained above). So, after this line of code, you've set the sphere's raza to 0. You then execute
obSfera.getAria()
and this method does
aria=4*Math.PI*raza*raza;
return aria;
so, once again, instead of just returning the area of the sphere, it overwrites its area with the computed value, which is 0 since you've set raza to 0 before.
Here's how a sphere class could look like:
public class Sphere {
private final double radius;
public Sphere(double radius) {
this.radius = radius;
}
public double getArea() {
return 4 * Math.PI * this.radius * this.radius;
}
public double getVolume() {
return (4.0 / 3) * Math.PI * this.radius * this.radius * this.radius;
}
}
Key points:
its fields are final: they can't change.
there is no need to store the volume and the area as fields, since they are derived from the radius
getters don't try to modify the object. They just compute a value and return it.

You are using the same point (p1) to calculate raza, thus replacing the value you used in the constructor. And then you used raza to calculate the other values in the Sfera class.
In the Cub class you are doing the same, so the programm is doing what it is supposed to do. If you calculate those things between the point and itself it will give you 0.
As a result the values you used in your constructor where overwritten by your methods.

System.out.println("Raza sfera:" + obSfera.getRaza(p1,p1));
Sorry, I can't translate what is Raza, but this method calculates distance between two points.
You pass into getRaza the same point. Distance between two identical points is zero. That is why getRaza returns zero.
You assign distance between points to internal field Sfera::raza inthe method getRaza
public double getRaza(Punct p1,Punct p2)
{
raza=Math.sqrt(Math.pow(p2.x-p1.x,2)+Math.pow(p2.y-p1.y, 2)+Math.pow(p2.z-p1.z, 2));
return raza;
}
So after calling obSfera.getRaza(p1,p1) the field obSfera.raza equals to zero.
All other methods use obSfera.raza in their formulas:
public double getAria()
{
aria=4*Math.PI*raza*raza;
return aria;
}
public double getVolumul()
{
volumul=4/3*Math.PI*raza*raza*raza;
return volumul;
}
Put raza value into your formulas:
volumul = 4/3*Math.PI*raza*raza*raza = 4/3*Math.PI*0*0*0 = 0
aria = 4*Math.PI*raza*raza = aria=4*Math.PI*0*0
The same is happening with the object obCub

create another object for class Punct and rewrite the code like below:
public class TestTema
{
public static void main(String[] args_)
{
Punct p1=new Punct(2, 2, 2) {};
Punct p2=new Punct(3, 3, 3) {};
Sfera obSfera=new Sfera(1,2,3,1,1,1,1);
System.out.println("Raza sfera:" + obSfera.getRaza(p1,p2));
System.out.println("Aria sfera=" + obSfera.getAria());
System.out.println("Volum sfera= " +obSfera.getVolumul());
// System.out.println("Centrul= "+obSfera.getSuprafata());
Cub obCub=new Cub(1,2,3,1,1,1,1);
System.out.println("Lungime latura cub:"+obCub.getLatura(p1,p2));
System.out.println("Aria cubului="+obCub.getAria());
System.out.println("Volumul cubului="+obCub.getVolumul());
// System.out.println("Suprafata="+obCub.getCentrul());
}
}
classes Cub and Sfera both refering the same object p1, so the distance value Math.pow(p2.x-p1.x,2) always be 0.

Related

How do I create a loop to iterate objects and display calculations of the objects from the array?

I am new to Java and currently doing a small project to learn.
These are the requirements for the project:
Create a class named Circle with a field named radius.
Include default constructor
Include a default constructor that sets the radius to 1 by default.
Include another constructor that receives the radius and sets the radius to the value
received.
Include a method that returns the area of the circle.
-Include another method that returns the circumference of the circle.
Use the PI constant of the Math class for this calculation.
Create a class named TestCircle whose main() method declares 5 Circle objs and stores them in an array
5 circle objects will have different radius values
Using a loop, iterate the objects and display areas and circumference of the objects from the array
if the radius is one, display a message saying "This is a unit circle".
I managed to complete some of the requirements to the best of my ability but I don't know how to
Using a loop, iterate the objects and display areas and circumference of the objects from the array. If the radius is one, display a message saying "This is a unit circle".
class Circle {
double radius;
//constructor to default radius to 1
public Circle() {
this.radius = 1;
}
//constructor to receive values and set it as radius
public Circle(double [] circlesRad) {
this.radius = circlesRad[0];
}
public double computeArea(){
return Math.PI * (radius * radius);
}
public double computeCircumference() {
return Math.PI *2*radius;
}
}
public class TestCircle {
public static void main(String[] args) {
Circle c1 = new Circle();
double circlesRad[] = {1, 34, 56, 23, 93, 18};
for (double rad : circlesRad) {
System.out.println("Circle:"+"\nArea: "+ c1.computeArea()+"\nCircumference: "+ c1.computeCircumference());
if (rad == 1){
System.out.println("Circle:"+"\nArea: "+ c1.computeArea()+"\nCircumference: "+ c1.computeCircumference());
System.out.println("This is a unit circle.");
}
}
}
}
I know its very wrong, and I apologise.
Any help would be much appreciated.
Below is the code:-
class Circle {
double radius;
//constructor to default radius to 1
public Circle() {
this.radius = 1;
}
//you should consider this as just passing a radius value.
public Circle(double circlesRad) {
this.radius = circlesRad;
}
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
this.radius = radius;
}
public double computeArea(){
return Math.PI * (radius * radius);
}
public double computeCircumference() {
return Math.PI *2*radius;
}
}
public class TestCircle {
public static void main(String[] args) {
Circle[] circles = {new Circle(1), new Circle(34), new Circle(56),
new Circle(23), new Circle(93), new Circle(18)};
for (Circle circle : circles) {
System.out.println("Circle:"+"\nArea: "+ circle.computeArea()+"\nCircumference: "+ circle.computeCircumference());
if (circle.getRadius() == 1){
System.out.println("This is a unit circle.");
}
}
}
}

How to effectively utilize inheritance and polymorphism on a interface

I created an interface 'Polygon' that stores the abstract methods: 'area' and 'perimeter'. However, I am not understanding how to effectively use the interface, when the classes that implement Polygon have different computations involved for calculating area and perimeter. In my opinion, I don't even need an interface 'Polygon' since it has no use in my code.
I've tried overriding the method 'area' in the Triangle class, but received the following error:
Triangle is not abstract and does not override abstract method area() in Polygon
since the Triangle area has constructors. I cannot modify the Polygon area method to have the same number of constructors needed for Triangle, because it will not then suit my Rectangle class.
public interface Polygon {
void area();
void perimeter();
}
class Triangle implements Polygon{
private double triangleArea;
private double trianglePerimeter;
public Triangle (){};
public void area(){}; //I've tried overriding method here but get a
compiler error since it is not identical to the Polygon method.
public double area(double base, double height){
triangleArea = base * height * (.5);
return triangleArea;
}
public class Project25 {
public static void main(String[] args) {
Triangle testTriangle = new Triangle();
testTriangle.area(2, 2);
testTriangle.printArea();
I've managed to obtain the answers I need in my code i.e. area and perimeter, but I need to know how to modify my code to utilize inheritance and polymorphism.
The purpose of an interface is to be an abstract view of the common features of the objects.
In case of polygons, you've already identified some things they have on common, i.e. all polygons have an area, and they all have a perimeter.
The abstract view would be to get those common values:
public interface Polygon {
double getArea();
double getPerimeter();
}
Of course, you can only get those values if the polygon is fully defined, e.g. for a triangle the base and the height might be enough to calculate the area, but not the perimeter. Instead, you usually use the lengths of the 3 sides.
public class Triangle implements Polygon {
private final double a;
private final double b;
private final double c;
public Triangle(double a, double b, double c) {
this.a = a;
this.b = b;
this.c = c;
}
#Override
public double getArea() {
// Using Heron's Formula
double p = (a + b + c) / 2;
return Math.sqrt(p * (p - a) * (p - b) * (p - c));
}
#Override
public double getPerimeter() {
return a + b + c;
}
}
A rectangle is even easier.
public class Rectangle implements Polygon {
private final double width;
private final double height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
#Override
public double getArea() {
return width * height;
}
#Override
public double getPerimeter() {
return (width + height) * 2;
}
}
As you can see, since the inputs for calculating area are different, depending on the type of polygon, the area method cannot take a common set of parameters, therefore they must be embedded in the polygon object, so we can get a common area method.
I think,
Methods in Polygon interface should return values (area and perimeter).
Each shape class that implements Polygon should have its own fields and appropriate constructor to initialize them. (length and height for example), which will be used for implementation of area and perimeter.
So,
Class Triangle should have a constructor,
public Triangle (final Double base, final Double height) {
this.base = base;
this.height = height;
};
And your area method should be like,
#Override
public Double area() {
return base * height * (0.5d);
}
And you should use it something like below,
final Polygon polygon = new Triangle(13, 212);
final Double area = polygon.area();
final Double perimeter = polygon.perimeter();
The first problem I see is that you didn't declare the perimeter method in the class that implements the interface, so that would cause a compiler error right there. As to what others said, you're returning a value on both of those methods, so they shouldn't be void methods.
Also, why did you use an overloaded method in the Triangle class?

Java Class type method

I have a home work in a java... I tried many ways, but, apparently, stackoverflow is a last :(
So, I have this class:
public final class Span {
private final double length;
public Span(){
this(0);
}
public Span(double length) {
this.length= length;
}
public double getLength(){
return length;
}
}
public final class Circle {
private Span radius;
//radius with double
public Circle(double radius) {
}
// span
public Circle(Span radius){
this.radius= radius;
}
//calculate area.....
public double area(double radius){
return Math.PI * (radius * radius);
}
But:
**private Span radius**; <---- This is necessary :(
I have to create Span(type) radius (in Circle class), Span diameter and Span perimeter.
public final class Circle {
private Span radius;
//radius with double
public Circle(double radius) {
this.radius = new Span(radius);
}
// span
public Circle(Span radius){
this.radius= radius;
}
//calculate area.....
public double area(){
return Math.PI * (radius.getLength() * radius.getLength());
}
It's hard to see much value in the Span class over and above a raw double. I can think of two features you could add that would make it more useful:
Negative lengths make no sense. I'd add a check in the Span constructor to the throw an IllegalArgumentException if a length less than zero is passed it prior to assignment.
Encapsulating units along with the length (cm, m, inches, feet, etc.) would be an improvement.
Having those, you just need to be able to calculate using spans:
double perimeter = 2.0*Math.PI*Span.getLength();
You should not be setting radius once you construct the Circle. Let it tell you what the area is using the original Span.

Creating a Cylinder Class

I'm currently undertaking a Java class (one of my final ones for my bachelor, yay) and I'm having a really difficult time trying to understand classes and do this problem below. The textbook I'm currently using is quite confusing and I've tried to use other online resources to figure out what I'm doing wrong but I still seem stuck on the question below. Whenever I try and run the program all I get is 0.00.0 for my answer, is this due to myself incorrectly assigning values to cylinder1? Also, for the toString() class how do I even go about doing this? I'm always getting errors on converting doubles to Strings no matter what I can do.
Any help would be appreciated it.
Thanks.
Prompt
Implement the class called Cylinder shown in UML below. The constructor accepts and initializes the radius and height for the Cylinder, while accessors and mutators allow them to be changed after object construction. The class also include methods that calculate and return the volume and surface area of the Cylinder. Lastly, it contains a toString method that returns the name of the shape, its radius, and its height. Create a main method which instantiates 4 Cylinder objects (any parameters), display them with toString(), change one parameter (your choice) in each, and display them again. [15 points]
UML
Code
import java.util.*;
import java.text.*;
import java.io.*;
import java.lang.*;
class Cylinder
{
private double radius, height, area, volume;
public Cylinder(double height, double radius) {
radius = 0.0;
height = 0.0;
}
public double getRadius() {
return radius;
}
public double getHeight() {
return height;
}
public double getArea() {
double area = (2 * Math.PI * radius * height) + (2 * Math.PI * Math.pow(radius, 2));
return area;
}
public void setRadius(double r) {
radius = r;
}
public void setHeight(double h) {
height = h;
}
public double calcVolume() {
double volume = Math.PI * Math.pow(radius, 2) * height;
return volume;
}
public String toString (){
StringBuilder StBuild = new StringBuilder();
StBuild.append(radius).append(height);
return StBuild.toString();
}
public static void main(String[] args) {
Cylinder cylinder1 = new Cylinder(5, 5);
System.out.println(cylinder1);
}
}
Since this is obviously homework I won't give you the answers, but I'll try to explain a few things.
This:
public Cylinder(double height, double radius) {
radius = 0.0;
height = 0.0;
}
is a constructor. When you create an object (and instance of a class) you call this. You call it by doing:
Cylinder cylinder1 = new Cylinder(5, 5);
But what happens in your class? When you call the constructor are you really saving the values you want?
As for the toString method, you could either call the toString for the double (height.toString) or you could just do what I always end up doing which is just cheat by adding a string to it.
public String toString (){
return "Cylinder [ h: " + height + " - r: " + radius + " - v: " + calcValume() + "]";
}
in class Cylinder change the constructor to:
public Cylinder(double height, double radius) {
this.radius = radius;
this.height = height;
}
In void main() :
Cylinder cylinder1 = new Cylinder(5, 5);
System.out.println(cylinder1.calcVolume());
This will work.
But you should shift the main method to some other class.
In the constructor you are setting the radius and height to 0.0. Try:
public Cylinder(double height, double radius) {
this.radius = radius.
this.height = height;
}

how to return a Point in this example

I am trying to return a Point from a circle.java class that extends a shape class. i keep getting a null pointer exception at the moment. i need to retrun the center point using the inherited getPoints(); method but the inhereted method returns a array and value to be returned from circle is not an array. how would i return the center point without makeing a seperate return method.
my Shape class is as follows
import java.awt.Point;
public abstract class Shape {
private String name;
private Point[] points;
protected Shape(){};
protected Shape(String aName) {
name = aName;
}
public final String getName() {
// TODO Implement method
return name;
}
protected final void setPoints(Point[] thePoints) {
points = thePoints;
}
public final Point[] getPoints() {
// TODO Implement method
return points;
}
public abstract double getPerimeter();
public static double getDistance(Point one, Point two) {
double x = one.getX();
double y = one.getY();
double x2 = two.getX();
double y2 = two.getY();
double x3 = x - x2;
double y3 = y - y2;
double ypow = Math.pow(y3, 2);
double xpow = Math.pow(x3, 2);
double added = xpow + ypow;
double distance = Math.sqrt(added);
return distance;
}
}
my circle class is a follows
import java.awt.Point;
public class Circle extends Shape{
private double radius;
public Circle(Point center, int aradius) {
super("Circle");
radius = aradius;
if(radius < 0){
radius = 0;
}
else{
radius = aradius;
}
}
#Override
public double getPerimeter() {
double perim = 2 * Math.PI * radius;
return perim;
}
public double getRadius(){
return radius;
}
}
The simplest solution I can think of is simply to use the setPoints method from the Shape class...
public Circle(Point center, int aradius) {
super("Circle");
//...
setPoints(new Point[]{center});
}
The reason you're getting a NullPointerException is because you never setPoints of Shape.
I'm not sure what points is supposed to contain but the only thing that would kind of make sense to me is all the points within the shape. Which IMO gets a bit tricky to determine with shapes like circles and determining a center point seems even trickier (although I guess for a circle it would pretty much be the middle point of the array depending on the order?).
(On second thought points could also contain whatever the subclass decides it should, like 1 center point for a circle and 4 points for a rectangle..)
Anyway you will have to fill the points array of Shape (by calling setPoints) with some data before you can use getPoints.

Categories