Hi im new to java i am unsure how to use class function in java . my teacher gave us the point2d class and wants us to use the function in there. there is a function call distanceTo
// return Euclidean distance between this point and that point
public double distanceTo(final Point2D that) {
final double dx = this.x - that.x;
final double dy = this.y - that.y;
return Math.sqrt(dx*dx + dy*dy);
}
i am not sure how am i suppose to implement this. this is my code
public static int calc(int amount)
{
for (int t = 0; t < amount; t++)
{
double current = 0;
double x = StdRandom.random();
double y = StdRandom.random();
Point2D p = new Point2D(x, y);
if ( current < distanceTo(Point2D p ) )
{
}
i tried to use distanceTo(p) and distanceTo(Poin2D) and nothing works.
Thanks in advance
As it is a class function, you need a reference to an instance of the class as well. In this case something like
Point2D b;
p.distanceTo(b); // Invoke distanceTo on b from the point of view of p
This is because your method needs 2 objects to be referenced. The invoking object p and the passed object b, in your function referred to as this and that respectively.
public static int calc(int amount) is static, and distanceTo is not.
For not being static, distanceTo requires an enclosing instance of an object, say: new Point2D().distanceTo(...).
You can then call distanceTo to you some Point2D you already have, say p2:
p2.distanceTo(p);
Or you can try turning distanceTo into a static method, that would receive two points as arguments:
public static double distanceTo(final Point2D one, final Point2D that) {
final double dx = one.x - that.x;
final double dy = one.y - that.y;
return Math.sqrt(dx*dx + dy*dy);
}
And call it using just:
distanceTo(p, p2);
PS.: as an alternative, maybe your solution is to turn calc non-static. You should try it, maybe.
To call a non static method of a class use the . operator.
To call distanceTo, use following syntax:
p.distanceTo(p);
if it was static, use class name with . operator
Point2D.distanceTo(p);
Related
So, I have to create 68 different summing methods using the datatypes, int, float, double and short. The class is called, OverloadingSums. Here is an example of one the methods.
public double sum(double x, float y, int z)
{
return x+y+z;
}
Now I'm being asked to create a class called ZeroSum, essentially copying OverloadingSum and returning everything to zero. Here is an example.
public double sum(double x, float y, int z)
{
return 0;
}
Then I'm being asked to create another class called RealSum, which will extend the ZeroSum class. I'm a little confused about the wording of this assignment, not sure if the stackoverflow community could help but I'm just extremly confused.
Here is the assignment requirements:
Now that we have thoroughly explored overloading we are going to
explore overriding. Create a class called ZeroSum.java. Take all of
the methods from OverloadingSum.java and change them to return all
zeros in ZeroSum.java. Next, create a class called RealSum.java. This
class, RealSum, will extend the ZeroSum class. Having all zeros for
our sums isn't very useful. We will need to override the parent, or
super class methods to produce real results. Create the necessary
methods to override all of those in the ZeroSum.java. When you are
done run your classes against DrivingSum.java.
This is what I have in my main method:
public class DrivingSum {
public static void main(String[] args) {
int x = 10;
int y = 20;
// x + y = 30....yay?
ZeroSum zero= new ZeroSum();
RealSum real= new RealSum();
System.out.println("Calling ZeroSum " + zero.sum(x,y) );
System.out.println("Calling ZeroSum " + real.sum(x,y) );
}
}
So, from how I'm understanding this I wrote the following code:
public class ZeroSum extends RealSum{
public double sum(double x, float y, int z)
{
return super.sum(x,y,z);
}
This will grab the method from RealSum, instead of using the sum method located in the ZeroSum class. So when I run the main method, zero.sum(x,y) gives me 30.
The confusion comes from the fact that the assignment asks me to set everything in ZeroSum returning to zero. If I extend ZeroSum to RealSum, it doesn't really make a difference. Am I doing this correctly? or Am I just overthinking this way too much?
The goal of this assignment is to explore overriding concept, where function executed depends on type of object it called upon on run time, so you will have something like this :
public class ZeroSum {
public double sum(double x, float y)
{
return 0;
}
}
public class RealSum extends ZeroSum{
public double sum(double x, float y)
{
return x+y;
}
}
public class DrivingSum {
public static void main(String[] args) {
int x = 10;
int y = 20;
// x + y = 30....yay?
ZeroSum zero= new ZeroSum();
ZeroSum real= new RealSum();
System.out.println("Calling ZeroSum " + zero.sum(x,y) ); //here the sum will return zero
System.out.println("Calling ZeroSum " + real.sum(x,y) ); //here the sum will return 30
}
I believe he's trying to make a point in which whatever you write in the parent class is transferred (this is called inheritage) to the child. You can override this by writing a method in the child class using the same name and arguments as the parent class' method.
I also believe you read the assignment a bit wrong, it said:
This class, RealSum, will extend the ZeroSum class.
I interpret this as RealSum is the child to ZeroSum, not the other way around as such:
public class RealSum extends ZeroSum{
//code code code
}
This means everything in ZeroSum is set to 0 and RealSum set new values, not using the super. I'm not betting my hand this is correct but try to read the assignment again after a break and some fresh air :)
Hope this helps!
Consider this:
public class Test {
public static int numberOfInstances = 0;
public int myInstanceID;
public String myInstanceName;
The static variable doesn't need to be called within an instance, it's available everywhere like this:
Test.numberOfInstances
When creating an instance, I only do this into my constructor:
public Test(int id, String name) {
myInstanceID = id;
myInstanceName = name;
numberOfInstances += 1;
}
I've recently discovered the this keyword and have noted some of its uses:
public Test() {
this(numberOfInstances + 1, "newInstance");
numberOfInstances += 1;
}
From what I've noticed, the this keyword allows you to call another one of the class' constructors. It also allows you to do this:
public Test(int x, int y) {
this.x = x;
this.y = y;
}
With java, I highly disagree with this style; same variable names, and I don't see the point of using this, especially after looking at the docs example. I look at this:
public Test(int a, int b) {
x = a;
y = b;
However, the use of the this keyword isn't necessary; In my code, I have a variables in my class (e.g. xCoordinate) where I don't use the this keyword (it's not static).
What I've been struggling to understand is what the difference is between non-static variables and this variables. Is there a difference? In one of my classes (the Paddle for Pong), I have this:
public class Pong {
public int xCoordinate;
public int yCoordinate;
and so on...
I never use the this keyword anywhere, and the data is stored within it's own instance.
Bottom line, my question is what is the difference between non-static variables and this.variables. Is it a standard coding practice? Why would I ever you the this keyword on non-static variables?
I think you may have almost answered your own question. You provided the function
public Test(int x, int y) {
this.x = x;
this.y = y;
}
However, what do you think would happen if you wrote it this way instead?
public Test(int x, int y) {
x = x;
y = y;
}
Noticed that I removed the this in the second function. Therefore, x and y would just be referring to the local x and y variables. this allows you to specify that you actually want to use the non-static class variables x and y.
If, as is typical, the parameter variable names of a constructor (say x) are the same as fields of the class, then the field names are shadowed by the parameters passed.
this is used in this case to disambiguate: this.x denotes the field x. It makes perfect sense. this means "reference to the current instance".
So, statements like this.x = x; are quite common.
If you still continue to dislike the Java style, and you adopt m_x-style notation for class fields, then you can write m_x = x; in your constructor. As you rightly point out, this is then not required.
this is also used as the notation for delegating constructors, as you point out.
The "this" keyword allows you to difference between method and instance variables:
public class Point {
private int x;
private int y;
public void add(int x, int y) {
this.x += x;
this.y += y;
}
}
There is no this variables. It's just used to tell the compiler that the variable you want to change is the declared field and not the local variable, in case they have the same name.
For the constructor part, this is just a shortcut for classes which have multiple constructors. You can write the code once and just call that from the alternative constructors.
There is also a similiarly used keyword super, which allows you to call methods and constructors of the superclass:
public SomeClass(int x) {
super(x);
super.someMethod(); // even if we would have overridden someMethod(),
// this will call the one from the superclass
}
Here's one instance where you would need the 'this' keyword:
public class Pong {
public int xCoordinate;
public int yCoordinate;
public Pong (int xCoordinate, int yCoordinate) {
this.xCoordinate = xCoordinate;
this.yCoordinate = yCoordinate;
}
}
Consider the class
public class Complex
{
private double x;
private double y;
public Complex(double x , double y)
{
this.x = x;
this.y = y;
}
}
That represents a Complex number x + y*i , where i is the imaginary part.
I have the following main :
public static void main(String args[])
{
Complex p1 = new Complex(1 , 2); // ok
Complex p2 = new Complex(3 , 4); // ok
Complex p3 = p1 + p2; // Not ok , doesn't compile
}
The third line Complex p3 = p1 + p2; doesn't compile , since there is no operator overloading
in Java . It would have worked in C++ .
Any way around this (in Java) ?
Much appreciated
Operator overloading is not possible in Java. What you have to do instead is to implement methods for the operations.
BigDecimal is a good example of how this should be done in Java:
http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html
note that BigDecimal is a immutable class, this is often a very good idea when you have classes that you in C++ would have operator overload like this for. It makes for cleaner code that is easy to maintain.
Not really no. Operator overloading is not supported in Java for various reasons. You can just provide an add method or something similar.
There is no operator overloading in Java as in C/C++ world, so the + operator is used, let's say only, for primitive numbers (byte, short, int, long, float and double) incremental operations.
This saying you should not complain or get surprised when you find a special case where the + operator is overloaded when it comes to the String Class.
String s1 = "Hello ";
String s2 = "World";
String helloWorld = s1 + s2;
Look at the last line in above code, it is totally legal and will result on a concatenated String and the compiler will never complain about it. Remember that this is the one and only exception.
So instead of overloading some operators, you can seamlessly implement a method that handles your addition stuff:
public class Complex
{
private double x;
private double y;
public Complex(double x , double y)
{
this.x = x;
this.y = y;
}
public Complex add (Complex c)
{
Complex sum = new Complex();
sum.x = this.x + c.x;
sum.y = this.y + c.y;
return sum;
}
}
public static void main(String args[])
{
Complex p1 = new Complex(1 , 2);
Complex p2 = new Complex(3 , 4);
Complex p3 = p2.add(p1);
}
How to call distanceTo(Point p) of Point.java into Point2.java under a method takes no parameter? There should be a way but I cannot find from my materials. Could anybody help me? It has been doing 2 days. Please help...
---------------------Point.java---------------------------------
public class Point{
private int x;
private int y;
//x and y coordinates as parameters
public Point(int x, int y){
this.x = x;
this.y = y;
}
//I want to call this method by calling a method which taken no parameter in Point2.java.
public double distanceTo(Point p){
return Math.sqrt(((x - p.x) * (x - p.x)) + ((y - p.y) * (y - p.y)));
}
}
---------------------ClonePoint.java---------------------------------
public class ClonePoint{
private int a;
private int b;
//x and y coordinates as parameters
public ClonePoint(int a, int b){
this.a = a;
this.b = b;
}
//I failed with this way. Can anybody correct me?
public double measureDistance(){//it should be takes no parameter.
return distanceTo(ClonePoint p)
}
}
----------------------PointDriver.java-----------------------------
public class PointDriver {
public static void main(String [] args) {
Point2 nn = new Point2(11, 22);
Point2 mm = new Point2(33, 44);
System.out.println(nn.distanceTo(mm)); //I succeeded with this!
System.out.println(nn.measureDistance(mm)); //But I got an error illegal start of expression
}
}
#Evan a class is a generalized container for your things. A car, a person, a point (in your case).
Everytime you want to "create" one or more object of your defined class, you instantiate them:
Person evan = new Person();
Person rob = new Person();
both of us are person, you don't really need to define class Person1 and Person2!
And in a class you should define the methods used to "relate" to other similar objects.
For example:
// In Person.java
public void greet(Person p) {
System.out.println("My name is "+this.name+". Nice to meet you +"p.getName());
}
// In main
rob.greet(evan); // it now gives compile errors of course but take the point :P
What you want to achieve is to create a better and more complete Point class with all the methods you want to use. In the end, just initialize more Point objects (same class!) in your main and play with them.
Hope it helps :)
EDIT
Ok, perhaps I've got what your homework wants you to perform.
A "parameter-less" method measureDistance() should make you wonder one important thing: "distance FROM which point????".
Obviously, if the function takes no parameters all the information needed to that calculus must be in the object which calls it. Don't you think?
So, you probably want to achieve a secondary class (if you really need to define it as Point2 it's ok, but change that name because it's confusing) which can take a Point in its constructor (saving this information in itself) and then use that Point to measure distance from it.
Example
public class Point2{
private int a;
private int b;
private Point startingPoint;
public Point2(int a, int b, Point p){
this.a = a;
this.b = b;
startingPoint = p;
}
// Computes the distance from starting point to this
public double measureDistance(){//it takes no parameter.
return startingPoint.distanceTo(a, b);
}
/*
if you can't edit distanceTo() it gets a little verbose but you must create a
Point with Point2 coordinates - remember this example when you will study Inheritance
public double measureDistance() {
Point endingPoint = new Point(a, b);
return startingPoint.distanceTo(endingPoint);
}
*/
}
First, it is not good idea to duplicate a class that does the same thing because you are doing extra unneeded work. Second, if you make various point types, you are loosing the advantage of seamless compatibility between them.
Then, if you want to call method from other class you can do it like this:
NameOfOtherClass.SomeMethod()
But you have to declare the SomeMethod in the other class as static...
public static double SomeMethod() { ... };
But then you can't use the method to access the data of your concrete points you have created in your code, so any data should be put into parameters.
If you want to do it your way, you have to just add a parameter to public double measureDistance()
function so the function has access to another point to measure distance to.
public MyLine(double x, double y)
{
MyLine p1 = new MyLine();
p1.x = x;
p1.y = y;
}
That's my code
and the error I get is
./MyLine.java:12: cannot find symbol
symbol : constructor MyLine()
location: class MyLine
MyLine p1 = new MyLine();
Don't instantiate it inside the constructor. Just assign:
this.x = x;
this.y = y;
The error tells you that you don't have a no-argument constructor, but even if you had, the behaviour won't be as you expect
The error message tells you that you don't have a no-arguments constructor in your MyLine class.
You could create one to let that code compile.
However it looks like you're trying to instantiate a MyLine object inside the MyLine constructor. You almost certainly don't want to do this.
Instead you want to take the values passed as arguments and initialize the fields of the current object with them:
public MyLine(double x, double y)
{
this.x = x;
this.y = y;
}
Provide default constructor
i.e. add
public MyLine(){}
and it doesn't makes sense you are creating local object to constructor and assigning values to is..
instead use
this.x=x;
this.y=y;
This line:
MyLine p1 = new MyLine();
should be removed. That's creating a new instance, you actually want to work with the instance you're creating (since you're in the constructor.) You're getting the error because you're calling a constructor from this line that doesn't exist, but you don't want to be doing that anyway.
You can use the this keyword to reference the current instance (which you need to do if the fields have the same name as the parameters, which in this case it looks like they do.)
So taking that into account, you'd end up with the following:
public MyLine(double x, double y) {
this.x = x;
this.y = y;
}
You're constructing an instance of MyLine inside what appears to be a constructor of MyLine. So the caller of the constructor you're writing will cause two objects to be allocated. Is that what you want?
Do you really mean to construct a new MyLine object while constructing another MyLine object?
Do you really mean to do:
public MyLine(double x, double y)
{
this();
this.x = x;
this.y = y;
}
You really shouldn't instantiate a new MyLine inside your other constructor. Why not simply do:
public class MyLine {
private double slope;
private double constant;
// creates a new line: f(x) -> m*x + b
public MyLine(double m, double b) {
this.slope = m;
this.constant = b;
}
// ...
}
The problem is that once you create a constructor yourself, like public MyLine(double x, double y) the compiler won't add the public MyLine() default constructor automatically.
If you want to make this a factory method you should return p1 and maybe make it static.