Java Composition and Aggregation at same class? - java

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.

Related

Why doesn't Project Valhalla introduce mutable structs?

Looks to me like primitive classes could behave more efficiently (at reasonable sizes) if they weren't immutable as currently proposed, but worked more like C structs.
Given this primitive class
primitive class Point implements Shape {
public long x;
public long y;
public Point(long x, long y) {
this.x = x;
this.y = y;
}
public boolean contains(Point p) {
return equals(p);
}
}
interface Shape {
boolean contains(Point p);
}
And an array Point[] points = new Point[N];
Why wouldn't we be able to do this?
points[0].x = 42; //lastore
points[1].x++; //laload, iinc, lastore
Point p = points[2]; //laload, laload
Shape s = p; //new Point.ref (boxing)
p.x++; //iinc
assert !s.contains(p);
Instead it sounds like current design intends for the whole Point be read, mutated using withfield and written back in its entirety, which seems kind of wasteful - especially for larger types. Or would compilers routinely apply copy elision here?
Note that Point must be flattened instead of flattenable here, so the user can be certain not to mutate a shared instance.
Could someone further clarify the rationale behind immutability of primitive types?
#see
JEP 401: Primitive Classes (Preview)
State of Valhalla - Part 3: The JVM Model

Need help to write a translate method in my segment method

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.

Call a method from another class(not main class)

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.

How to deal with JavaDoc comment repetition?

I was wondering what the best way of documenting this potential Point class is:
public class Point {
/* the X coordinate of this point */
private int x;
/* the Y coordinate of this point */
private int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
}
My concrete concern lies with the repetition between the x and y attributes and their respective getters and setters, as well with the constructor arguments.
It's not that I'm developing a public API or anything of the likes, it's no problem for me to have a general comment regarding some variable and then having the getter and setter have just the same text, for instance. I'd just like to avoid comment repetition in my own internal code. Is there a way to tie getX() and the int x argument of the constructor to the x attribute, for instance?
Thanks
Is there a way to tie getX() and the int x argument of the constructor
to the x attribute, for instance?
No, not that I'm aware of. What I do:
don't comment getters (or setters) at all
if X needs contextual information and if it somehow represents (part of the) state of the class I document it in the class-level Javadoc only
One obvious convention would be not writing JavaDoc comments for trivial getters.

Java constructor explanation please? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
I dont understand how a constructor works
In the following code i know that we have a class, then two variables. When you create a variable you create a container for a value, so by declaring the variables x and y we created two containers, and they contain 0,0.
why the constructor, why the a and b?
public class Point {
public int x = 0;
public int y = 0;
//constructor
public Point(int a, int b) {
x = a;
y = b;
}
}
Constructors are used to initialize instances of classes.
Each instance's x and y values are initialized to what you pass in to the constructor, here, the parameters are named "a" and "b".
In general, direct public access to instance variables is frowned upon, instead they'd be accessed through getters and setters.
This constructor is used in another class. In this case it looks like you're trying to make a "point on a graph" so with that assumption in another class you would use this constructor to make an instance of the Point class.
public class Example {
private Point pt;
public static void main(String[]args) {
pt = new Point(20,10);
}
}
This example creates a new instance of the Point class where x is 20 and y is 10.
We have the code here, I'll explain it line by line.
public class Point {
public int x = 0;
public int y = 0;
//constructor
public Point(int a, int b) {
x = a;
y = b;
}
}
First of all we have the public class Point {, this is the start of the class. All of the classes functions/variables go inside of this brace.
public int x = 0;
public int y = 0;
x and y are being declared here. By declaring them outside of any of the funcions, we're making them global and accessible to the entire class. These two variables are public which means they can be accessed outside of the script, but because they are not static, they can only be called from outside of the script after a new instance of Point has been created.
public Point(int a, int b) {
This line of code is called the constructor. We can see this because it (a) doesn't have a return type and (b) shares the same name as the class. The instructor is called when a new instance of the class is created via the new keyword. I.E. new Point().
int a and int b are two required variables, so you must create your new instance of this class like so new Point(5, 10); where 5 represents A and 10 represents B.
Inside of your constructor you are setting the variables x and y to contain the two values passed to the constructor. So X will become 5 using my example, and Y will become 10.
X and Y will not be 0 because they have both already been created using the value of 0, and are now being set to a different value.
It is important to note that a constructor does not have to have parameters, and it could simply be written as public Point() { if you do not need to pass any parameters to it.
"Why the constructor? "
Answer: User "should" instantiate the class Point by giving 2 values to the variables. Which signifies whoever want to use Point, give value and use it.
"Why a and b?"
Answer: 2 explicitly given user values for the variables of Point class. You can even do like this forgetting a and b:
enter code here: public class Point {
public int x = 0;
public int y = 0;
//constructor
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
Let me explain you by using a very easy understanding example so that you can be able to learn and adapt it with easily.
class store
{
protected String nameproduct;
protected String idproduct;
public store(String nameproduct, String idproduct) {
this.nameproduct = nameproduct;
this.idproduct = idproduct;
}
}
Based on what code above that we have declared nameproduct and idproduct as a String. Why I use protected because when you inheritance this class to other class that STILL RELATED so you don't need to declare those variables. So the variables are like a raw material that ready to build and the constructor is tool to developed it.
"x" and "y" values are initialized to what is passed from the constructor, in this case "a" and "b"
When the Point class is instantiated x and y has value 0. But when the class is instantiated by giving user values it make use of this constructor and make the value of x and y as user intended.
ie; one can create:
Point pt=new Point(); //point which has x and y as 0
OR
Point pt=new Point(10,5); //point which has x=10 and y=5

Categories