I am trying to write a translate method in a segment class. My variables are p1 = x1, y1 and p2 = x2, y2. How can I create a translate method using these two variables?
I wrote my translate method in my Point class as:
public void translate(int xmove, int ymove) {
x += xmove;
y += ymove;
}
Here my variables are x and y, simple! But for my segment class I am confused and not sure how to put them in the code.
If this is a geometric segment, then it ought to be defined in terms of two Points (a line segment) or two Points and a radius (circular segment), or something along those lines.
In that case, it should have some private fields that store the Point data. Translating the whole segment just means translating each Point in the class.
So if it's a line segment, and you have
class Segment {
Point start;
Point end;
//...
}
then you'd just need
class Segment {
Point start;
Point end;
public void translate(int xmove, int ymove) {
start.translate(xmove,ymove);
end.translate(xmove,ymove);
}
}
This is good design because it reuses your Point class in defining the Segment, and uses Point methods to define Segment methods.
But it does depend a little on quite what you mean by "segment"...
I am not 100% sure this is what you want, but assuming you would like to translate a segment of 2 points
class Segment{
Point point1;
Point point2;
//constructor
public void translateSegment(int xmove, int ymove){
point1.translate(xmove,ymove);
point2.translate(xmove, ymove);
}
}
If you change the method in the point class to private, you will need to do something else. This code is based on the fact that your translate method for a point is public. There are advantages and disadvantages to having an object mutable, and this is a design question you should consider.
Related
I have a code on my super class that want WIDTH and HEGHT from subclass to calculate
public SuperClass{
public Vector2 getCenter(){
float x = this.position.x + WIDTH/2;
float y = this.position.y + HEIGHT/2;
return new Vector2(x, y);
}
public void setCenter(Vector2 position){
float x = position.x - WIDTH/2;
float y = position.y - HEIGHT/2;
setPosition(new Vector2(x, y));
}
}
I have to use static field of WIDTH and HEIGHT but it compilation error cause super class still don't know where is WIDTH and HEIGHT. Can I have static field that overrided in subclass?
You can't do that. The whole point of polymorphism is that super classes know nothing about child classes!
In other words: dependency flows "upwards" only. A child class depends on its superclass, but not vice versa.
If at all, you can do something like this:
public abstract class SuperClass {
protected abstract int getWidth();
to then call getWidth() within your base class algorithms; and your child classes then have to implement those methods - that is how you actually do proper OO design following the Open/closed principle.
So, the solution here is: you step back and do some more reading on OO design; how to do it; and how it actually works with Java. And for the record: you really want to stay way from using static - that is an abnormality in good OO design; and should only be used when you have really good reasons to do so!
Consider we have two class named Point and Line. And Line class has two constructors. This is code of Point class.
// The Point class definition
public class Point {
// Private member variables
private int x, y; // (x, y) co-ordinates
// Constructors
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public Point() { // default (no-arg) constructor
x = 0;
y = 0;
}
}
And this is code of Line class.
public class Line {
// Private member variables
Point begin, end; // Declare begin and end as instances of Point
// Constructors
public Line(int x1, int y1, int x2, int y2) {
begin = new Point(x1, y1);
end = new Point(x2, y2);
}`
public Line(Point begin, Point end) {
this.begin = begin;
this.end = end;
}
}
As you see Line class has two constructor. And First constructor is example of Compositon while second constructor example aggregation. Now, what can we say about this case? Can a class have both aggregation and composition? Thank for your answers.
A generally accepted definition of the difference between aggregation and composition is lifetime responsibility and ownership.
Aggregation: An object A holds references to other objects, but those other objects are shared with other classes. When A is disposed, the other objects continue to live and be used in the application
Composition: An object B is "made" of other objects. When A is disposed, so are the other objects.
It's worth quoting Fowler on this:
Few things in the UML cause more consternation than aggregation and composition
...
Aggregation (white diamond) has no semantics beyond that of a regular association. It is, as Jim Rumbaugh puts it, a modeling placebo
...
Composition (black diamond) does carry semantics. The most particular is that an object can only be the part of one composition relationship
So yes, a class can have both composition and aggregation relationships to the objects it holds references to, but possibly not as per the example you have shown.
Since the defining characteristic of composition (versus aggregation) is having exclusive/non-shareable parts (see https://stackoverflow.com/a/27889087/2795909), your example of a Point-Line part-whole relationship is clearly an aggregation (no matter if you pass the point objects to, or create them in, the constructor) since the two points definijng a line can be shared with other lines.
I have a segment class with includes a bunch of codes. I have stuck on using two methods, isParallel and shorten methods. Here is my code so far(I have a point class as well which linked to this class):
public class Segment {
//two Points that hold endpoints of the segment
private Point p1, p2;
//Default constructor that will set the endpoints to new
//Points with values (0,0) and (4,4)
public Segment(){
this(0, 0, 4, 4);
}
//Parameterized constructor that accepts (int x1, int y1, int x2, int y2)
//and creates and sets the endpoints
public Segment(int x1, int x2, int y1, int y2){
this.p1 = new Point(x1, y1);
this.p2 = new Point(x2, y2);
}
//Parameterized constructor that accepts (Point p1, Point p2) and sets both
//the endpoints to a deep copy of the Points that are passed in.
public Segment( Point p1, Point p2){
this.p1 = new Point(p1.getX(), p1.getY());
this.p2 = new Point(p2.getX(), p2.getY());
}
//Copy constructor that accepts a Segment and initializes the data (of the
//new Segment being created) to be the same as the Segment that was received.
public Segment(Segment other){
p1 = other.getP1();
p2 = other.getP2();
}
public Point getP1(){
return p1;
}
public Point getP2(){
return p2;
}
//The length method returns the length of the Segment.In fact, this method is same as distanceTo method
//So we can use distanceTo method which is already defined in Point class
public double length(){
return (p1.distanceTo(p2));
}
//The translate method returns nothing and should translate, or shift,
//itself (the Segment) by the distances passed in
public void translate(int xmove, int ymove) {
p1.translate(xmove,ymove);
p2.translate(xmove,ymove);
}
//The midpoint method calculates and returns the midpoint of the Segment as a new Point
public Point midpoint(){
return (p1.halfWayTo(p2));
}
//The slope method returns the slope of the Segment as a double.
public double slope(){
return (double)(p2.getY() - p1.getY()) / (p1.getX() - p2.getX());
}
/**
* The isParallel method returns true/false depending on whether the current Segment
* is parallel to the Segment received. Think about how you can tell if two segments
* are parallel. Note: Two overlapping segments ARE parallel.
*/
public boolean isParallel( Segment s1 ){
{
/**
* The shorten method changes its (the Segment's) endpoints so that they are both halfway
* to the midpoint. Example: The segment (0,0)---(12,16) has midpoint (6,8). After
* calling the shorten method, the segment should be (3,4)---(9,12). Each endpoint
* has moved in toward the midpoint (which stayed the same). So (3,4) is halfway between
* (0,0) and (6,8) and (9,12) is halfway between (12,16) and (6,8).
*/
public void shorten();
Can someone give me an idea of how to use these two methods in my code. I really appreciate your help.
Thank you!
I am actually working on the same exact assignment! For the isParallel method, you need to check and see if the current Segment's slope is the same as the slope of the Segment received. I haven't worked on the shorten method so I can't help you with that yet.
Also, in my class (since I'm doing the same assignment), we aren't suppose to use the getX() and getY() methods since they defeat the whole purpose of learning about encapsulation. We need to actually ask the Point class to calculate the information for the points. For example, with the slope method instead of returning return (double)(p2.getY() - p1.getY()) / (p1.getX() - p2.getX());, I made a method inside of Point to calculate the slope of two points called calcSlope. And to call that method within the Slope method inside Segment: return p1.calcSlope(p2);.
Hopefully that helps!
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.
I am trying to understand the difference between 2 methods that have the same name. This is the code I am trying to understand...
public class Test {
public static void main(String[] args) {
MyPoint p1 = new MyPoint();
MyPoint p2 = new MyPoint(10, 30.5);
System.out.println(p1.distance(p2));
System.out.println(MyPoint.distance(p1, p2));
}
}
class MyPoint {
.....
}
public double distance(MyPoint secondPoint) {
return distance(this, secondPoint);
}
public static double distance(MyPoint p1, MyPoint p2) {
return Math.sqrt((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y));
}
Could someone please explain the difference between the 2 distance() methods. What does the type MyPoint actually mean? Why does 1 of the methods have a single MyPoint object, whereas the other method has 2 MyPoint objects?
MyPoint is the type of the object. In the distance(MyPoint p1, MyPoint p2) method, for example, it means that you are passing in 2 objects to this method - the first object is a MyPoint object called p1, and the second object is another MyPoint object called p2.
The difference between the 2 println statements is that the first one runs the distance(MyPoint) method, and the second one runs the distance(MyPoint, MyPoint) method. Additionally, the first method runs the distance() from the MyPoint p1 object to the one passed in to the method (p2), whereas the second distance() method is a static call which calculates the distance between the 2 MyPoint objects passed in to the method (p1 and p2).
The difference is in the way you are calculating. First one does it by the instance's state and second one in by 'static' way.
You might want to look at the real usage. If it is like utility, it makes more sense in make it static.
distance is the method that is used to calculate the distance between two points given as input.
The Class MyPoint depicts point in space. now method distance(Mypoint x) in this class gives you the distance of this point from the reference point passed as parameter, while the static method simply returns the distance between two points passed
Maybe your problem is about the static methods?
p1.distance(p2)
this calls a member function of MyPoint, this call is from a particular instance of MyPoint p1
however
MyPoint.distance(p1, p2)
calls a static method of MyPoint, which doesn't need any instance, but you must add MyPoint. to tell the compiler you are refering to a static method or field.