I am doing this piece of school work. its about bin packing problem but its a bit modified about a trolley. There can be two or more piles inside the trolley. What I have done so far is made a parcel class and pile class. There are few rules to this that i need to follow. One of them is that when i put parcel (width 3) inside pile i cant put parcel (width 4) on top of it.
Yes i will have trolley class, pile class and parcel class.
What i am trying to do here make a function inside the pile class that changes the Width of the pile to whatever the width of the Parcel is that was just put in. How do I access parcel width from pile class ? will it just be getW() ? much appreciated the help. Or should i do this inside the trolley class ? not exactly sure how to implement this.
public class Parcel {
private int H;
private int W;
private int customer;
Parcel(int inH, int inW, int inCustomer){
this.H = inH;
this.W = inW;
this.customer = inCustomer;
}
public int setH(){
int x = (int )(Math.random() * 50 + 1);
return x;
}
public int setW(){
int y = (int )(Math.random() * 100 + 1);
return y;
}
public int getW(){
return W;
}
public int getH(){
return H;
}
Your setW() is misnamed. It should be randomizeWidth(). What you should consider doing is to give the above class a valid width setter method, setWidth(int width) that set's the W variable (rename it to width to comply with Java naming conventions -- variable names should begin with a lower-case letter) so that outside classes can call the method and set the width.
Pile should likewise have valid setters and getters for its width and other properties. Pile can then call the Parcel methods above and use the information to set its width. If Pile object holds Parcel objects, then it's probably better for Pile to set its own width based on the widths of the Parcel objects it holds. So my suggestion is that Parcel not set a Pile's width.
Assuming that pile has a field of type parcel, you can just call the getter.
public class Pile
{
Parcel parcel;
public Pile()
{
//instanciate parcel here;
}
public void someMethod
{
int w = this.parcel.getW();
}
}
Related
So I'm extending the Java Rectangle class. And I happen to be a bit confused with the use of this and super and when each should be used. I understand that super is the super class (parent class) and this is the current class you're calling it from.
I currently have a BetterRectangle class extending from the Rectangle class and a method:
boolean isCongruent(Rectangle r)
{
if(r.width == super.width && r.height == super.height)
{
return true;
}
return false;
}
Does it matter if I use this.width and this.height instead of super?
Which would be the more correct way of using regardless both give me the same answer?
If your subclass has field width (and height), then super.width's value can be different than this.width depending on how you initialize the fields. Here is a quick test:-
import java.awt.*;
public class BetterRectangle extends Rectangle {
public int width;
void testWidth() {
System.out.println("width = " + width);
System.out.println("this.width = " + this.width);
System.out.println("super.width = " + super.width);
}
}
--
public static void main(String[] args) {
Rectangle rect = new BetterRectangle();
rect.width = 10; //sets the value of super class's field
((BetterRectangle) rect).width = 90; //sets the value of subclass's field
((BetterRectangle) rect).testWidth();
}
This prints:-
width = 90
this.width = 90
super.width = 10
Note that width and this.width prints the same thing because of data hiding. You'll have to add the super keyword to access the super class's field.
If you don't have a width variable in your subclass, then super.width and this.width point to the same field, so why not just use width?
Hope this helps.
Does it matter if I use this.width and this.height instead of super?
If your subclass has inherited the attributes from its superclass (in this case, Rectangle's width and height), then your subclass now owns width and height as its own attributes.
So if your intention is to access the subclass' attributes, using this (which refers to the class itself) will make more sense isn't it? So I will go with using this.
Attributes inherited to child:
class Parent{
protected int width = 5;
protected int height = 5;
}
class Child extends Parent{
public Child(int width, int height){
this.width = width;
this.height = height;
}
public int getHeight() {
return this.height;
}
public int getWidth() {
return this.width;
}
public int getSuperHeight() {
return super.height;
}
public int getSuperWidth() {
return super.width;
}
}
Test Run:
Child c = new Child(2, 3);
System.out.println(c.getWidth() + " " + c.getHeight()); //2 3
System.out.println(c.getSuperWidth() + " " + c.getSuperHeight()); //2 3
Like what ScarryWombat mentioned, if the attributes are masked by the attributes declared in the subclass, then using this and super makes a difference. this now refers to the attributes declared within the subclass instead of the inherited attributes.
Attributes inherited to child, but masked:
class Child extends Parent{
private int width;
private int height;
public Child(int width, int height){
this.width = width;
this.height = height;
}
public int getHeight() {
return this.height;
}
public int getWidth() {
return this.width;
}
public int getSuperHeight() {
return super.height;
}
public int getSuperWidth() {
return super.width;
}
}
Test Run:
Child c = new Child(2, 3);
System.out.println(c.getWidth() + " " + c.getHeight()); //2 3
System.out.println(c.getSuperWidth() + " " + c.getSuperHeight()); //5 5
In general, there should hardly ever be a genuine need to use either this. or super.
Looking at your iscongruent() method, ask yourself how it could ever return false. Answer : that's only possible if the super class and the sub class both have a member of the same name, that is, there are multiple distinc fields named 'width' and/or 'height'. That's bad practice.
Why is that so ? Suppose these fields are supposed to carry the same semantics. At all time. So then why are there two distinct appearances of the field ? It's plain redundancy and that's a source of bugs. Eliminate one of the two and you're out of the problem. Suppose contrariwise that these fields can possibly carry different semantics. You likely want to expose those semantics in your sub class at least through a getter (and perhaps a setter too). So now you have getters (and perhaps setters) in both your super and sub classes with identical signatures but differing semantics. That's plain anti-design-by-contract. Sub classes should never alter the semantics of methods established by their super class. And finally, if you don't want to expose the same-named field in the sub class, there's nothing to stop you from just naming it 'localWidth' or 'subWidth' or whatever other name that provides a better and more detailed explanation of the intended semantics.
That said, here are some cases where using 'this' and/or 'super' is warranted or even unavoidable :
In constructors, when setting fields from the value of a parameter that has been given the same name as the field :
this.x = x; /* x = x would mean an assignment to the method parameter, not the field */
In overriding implementations, when you also need to execute the code as defined in the super class :
method ( ... ) {
super.method( ... );
/* some extra code here to deal with the extra state in the sub class */
}
There may be more, but in general abundant use of 'this' and 'super' leads to too much 'noise' that can be avoided without harming readability. Of course that's just a matter of opinion and of preferred style.
The best way may be is to look at how standard Java classes accesses the variables. javax.swing.text.DefaultCaret extends Rectangle. Except where there are local variable clashes - the access of variables do not use any this or super specifiers. I would stick to that :).
For example, this is the repaint method:
protected final synchronized void repaint() {
if (component != null) {
component.repaint(x, y, width, height);
}
}
I'm trying to create a program that starts with a Piece class. For the purpose of the exercise every other class extends Piece. The other classes contain methods for moving the pieces, either one space or n spaces.
All of the pieces are stored in a 2D array which the use to move around.
My problem is that if i make an array of Pieces I cannot access the move methods as they are stored in the subclasses. I also can't just cast the object because i have 4 different types that the user can ask to move.
This is the code that adds a piece to the board
//adds a piece based on given type, but only if the space is clear (null)
public void addpiece(String type, String n, String c, int x, int y){
if(board[x][y] == null){
if(type == "FastFlexible"){
board[x][y] = new FastFlexiblePiece(n,c,x,y);
}
else if(type == "FastPiece"){
board[x][y] = new FastPiece(n,c,x,y);
}
else if(type == "SlowFlexible"){
board[x][y] = new SlowFlexiblePiece(n,c,x,y);
}
else if(type == "SlowPiece"){
board[x][y] = new SlowPiece(n,c,x,y);
}
else{
System.out.println("Invaild type");
}
}
}
And this is the code that tries to move the piece, the error I get is because the parent Piece doesn't have a move method, but I can't figure out a way to get the pieces to cast correctly
//Move a piece, two method one for fast and one for slow
public void movePiece(int x, int y, String direction){
if(board[x][y] != null){
if(board[x][y].getType().equals("SlowPiece")){
board[x][y] = board[x][y].move(direction);
}
else if(board[x][y].getType().equals("SlowFlexible")){
board[x][y] = board[x][y].move(direction);
}
}
}
There is another similar method for fast pieces.
Constructor for the slowPiece:
//Constructor
public SlowPiece(String n, String c, int x, int y){
super(n,c,x,y);
this.setType("SlowPiece");
}
But the code doesn't notice what type any of the Pieces are and so I can't cast them correctly
The very aim of Polymorphism is to avoid writing code like the implementation specified for public void movePiece(int x, int y, String direction){.
board[x][y] can refer to SuperType Piece and any of its SubTypes like the SlowPiece, SlowFlexible, FastPiece, FastFlexible. Piece can have the abstract move behavior specified in the definition of the class, without having to provide the implementation. All the SubTypes of Piece class provide their own implementation for move method.
The method public void movePiece(int x, int y, String direction) would simply boil down to this :
public void movePiece(int x, int y, String direction){
board[x][y].move(direction);
}
At runtime, move method is dynamically dispatched depending upon the SubType of Piece class.
My suggestion is to add an abstract method to the parent Piece class.
public class Piece{
public abstract void move();
}
NOTE: now you can't directly instantiate a Piece. This code is illegal:
Piece p = new Piece();
How public members of a class causes havoc in java? Can someone please explain with example? I tried to create such situation but couldn't succeed. I simply found them equivalent to 'protected' access modifier.
It allows invalid values, breaking encapsulation.
public class Clock {
public int hours;
public int minutes;
}
Then, in unrelated code...
Clock clock = new Clock();
clock.hours = 42;
clock.minutes = 99;
Having them private with setter and getter methods allows encapsulation to enforce proper values.
public class Clock {
private int hours;
private int minutes;
public void setHours(int hours) {
if (hours < 0 || hours > 23) throw new IllegalArgumentException("bad range");
this.hours = hours;
}
// Likewise for "setMinutes" method.
}
Here's a tutorial page on encapsulation in Java on encapsulation's benefits. Quoting:
The fields of a class can be made read-only or write-only.
A class can have total control over what is stored in its fields.
The users of a class do not know how the class stores its data. A
class can change the data type of a field, and users of the class do
not need to change any of their code.
I believe it all depends on the application/program that you design.
Declaring the members as private definitely does have advantages.
But on the other hand,
If you design say a Point Class, which the users would be inheriting
and using it to draw various shapes, square, rectangle, circle, you
might think of keeping the memebers x, y, z as public.
Example:
class Point{
public double x = 0.0;
public double y = 0.0;
public double z = 0.0;
}
The advantage here would be; the classes Rectangle, Square, can access the points directly
say;
class Square extends Point{
private Point p;
p.x = 4.0;
p.y = 10.0;
p.z = 0;
// Instead of using double x = p.getX(); double p.setX(5.0);
}
Hope this helps.
Read the below articles; it should help you.
Source 1
Source 2
Source 3
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 getting a syntax error "insert } to complete ClassBody.
This code works ok/ error free:
import java.awt.Rectangle;
class Trigger
{
Type type;
long time;
ObjectID controlType;
int controlNum;
int resType, resNum;
Rectangle location;
enum Type {TIMED, CONTROLED, LOCATION, RESOURCE};
Trigger()
{
}
}
However when I add in constructors like this I get the error:
class Trigger
{
Type type;
long time;
ObjectID controlType;
int controlNum;
int resType, resNum;
Rectangle location;
enum Type {TIMED, CONTROLED, LOCATION, RESOURCE}; //I get the error on this line
Trigger(Type.TIMED, long t)
{
time = t;
}
Trigger(Type.CONTROLLED, int c)
{
controlNum= c;
}
Trigger(Type.LOCATION, int locx, int locy, int w, int h)
{
location = new Rectangle(locx, locy, w, h);
}
Trigger(Type.RESOURCE, int resT, int resN)
{
resType = resT;
resNum = resN;
}
}
**Note that I am writing this code in processing!
also if I move the enum line to the top (above "Type type;") then the error message jumps to the line "Rectangle location;"
so what is going on here? I don't understand why I do not get an error for the first code but i do for the second!
Update
ok I changed the code to make the enum initialize the type variable in each constructor. This is going to be for an rts I am helping to design for a class project. There is another class called GameEvent that has have an instance of trigger in it and an array list of actions. The triggers will be uploaded from a file and then the actions will be hardcoded ( I know bad style but there are only 3 missions and the TA said that we wouldn't be losing marks for doing that). So children classes sounds like a good idea. But how come it isn't working as is?
here's the updated code:
import java.awt.Rectangle;
class Trigger
{
Type type;
long time;
FCObjectID controlType;
int controlNum;
int resType, resNum;
Rectangle location;
enum Type {TIMED, CONTROLED, LOCATION, RESOURCE};
Trigger(Type.TIMED, long t)
{
type = TIMED;
time = t;
}
Trigger(Type.CONTROLLED, int c)
{
type = CONTROLED;
controlNum= c;
}
Trigger(Type.LOCATION, int locx, int locy, int w, int h)
{
type = LOCATION;
location = new Rectangle(locx, locy, w, h);
}
Trigger(Type.RESOURCE, int resT, int resN)
{
type = RESOURCE;
resType = resT;
resNum = resN;
}
}
Your constructors are incorrect. For example:
Trigger(Type.LOCATION, int locx, int locy, int w, int h)
What do you expect the Type.LOCATION part to do in the parameter list? Each parameter is meant to be a type followed by the name of the parameter (as int locx etc are, correctly).
Were you trying to add different constructors depending on whether the caller was trying to specify a location, a time etc? If so, that's definitely not how you do it... but it sounds like you probably want separate classes for each of those cases anyway.
I would advise against writing your constructors this way.
Your object ends up in different degrees of unusable state depending on which constructor you call. An object ought to be 100% ready to go after construction, without doing anything to surprise clients.
Write one constructor that initializes ALL the member variables, and then call "this" from the others with sensible default values.
You can't use Enum like this. When you create an Enum, you create a Type, so your constructor must take a variable which is the type of your Enum, you can't "force" it like this.
Trigget(Type t, [others arguments]) {
}
I don't grasp what you're trying to do, but you should read some documentation about Enums : http://download.oracle.com/javase/1.5.0/docs/guide/language/enums.html
And it seems to me that you better do some inheritance of your Trigger class. It's not really OO to put a lot of different fields in a class and initialize them depending on some Enum type.
You can easily have a parent Trigger class and then create a children for each Trigger type you need.
Your code doesn't make sense. The argument list for a method (including constructors) must be a list of typed variables, not values. Type.TIMED is a value, not a type!
k I changed my constructors to this and it works:
Trigger(Type tT, long t, int c, int locx, int locy, int w, int h, int resT, int resN)
{
type = tT;
if (type == Type.TIMED)
time = t;
else if (type == Type.CONTROLLED)
controlNum = c;
else if (type == Type.LOCATION)
location = new Rectangle(locx, locy, w, h);
else if (type == Type.RESOURCE)
{
resType = resT;
resNum = resN;
}
}