call a method in class, inheritance - java

I have a problem, the solution is probably very easy, but nothing comes to mind at the moment, so I am looking for a little help.
... so I have a problem with calling the method.
I have a Space 2D class:
public class Space2D {
//several other methods etc.
//for example I will take this method
public double distance(Space2D p1, Space2D p2) {
double dx = p1.x - p2.x;
double dy = p1.y - p2.y;
return Math.sqrt(dx * dx + dy * dy);
}
}
and I want to call it in the SpaceTest class:
public class SpaceTest extends Space3D {
public static void main(String[] args) {
Space2D point2D = new Space2D();
// I also have a Space 3D class that inherits from the 2D class.
// but I want to call the distance method from the Space 2D class so I'll try to do it like this:
point2D.distance(3,4) // <-- wrong
}
}
I would like to put 3 and 4 after p1 and p2 from the distance method but I get a bug that I have to put integers in it if I want to do so, so my question what do I have to put in calling this method so that I can run it, i.e. what do I have to put for this object ?? "Space2D p1"?
point2D.distance (???)
Thank you in advance for your help and explanation, I hope you will help me understand this.

public double distance(Space2D p1, Space2D p2) {
...
This means when you invoke distance you have to pass in two objects of type Space2D.
point2D.distance(3,4) <-- wrong
You tried to invoke it with two integers, which is why you get the error. Points have an x and y coordinate, what does it even mean to ask for the distance between 3 and 4 if the domain is R2.
What you probably want is something like
int dist = point2d.distance(new Point2D(3,0), new Point2D(4,0));

That's because you're putting integers as parameter which is not allowing to take as parameter. Distance function takes distance(Space2D p1, Space2D p2) Space2D object.
You can use like this:
In Space2D Class :
public class Space2D {
private int x;
private int y;
public Space2D(int x, int y) {
this.x = x;
this.y = y;
}
//several other methods etc.
//for example I will take this method
public static double distance(Space2D p1, Space2D p2) {
double dx = p1.x - p2.x;
double dy = p1.y - p2.y;
return Math.sqrt(dx * dx + dy * dy);
}
}
In SpaceTest class :
public class SpaceTest extends Space3D {
public static void main(String[] args) {
Space2D.distance(new Space2D(3, 2), new Space2D(3, 2));
}
}

Related

How to make a class operate with math operation in java? [duplicate]

This question already has answers here:
Operator overloading in Java
(10 answers)
Closed 5 years ago.
I have the following class, which describe one point on XY surface:
class Point{
double x;
double y;
public Point(int x, int y){
this.x = x;
this.y = y;
}
}
So I want to overlad + and - operators to have possibility write run following code:
Point p1 = new Point(1, 2);
Point p2 = new Point(3, 4);
Point resAdd = p1 + p2; // answer (4, 6)
Point resSub = p1 - p2; // answer (-2, -2)
How can I do it in Java? Or I should use methods like this:
public Point Add(Point p1, Point p2){
return new Point(p1.x + p2.x, p1.y + p2.y);
}
Thanks in advance!
You cannot do this in Java. You'd have to implement a plus or add method in your Point class.
class Point{
public double x;
public double y;
public Point(int x, int y){
this.x = x;
this.y = y;
}
public Point add(Point other){
this.x += other.x;
this.y += other.y;
return this;
}
}
usage
Point a = new Point(1,1);
Point b = new Point(2,2);
a.add(b); //=> (3,3)
// because method returns point, you can chain `add` calls
// e.g., a.add(b).add(c)
Despite you can't do it in pure java you can do it using java-oo compiler plugin.
You need to write add method for + operator:
public Point add(Point other){
return new Point(this.x + other.x, this.y + other.y);
}
and java-oo plugin just desugar operators to these method calls.
There is no operator overloading in Java. Apparently for reasons of taste. Pity really.
(Some people will claim that Java does have overloading, because of + with String and perhaps autoboxing/unboxing.)
Let's talk about value types.
Many early classes (and some later ones) make a right mess of this. Particularly in AWT. In AWT you should be explicitly making copies of simple values all over the place. Almost certainly you want to make value types immutable - the class should be final and it should never change state (generally all final fields pointing to effective immutables).
So:
public final class Point {
private final int x;
private final int y;
private Point(int x, int y) {
this.x = x;
this.y = y;
}
public static of(int x, int y) {
return new Point(x, y);
}
public int x() {
return x;
}
public int y() {
return y;
}
public Point add(Point other) {
return of(x+other.x, y+other.y);
}
// Standard fluffy bits:
#Override public int hashCode() {
return x + 37*y;
}
#Override public boolean equals(Object obj) {
if (!(obj instanceof Point)) {
return false;
}
Point other = (Point)obj;
return x==other.x && y==other.y;
}
#Override public String toString() {
return "("+x+", "+y+")";
}
}
The original code was confused between int and double, so I've chosen one. If you used double you should exclude NaN. "Point" tends to imply an absolute point, which doesn't make sense to add. "Vector" or "dimension" would probably be more appropriate, depending upon what you intend.
I've hidden the constructor, as identity is not important. Possibly values could be cached. Possibly it is, say, common to add a point to a zero point, so no points need to be created.
It's possible you might want a mutable version, for example to use as an accumulator. This should be a separate class without an inheritance relationship. Probably not in simple cases, but I'll show it anyway:
public final class PointBuilder {
private int x;
private int y;
public PointBuilder() {
}
public PointBuilder(Point point) {
this.x = point.x;
this.y = point.y;
}
public Point toPoint() {
return new Point(x, y);
}
public PointBuilder x(int x) {
this.x = x;
return this;
}
public PointBuilder y(int y) {
this.y = y;
return this;
}
public PointBuilder add(Point other) {
this.x += other.x;
this.y += other.y;
return this;
}
}
You cannot do this in Java because there is no operator overloading in Java.
You have to use the second option you have mentioned:
Edit: You can add the Add method in the Point class itself
public Point Add(Point other){
return new Point(this.x + other.x, this.y + other.y);
}
You cannot overload operators in java. You will need handle this in Point class.
You cannot override operators in Java. That's one of the reasons why any nontrival math (especially geometric) operations should not be implemented in Java (the Point class above is kind of such a class, if you want it to do some real work, for example a line-line intersection, you'd better do it in C++).

How can I print multiple class instances in one statement? Java

public Class Point{
private double x;
private double y;
public Point() {
super();
}
public Point(double x, double y) {
super();
this.x = x;
this.y = y;
}
public static Point deepCopy(Point p2) {
Point point2 = new Point(p2.x+2, p2.y+2);
return point2;
}
public static Point shallowCopy(Point p4){
return p4;
}
public void setPoint3X(double x3) {
this.x = x+1;
}
public void setPoint3Y(double y3) {
this.y = y+1;
}
public void setPoint2(double x2, double y2) {
this.x = x2+2;
this.y = y2+2;
}
public double getX() {
return x;
}
public void setX(double x) {
this.x = x;
}
public double getY() {
return y;
}
public void setY(double y) {
this.y = y;
}
#Override
public String toString() {
return "Point [x=" + x + ", y=" + y + "]";
}
public class PointDemo {
public static void main(String[] args) {
double x = 0;
double y = 0;
Point point1 = new Point(5, 10);
Point point2 = Point.deepCopy(point1);
Point point3 = Point.deepCopy(point2);
point3.setPoint3X(x);
point3.setPoint3Y(y);
Point point4 = new Point();
point4 = Point.shallowCopy(point3);
Question 4 -
Write a class called Point. The class has two instance fields: x and y, both are of double type.
Write two constructors: one that uses x and y values for a point, and the other uses the first point values to create a second Point object with the exact same x and y values. Write a Demo class to build the following four Point objects.
Point 1: (x=5, y=10)
Point 2: (x=7, x=12). This point needs to be built using the deep copy constructor that copies point 1 and then using only one setter method.
Point 3: (x=10, y=15). This point needs to be built using the deep copy method that uses Point 2 as the original and then using two setter methods to change the required x and y values.
Point 4: This point needs to be built using the shallow copy method and it must use Point 3 as the shallow copy template.
Finally print all four points using one statement.
Okay. So my code gives me all the values from point1-point4 however, I cannot figure out a way to print them all in one statement. Obviously a loop in the demo class can print every Point object but that would be multiple print statements which violates the one print statement requirement.
Also, I cannot use an array in the Point class because it violates the 2 fields requirement.
Can anybody help or give me a suggestion as to how I can take all the Point objects and print it in one statement? Or is that even possible and maybe I am reading the question wrong?
You can use PrintStream.format(format(String format, Object... args):
System.out.format("(%f, %f), (%f, %f), (%f, %f), (%f, %f)\n", point1.x, point1.y, point2.x, point2.y, ...and so on);
I'm going to post this as an answer too since I think it might be what your instructor actually wants.
The key point here is to remember that the toString() method on your class can be used like a regular string and concatenate other strings, and that's what you normally do with + when calling println(). So just use the normal println() method like you've probably been doing already.
System.out.println( "Point 1 - " + point1.toString() + ";\n"
+ "Point 2 - " + point2.toString() + ";\n"
+ "Point 3 - " + point3.toString() + ";\n"
+ "Point 4 - " + point4.toString() + ";" );
You can use streams:
Arrays.stream(new Point[] {point1, point2, point3, point4}).forEach(System.out::println);
or String.format()
System.out::println(String.format("%s %s %s %s", point1, point2, point3, point4));

Calculating distance between two points in 3D

My assignment is to create main class in which I initialize the value of any point to be at (0,0,0) and to be able to access and mutate all three values (x,y,z) individually. To do this I have used getters and setters. My next task is to create a method within my main class (which I shall call "distanceTo") that calculates the distance between two points.
How do I go about creating the method "distanceTo" that calculates the distance between two points by taking in the x,y,z coordinates ? I assume my answer will have something to do with sqrt((x1-x2)^2+(y1-y2)^2+(z1-z2)^2) but I do not know how I can write that in my method in my main class if my points are not defined until my second test point class
So far I only have two points, but I am looking for a more general answer (so that if I created three points, p1 p2 and p3, I could calculate the distance between p1 and p2 or the distance between p2 and p3 or the distance between p1 and p3.
My main class:
package divingrightin;
public class Point3d {
private double xCoord;
private double yCoord;
private double zCoord;
public Point3d(double x, double y, double z){
xCoord = x;
yCoord = y;
zCoord = z;
}
public Point3d(){
this (0,0,0);
}
public double getxCoord() {
return xCoord;
}
public void setxCoord(double xCoord) {
this.xCoord = xCoord;
}
public double getyCoord() {
return yCoord;
}
public void setyCoord(double yCoord) {
this.yCoord = yCoord;
}
public double getzCoord() {
return zCoord;
}
public void setzCoord(double zCoord) {
this.zCoord = zCoord;
}
//public double distanceTo(double xCoord, double yCoord, double zCoord ){
}
My class with the test points:
package divingrightin;
public class TestPoints {
public static void main(String[] args) {
Point3d firstPoint = new Point3d();
firstPoint.setxCoord(2.2);
firstPoint.setyCoord(1);
firstPoint.setzCoord(5);
//System.out.println(firstPoint.getxCoord());
Point3d secondPoint = new Point3d();
secondPoint.setxCoord(3.5);
secondPoint.setyCoord(22);
secondPoint.setzCoord(20);
}
}
As #Dude pointed out in the comments, you should write a method:
public double distanceTo(Point3d p) {
return Math.sqrt(Math.pow(x - p.getxCoord(), 2) + Math.pow(y - p.getyCoord(), 2) + Math.pow(z - p.getzCoord(), 2));
}
Then if you want to get the distance between 2 points you just call:
myPoint.distanceTo(myOtherPoint);
//or if you want to get the distance to some x, y, z coords
myPoint.distanceTo(new Point3d(x,y,z);
You could even make the method static and give it 2 points to compare:
public static double getDistance(Point3d p1, Point3d p2) {
return Math.sqrt(Math.pow(p1.getxCoord() - p2.getxCoord(), 2) + ...
}
P.S. my first answer :)
public double distanceTo(Point3d other) {
return Math.sqrt(Math.pow(this.xCoord-other.getxCoord(), 2)
+ Math.pow(this.yCoord-other.getyCoord(), 2)
+ Math.pow(this.zCoord-other.getzCoord(), 2));
}
Add this to your Point3d class. When you need to calculate the distance in the TestPoints class, you do something like
double distance = firstPoint.distanceTo(secondPoint);
You have two possible approaches, according to what you want to achieve.
You can put your "distanceTo" method inside the class Point3D:
public class Point3d {
...
public double distanceTo(Point3d ) {
return Math.sqrt( Math.pow(this.x - that.x, 2) + Math.pow(this.y - that.y, 2) + Math.pow(this.z - that.z, 2));
}
In this case, you are always using the first point as the first argument, and any other point as the one you want to compute the distance from.
Alternatively, you can have a generic distanceTo method that lives somewhere(such as in your Program class, where you have your main method), that takes two points and compute the distance between those:
public class Program {
static public void main(String[] args) {}
public double distanceTo(Point3d p1, Point3d p2) {
return Math.sqrt( Math.pow(p1.x - p2.x, 2) + Math.pow(p1.y - p2.y, 2) + Math.pow(p1.z - p2.z, 2));
}
}
Which one is better? Depends on how you use them in the common case :)
Just use the getters
float distance = Math.sqrt(Math.pow(secondPoint.getXCoord() - firstPoint.getXCoord()), 2) + ...)
Two ideas.
Either add a:
public double distanceTo(Point3d otherPoint) {
// return distance by using this.getxCoord(), this.getyCoord(), etc.
// and otherPoint.getxCoord(), otherPoint.getyCoord()
}
method to your Point3d class.
Then, at the end of your main method, you can do:
System.out.println(firstPoint.distanceTo(secondPoint));
System.out.println(tenthPoint.distanceTo(ninthPoint));
Or, add a static method to your main TestPoints class:
public static double distanceBetween(Point3d point1, Point3d point2) {
// return distance by using point1.getxCoord(), etc. and point2.getxCoord()
}
Then, at the end of your main method, you can do:
System.out.println(distanceBetween(firstPoint, secondPoint));
System.out.println(distanceBetween(tenthPoint, ninthPoint));

Java error - "invalid method declaration; return type required"

We are learning how to use multiple classes in Java now, and there is a project asking about creating a class Circle which will contain a radius and a diameter, then reference it from a main class to find the diameter. This code continues to receive an error (mentioned in the title)
public class Circle
{
public CircleR(double r)
{
radius = r;
}
public diameter()
{
double d = radius * 2;
return d;
}
}
Thanks for any help, -AJ
Update 1:
Okay, but I shouldn't have to declare the third line public CircleR(double r) as a double, right? In the book I am learning from, the example doesn't do that.
public class Circle
{
//This part is called the constructor and lets us specify the radius of a
//particular circle.
public Circle(double r)
{
radius = r;
}
//This is a method. It performs some action (in this case it calculates the
//area of the circle and returns it.
public double area( ) //area method
{
double a = Math.PI * radius * radius;
return a;
}
public double circumference( ) //circumference method
{
double c = 2 * Math.PI * radius;
return c;
}
public double radius; //This is a State Variable…also called Instance
//Field and Data Member. It is available to code
// in ALL the methods in this class.
}
As you can see, the code public Circle(double r).... how is that different from what I did in mine with public CircleR(double r)? For whatever reason, no error is given in the code from the book, however mine says there is an error there.
As you can see, the code public Circle(double r).... how is that
different from what I did in mine with public CircleR(double r)? For
whatever reason, no error is given in the code from the book, however
mine says there is an error there.
When defining constructors of a class, they should have the same name as its class.
Thus the following code
public class Circle
{
//This part is called the constructor and lets us specify the radius of a
//particular circle.
public Circle(double r)
{
radius = r;
}
....
}
is correct while your code
public class Circle
{
private double radius;
public CircleR(double r)
{
radius = r;
}
public diameter()
{
double d = radius * 2;
return d;
}
}
is wrong because your constructor has different name from its class. You could either follow the same code from the book and change your constructor from
public CircleR(double r)
to
public Circle(double r)
or (if you really wanted to name your constructor as CircleR) rename your class to CircleR.
So your new class should be
public class CircleR
{
private double radius;
public CircleR(double r)
{
radius = r;
}
public double diameter()
{
double d = radius * 2;
return d;
}
}
I also added the return type double in your method as pointed out by Froyo and John B.
Refer to this article about constructors.
HTH.
Every method (other than a constructor) must have a return type.
public double diameter(){...
You forgot to declare double as a return type
public double diameter()
{
double d = radius * 2;
return d;
}
I had a similar issue when adding a class to the main method. Turns out it wasn't an issue, it was me not checking my spelling. So, as a noob, I learned that mis-spelling can and will mess things up. These posts helped me "see" my mistake and all is good now.

A really simple Java question

I'm trying to call angles from from the angle method down below in the Rotate90 method but I'm not sure of the syntax. What is the correct syntax?
import java.lang.Math;
public class CartesianPoint implements Point
{
private double xCoord;
private double yCoord;
public CartesianPoint (double xCoordinate,double yCoordinate)
{
xCoord = xCoordinate;
yCoord = yCoordinate;
}
public double xCoordinate ()
{
return xCoord;
}
public double yCoordinate ()
{
return yCoord;
}
public double angle ()
{
double angles;
angles = Math.cos( xCoord / Math.sqrt( xCoord*xCoord + yCoord*yCoord));
return angles;
}
public double radius ()
{
double radius;
radius = (yCoord*yCoord + xCoord*xCoord); //?
return radius;
}
public Point rotate90()
{
double rotated;
rotated = angles.angle + 90.0; //██████████ Error here ██████████
return rotated;
}
public double distanceFrom(Point other)
{
return 0;
}
}
I think you mean
rotated = angle() + 90.0;
Except I think you'll find that Math.cos uses radians not degrees, so you're not going to get the result you think you are. And shouldn't that be arc cos, not cosine? Something like this might be more what you're looking for:
public double angle()
{
return Math.atan2(ycoord, xcoord) * 180 / Math.PI;
}
If you want rotate90 to return a new Point that is 90 degrees from the current point, then change it to the following:
public Point rotate90()
{
return new CartesianPoint(-yCoord, xCoord);
}
Method invocations in Java always have trailing parentheses even when they don't have any arguments:
rotated = angle() + 90.0;
Method call requires parenthesis even if there are no parameters needed. This is different from other languages, e.g.groovy.
To answer your question directly: If you want to be able to access the variable "angles" from outside the "angle" function, you must make it a class variable. That is, declare it outside of any function, like you have declared xCoord and yCoord. Then refer to it by its simple name without any reference to the function that created it.
Note that if rotate90 tries to reference angle before angles() is called, angle will contain zero (or whatever default value you set) and is unlikely to be useful.
It's not clear to me exactly what you're trying to accomplish. I think that your intent is that the angles function would take the arc cosine, not the cosine.

Categories

Resources