How do I build a copy constructor that receive another point (x,y) and copy its values ?
I decide a signature: public Point1 (Point1 other) , but I don't know what to write in it...
The Point class looks like:
public class Point1
{
private int _x , _y;
public Point1 (Point1 other)
{
...
...
}
//other more constructors here...
}
I tried:
public Point1 (Point1 other)
{
_x = other._x ;
_y = other._y;
}
But I almost sure I can do it better..
thnx
Nope, your attempt of
public Point1(Point1 other)
{
_x = other._x ;
_y = other._y;
}
is absolutely fine... (I've corrected the parameter type.)
I'd be tempted to make _x and _y final, and make the class final, but that's because I like immutable types. Others definitely have different opinions :)
Cloning on an inheritance hierarchy is slightly trickier - each class in the hierarchy has to have a relevant constructor, pass whatever argument it's given to the superclass constructor, and then copy just its own fields. For example:
public class Point2 extends Point1
{
private int _z;
public Point2(Point2 other)
{
super(other);
this._z = other._z;
}
}
That's not too bad on the implementation side, but if you want to faithfully clone a Point2 you need to know it's a Point2 in order to call the right constructor.
Implementing Cloneable allows this to be done a bit more simply, but there are other things to consider around that... basically cloning objects isn't as simple as it might appear :) (I'm sure there's an entry in Effective Java for it. If you don't have a copy, buy one now.)
Although the question is quite old but here is an example of copy constructor
public class CopyConstructor {
private int id;
private String name;
public CopyConstructor(int id, String name) {
super();
this.id = id;
this.name = name;
}
public CopyConstructor(CopyConstructor copy) {
id = copy.id;
name = copy.name;
}
}
Copy constructor is much easier to implement and we don't need to
implement Clonable interface.
The clone method returns object which needs to cast , we don't need to cast copy
constructor.
Related
In Java, I feel that using Private when declaring an attribute and not declaring a Setter method for it gives the same outcome as using Final when declaring the attribute, both allow the variable to stay constant.
If that is the case, what is the benefit of using Final in this scenario?
Even without a setter other methods in the class can change the attribute so it's a completely different concept.
Many would argue it's not a good thing to do (it adds "side effects" to your program) but it's still possible.
Assumed you are talking about variables, the keywords final and private define different characteristics.
The keyword final denies any changes to the variable and throws compilation errors when modified or changed. However, without specifying public or private, with the default package-private access modifier, it could be accessed by other classes in the same package once initialized (text with bold fonts are corrected by #charsofire and #MC Emperor).
On the other hand, the keyword private rejects the idea of being called by other classes, even in the same package. But it could be changed and modified by methods in the same class, even without setter or getter methods.
For example in the same class of the same package:
public class Student {
private int score;
final int id;
public Student(int id, int score) {
this.id = id;
this.score = score;
}
public void modifyGrade(int newScore) {
// Accepted
this.score += newScore;
}
public void modifyID(int id) {
// Rejected
this.id = id;
}
}
And in different class of the same package:
public class School {
public static void main(String[] args) {
Student student = new Student(0, 35);
// Accepted
System.out.println(student.id);
// Rejected
System.out.println(student.score);
// Accepted
student.modifyGrade(29);
// throws exception
student.id = 5;
// Not visible
student.score = 29;
}
}
Hope this answer helps you well,
and many thanks again to both #charsofire and #MC Emperor, who helped to clarify significantly in this answer.
The answer is Encapsulation
Consider this.
public class Point
{
int x, y;
public Point(int x, int y)
{
this.x = x;
this.y = y;
}
//no getters or setters needed, I can just modify or read x and y directly.
}
public class FinalPoint
{
public final Point point;
public FinalPoint(int x, int y)
{
this.point = new Point(x, y);
}
//no getters needed, I'll just read point since it is public
}
Right now, this FinalPoint has a final Point as an instance field. On the one hand, it means that that instance field cannot be reassigned. However, the fields of that instance field can definitely be reassigned.
For example.
FinalPoint p = new FinalPoint(1, 2);
p.point.x = 4; //I have now modified state! final did not protect us here
The final keyword is powerful, but it does not mean that your data is unchangeable. It only means that that surface level reference is unchangeable - it will force a reference to always point to the same object. That does not stop the object its pointing to from changing it's internal state as much as it wants. The only guarantee final makes is that you always be pointing at the same object.
Which brings us to encapsulation. Encapsulation was created to solve this exact problem and more.
Consider this.
public class EncapsulatedPoint
{
private Point point;
public EncapsulatedPoint(int x, int y)
{
this.point = new Point(x, y);
}
public int getX() { return this.point.x; }
public int getY() { return this.point.y; }
}
Now, because I have encapsulated Point and exposed only the data I can safely expose, I have protected myself from modification. It is impossible to change this object (without using reflection or other hacks the designers are actively removing). It truly is Immutable.
Of course, Encapsulation is not superior to using final. There is a time and a place for both. Knowing when and where allows you to make your software secure.
Private variables will never access from the outside of the class and Final will never change by taking input from the user.
I'm writing a chess game. My basic design is to have a 2d array (8 x 8) consisting of square objects. Squares have a number of fields: int height, int width, Piece piece (null if empty, some type of Piece object otherwise.
NB: Rook, Knight, Bishop, etc. all extend Piece.
Now, I'm getting a little tripped up on how to figure out what moves are legal for a given piece, given my OOP design. Here's what I'm thinking:
1) User clicks square
2) We determine what piece is on square (if empty, return error message)
3) Generate legal moves for that piece on that square
I'm worried about writing code like:
if (clickedSquare.piece.instanceOf(Rook)) {
return Rook.getLegalDestinationSquares(clickedSquare);
} else if (clickedSquare.piece.instanceOf(Bishop)) {
return Bishop.getLegalDestinationSquares(clickedSquare);
} else if...
Which seems really bad. There must be a way to do this that conforms better to OOP but I'm still learning.
Thanks for the help,
Mariogs
You don't need to create that if statement. Just get the current piece on the field and call some method like (getLegalMoves()) or something.
If field is empty - return empty list of allowed moves.
public abstract class Piece {
public abstract List<Field> getFieldsAllowed(Field field);
}
public class Rook extends Piece {
#Override
public List<Field> getFieldsAllowed(Field field) {
// TODO Auto-generated method stub
return null;
}
}
public class Field {
public Piece getPiece() {
// get current piece
}
}
Something like this. Try to find your own solution. This one is not perfect.
public final class Point {
public final int x, y;
public Point (int x, int y){
this.x = x;
this.y = y;
}
}
public abstract class Piece {
private Point location;
protected Piece (Point initial){
this.location = initial;
}
public Point getLocation(){ return location; }
public Point setLocation(Point location){ this.location = location; }
public abstract List<Point> getLegalMoves ();
}
public final class Rook {
public Rook (Point initial){
super(initial);
}
public List<Point> getLegalMoves (){
// you know the current location, and you know you are a Rook,
// so you have all you need to determine the possible points where
// this Rook can go to
}
}
Then in other code, you can do:
List<Point> legalMoves = clickedSquare.piece.getLegalMoves();
which clearly makes abstraction of what actual piece it is acting upon.
If you do need a static method for other purposes, you can define them in each class such as Rook. Delegate the instance methods to the static methods to avoid code duplication. Like this:
public final class Rook {
// constructor etc.
public List<Point> getLegalMoves (){
return Rook.getLegalMoves (getLocation());
}
public static List<Point> getLegalMoves(Point start){
// you know the location (start), and you know this method is for a Rook,
// so you have all you need to determine the possible end points
}
}
However, if you do not need that static method, don't use and don't even write it (or at least don't expose it in the API of the class). Users of your classes will otherwise start to abuse it end will end up writing code as you provided in your start post - those countless if-elses.
By using this solution, you can add more concrete subclasses (Pawn, King, ...) in the future without touching any existing code (that now acts on Piece), which gives you a maintainability advantage compared to your provided approach.
If Rook, Bishop etc are:
public class Rook extends Piece {
#Override
public String getLegalDestinationSquares() {
// returns all leagal Rook squers
return null;
}
}
and Piece is:
public abstract class Piece {
public abstract String getLegalDestinationSquares();
}
Then you might do it like (in your sample):
return clickedSquare.piece.getLegalDestinationSquares();
Return String is just example, probably you should return Collection of squares.
From OOD there are a few critics.
a field is a field even if no figure is on the field. A null-filed therefore does not exists (LSP)!
a figure do never know what moves he can do, this must be set only by the game rules. Create a new class called Rules. Its the responsibility of the rules to know what moves he can do(SRP). A King (for example) must know if he already did a Castling to decide if he can do a Castling, therefore he must know the previous moves, and this breaks the DIP - ah, here we have another class we miss: ChessNotation.
instanceof is usefull when you inherit things, a Rook can not inherit a field (LSP,DIP).
I would like to make it so I can put integers defined by when I calling new Objectives(new Runnable(), "name here", int x, int y, int z) but I cant seem to do it. Again, the ints in the ENUMS will be put there when calling a new Objectives and the Location
Here's my code so far:
package me.terturl.com.Objectives;
public enum Objectives {
MECH(new Runnable() {
#Override
public void run() {
}
}, "Mech", Location loc, int x, int y, int z);
private String name;
private Location loc;
private int x;
private int y;
private int z;
public objectives(Runnable run, String name, Location loc, int x, int y, int z) {
this.name = name;
this.loc = loc;
this.x = x;
this.y = y;
this.z = z;
}
public String getName() {
return name;
}
public Location getLoc() {
return loc;
}
}
All enums are constants. You cannot specify parameters for new instances of an enum. Instead, use a class to construct new objects based on the given parameters.
Example of an enum in usage:
enum WeekDay { MONDAY(1), TUESDAY(2), WEDNESDAY(3), THURSDAY(4), FRIDAY(5), SATURDAY(6), SUNDAY(0); public final int id; WeekDay(int id){ this.id = id; } }
Example of a class that may be used for this case:
package me.terturl.com.Objective;
import org.bukkit.Location;
public class Objective {
private String name;
private Location loc;
private int x, y, z;
Objective(Runnable run, String name, Location loc, int x, int y, int z) {
this.name = name;
this.loc = loc;
this.x = x;
this.y = y;
this.z = z;
}
public String getName() { return name; }
public Location getLoc() { return loc; }
}
Edit: All enums implicitly extend java.lang.Enum. Since Java does not support multiple inheritance, an enum cannot extend anything else. Hence, enums will not achieve what you are looking for - Storing details of an objective. Instead use the above class and create a Manager Class to handle your objectives.
However, enums can implement interfaces, when applicable:
interface MajorObjectWrapper{
public Object getMajorObject();
}
enum Utility implements MajorObjectWrapper {
VAULT("Gold"),
//...
LOCK(new Lock());
#Override public Object getMajorObject(){ return obj; }
private Object obj;
Utility(Object obj){ this.obj=obj };
}
{
MajorObjectWrapper wrapper=Utility.VAULT;
System.out.println(wrapper.getMajorObject());
// You will get: "Gold"! :)
}
Thanks to #nrubin29 for citation on implementing interfaces with enums.
Specified by:
http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html
PS: Your package declaration makes the absolute path of the class me.terturl.com.Objectives.Objectives. Consider refactoring the package declaration as me.terturl.com or me.terturl.com.objectives. Semantics :)
I don't think an enum is what you're looking for. From the Oracle Java tutorial's enum page here:
An enum type is a special data type that enables for a variable to be a set of predefined constants.
Constants. So making new instances really doesn't make sense. And that's also enforced at the language level. JLS section 8.9.2:
It is a compile-time error if a constructor declaration in an enum declaration is public or protected (ยง6.6).
In an enum declaration, a constructor declaration with no access modifiers is private.
So there's your first problem. You can't have a public enum constructor.
Second, you're slightly misunderstanding how enum constant constructors work. When you do something like
MECH(...)
You're effectively calling a constructor. And you can't do things like have int x in a constructor call. You're going to have treat it like any other constructor, which means either you get to put a method call there or some other expression that evaluates to something. Your first two parameters were OK, but the rest of them, not so much.
For example, if I wanted to make a new String(), I can't do this:
String s = new String(String putStringHere);
Similar logic applies to your code.
Honestly, I'm a little confused why you're using an enum. Seems to me like a regular old class would do just fine.
(also, probably a typo, but your constructor should be capitalized)
I am using the Vector2 class of the libGDX API, and if I want to check the equality of two vectors I have to do the following:
Vector2 vectA = new Vector2(0, 1);
Vector2 vectB = new Vector2(1, 1);
if (vectA.x == vectB.x && vectA.y == vectB.y) {
return true;
}
This is very uncomfortable and I am thinking about creating an equals() method for this scenario. Which should be the better to do:
Creating a wrapper for the Vector2 class with an equals(Vector2) method
Creating an EqualUtil class with an equals(Vector2, Vector2) method
The first would look better (in my opinion), but it may not be a 'nice' solution while the other is much cleaner but also a bit simplistic. Different ideas also welcome.
Yes you should.
In my opinion, it is better to create a Wrapper (and you should also override hashCode() to match the new behavior).
Not only doing so will result in more readable code, it will also allow you to use collections such as a HashSet or other methods that rely on the equals() behavior.
It also makes sense logically, because you are trying to create a method that gives data on the specific object - what better way to show it then to do it as an instance method?
I'll go with, overriding both equals() as well as hashCode() method inside a Vector2 class.
From Joshua Bloch Item -9
Always override hashCode when you override equals
Edited:
Scroll down to page 45
Page 45: Item-9
public interface CheckObject(){
public abstract boolean and(CheckObject checkobject);
}
public abstract class AbstractObject()
implements CheckObject
{
public AbstractObject()
{
}
public abstract boolean and(CheckObject checkobject);
protected void beforeObjectChecked(Object obj)
throws IllegalArgumentException
{
}
public class EqualUtil extends AbstractObject {
private int point1;
private int point2;
}
protected EqualUtil(int point1,int point2){
this.point1=point1;
this.point1=point2;
}
public boolean and(CheckObject checkobject){
beforeObjectChecked(checkobject);
return(this.getPoint1()==checkobject.getpoint1() && this.getPoint2()==checkobject.getpoint2()));
}
public int getPoint1() {
return point1;
}
public void setPoint1(int point1) {
this.point1 = point1;
}
public int getPoint2() {
return point2;
}
public void setPoint2(int point2) {
this.point2 = point2;
}
Now you can use it from Main Class
Wrapper's are a good and understandable way to add in new behaviour when the original designers did not include it for some reason. Given that the original API class just uses the java.lang.object equals method, creating a wrapper seems a sensible option to me.
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Property and Encapsulation
NEWB Alert!!
I am starting with Android and Java and I am starting to understand it but I am wondering why I should use getters and setters and not just public variables?
I see many people make a private variable and create a get and set method.
What is the idea here?
Its called encapsulation and the concept is central to object oriented programming. The idea is that you hide the implementation of your class and expose only the contract i.e. hide the how and only expose the what. You hide the variables by making them private and provide public setters-getters and other public methods which the clients invoke to communicate with your class. They are not tied to the actual implementation of the methods or how you store your variables.
For example, suppose you had this class where you stored a phone number as a Long object:
public class ContactInfo {
private Long phoneNo;
public Long getPhoneNo() {
return phoneNo;
}
public void setPhoneNo(Long phoneNo) {
this.phoneNo = phoneNo;
}
}
Since the clients of the class only see the getter/setter, you can easily change the implementation of the class/methods by switching the phone number representation to a PhoneNumber object. Clients of ContactInfo wouldn't get affected at all:
public class ContactInfo {
private PhoneNumber phoneNo;
public Long getPhoneNo() {
return phoneNo.getNumber();
}
public void setPhoneNo(Long phoneNo) {
this.phoneNo = new PhoneNumber(phoneNo);
}
}
public class PhoneNumber {
private Long number;
public PhoneNumber(Long number) {
this.number = number;
}
public Long getNumber() {
return number;
}
}
The OOP concept involved is encapsulation (google it).
Some of the advantages are: you can specify different access level for setters (mutators) and getters (accessors), for example public getter and private setter. Another advantage is that you can add another code other than changing or retrieving the value. For example, you may want to check the validity of the set value, or you want to throw exceptions or raise some events in response to changing the variable to certain value. If you implement these inside an accessor or mutators, you can also change their implementations without changing any code outside of the class.
I believe the idea is "information hiding" http://en.wikipedia.org/wiki/Information_hiding
It also serves to control the access to variables (provides an interface). For example, you can provide a getter but not a setter, so that they may be read but not written. Whereas if everything was public any thing could read and write to the variables.
Also important is any checking/validation need to set a variable. For example you have a String name that is not allowed to be empty but if it is public it could easily be forgotten and set as name = "". If you have a setter such as public boolean setName(String newName) you can check newNames length and return true or false if it passes and is set or not
The concept is called encapsulation.
What it attempts to do is to separate the inner structure of a class from its behaviour.
For example, suppose a class like this
public class Point{
private float x;
private float y;
public float getX(){
return x;
}
public float getY(){
return y;
}
public float distanceToZero2(){
return x*x + y*y
}
public float getAngle(){
//havent considered the x = 0 case.
return atan(y/x);
}
public boolean isInFirstQuad(){
return x>0 && y>0;
}
}
In this case, encapsulation hides the inner structure of the class, and exposes only the operations available to a Point. If you dont like it, you can change its inner structure and mantain its behaviour (for example, changing carthesian coordinates to polar coordinates).
Anyoune who uses this class wont care about it, he /she will be happy that they have a Point class with this functionality.
Asides the encapsulation, you can also control the value get or set to your variable in some cases. For example, you want to validate the value of an age variable which should be >=1
class Person {
private int age = Integer.MIN_VALUE;
public void setAge(int age){
if(age>=1)
this.age = age;
}
public int getAge(){
return age;
}
}