How to override equals in base and child class - java

I have one example where I have overriden equals methods in both base class and child class.
package com.test;
public class Point2D {
private int x = 0;
private int y = 0;
public Point2D(int x, int y) {
this.x = x;
this.y = y;
}
#Override
public String toString() {
return (x + " " + y);
}
#Override
public boolean equals(Object o) {
if (Point2D.class != o.getClass()) {
return false;
}
if ((o instanceof Point2D)) {
if ((((Point2D) o).x == this.x) && (((Point2D) o).y == this.y)) {
return true;
}
}
return false;
}
#Override
public int hashCode() {
return x + y;
}
}
class TestPoint2D {
public static void main(String args[]) {
Point2D d2 = new Point2D(2, 4);
Point2D d3 = new Point2D(2, 4);
Point3D d4 = new Point3D(2, 4, 5);
Point3D d5 = new Point3D(2, 4, 5);
System.out.println(d2.equals(d3));
System.out.println(d3.equals(d5));
System.out.println(d5.equals(d3));
System.out.println(d4.equals(d5));
}
}
class Point3D extends Point2D {
private int z = 0;
public Point3D(int x, int y, int z) {
super(x, y);
this.z = z;
}
#Override
public boolean equals(Object o) {
if ((o instanceof Point3D)) {
if ((((Point3D) o).z == this.z)) {
Point2D obj = (Point2D) o;
return super.equals(obj);
}
}
return false;
}
#Override
public int hashCode() {
return super.hashCode() + z;
}
}
While testing I'm getting output :
true
false
false
false
The expected output is :
true
false
false
true
Could anyone tell me what is missing here ?

As you saw, your code declares two equal Point3D objects (subclass objects) not equal, here d4 and d5. I think this is because of this if statement in Point2D.equals():
if (Point2D.class != o.getClass()) {
return false;
}
o is d5, so its getClass() returns Point3D.class, not the same as Point2D.class. The result returned is also returned from Point3D.equals() and is printed. I think that instead you want
if (getClass() != o.getClass()) {
Jim Garrison is correct, of course, that you can use a debugger to discover.

Related

Finding if the x and y coordinate is within a view is enclosed by two intersecting rectangles, in java

Say I have this view with two subviews A and B, A and B has a color property mColor,
I want a function in the parent view that has this signature: int getColor(int x, int y), which for any given x and y coordinate, return the color at that position, if the x and y coordinates land and the two shapes are overlapped, return the average color of A and B
The problem I am running into is i see myself doing a lot of conditional checks, checking if A is left of B or if A is right of B etc. I feel like I am missing some key intuition
I have a Point class that handles the coordinates"
public class Point {
private final int mX;
private final int mY;
public Point(int mX, int mY) {
this.mX = mX;
this.mY = mY;
}
public int getX() {
return mX;
}
public int getY() {
return mY;
}
}
Here is my subview class:
public class Chart {
private int mColor;
private Point mTopLeft;
private Point mBottomRight;
public Point getTopLeft() {
return mTopLeft;
}
public Point getBottomRight() {
return mBottomRight;
}
public Chart(int mColor, Point topLeft, Point bottomRight) {
this.mColor = mColor;
this.mTopLeft = topLeft;
this.mBottomRight = bottomRight;
}
public int getColor() {
return mColor;
}
public Point getTopRightCorner() {
return new Point(getBottomRight().getX(), getTopLeft().getY());
}
public Point getBottomLeftCorner() {
return new Point(getTopLeft().getX(), getBottomRight().getY());
}
}
My parent view class:
public class View {
private Chart mChartA;
private Chart mChartB;
public View(Chart chartA,
Chart chartB) {
mChartA = chartA;
mChartB = chartB;
}
public boolean doChartsOverlap() {
boolean isOverlapped = true;
if(isChartALeftOfChartBInX() || isChartARightOfChartBInX()) {
isOverlapped = false;
}
if(isChartABottomOfChartBInY() || isChartATopOfChartBInY()) {
isOverlapped = false;
}
return isOverlapped;
}
public final boolean isChartALeftOfChartBInX() {
return mChartA.getBottomRight().getX() <= mChartB.getTopLeft().getX();
}
public final boolean isChartARightOfChartBInX() {
return mChartA.getTopLeft().getX() >= mChartB.getBottomRight().getX();
}
public final boolean isChartATopOfChartBInY() {
return mChartA.getBottomRight().getY() <= mChartB.getTopLeft().getY();
}
public final boolean isChartABottomOfChartBInY() {
return mChartA.getTopLeft().getY() >= mChartB.getBottomRight().getY();
}
public void setChartA(Chart mChartA) {
this.mChartA = mChartA;
}
public void setChartB(Chart mChartB) {
this.mChartB = mChartB;
}
}
Logically, you want to test if the point is in both rectangles; so test if it is in one rectangle and also in the other rectangle. Everything else about whether one rectangle is above, below, left or right of the other is a red herring.
Add this method to the Chart class (use < instead of <= if you only want to paint the interiors):
public boolean contains(Point p) {
return mTopLeft.getX() <= p.getX() && p.getX() <= mBottomRight.getX()
&& mTopLeft.getY() <= p.getY() && p.getY() <= mBottomRight.getY();
}
And this method to the View class:
public int getColor(Point p) {
boolean inA = mChartA.contains(p), inB = mChartB.contains(p);
if(inA && inB) {
// ...
} else if(inA) {
// ...
} else if(inB) {
// ...
} else {
// ...
}
}
You can then overload public int getColor(int x, int y) to return getColor(new Point(x, y)).
Rectangle r1 = new Rectangle(x1, y1, width1, height1 );
Rectangle r2 = new Rectangle(x2, y2, width2, height2);
if ( r1.contains( x3, y3 ) && r2.contains( x3, y3 ) ) {
// (x3,y3) is in both rectangles
}

Type mismatch: cannot convert from Son to Super

I'm making a Stratego game in java and I'm having a problem with one of the game pieces, which throws me the error:
"Type mismatch: cannot convert from General to Piece"
I have all other pieces such as bomb scout, Marshall etc.. all defined and properly working, however, this gGeneral is giving me that error and I can't seem to understand why because when I wrote the code, I literally copy pasted from the other pieces and changed only its value(integer value of a piece to use in combat purposes) and its icon.
this is a sample code from one of the Pieces:
package Strategu.Pecas;
import javax.swing.ImageIcon;
import Strategu.Piece;
public class Major extends Piece {
public ImageIcon imageRed = new ImageIcon(
"D:\\faculdade\\Modelação e Programação\\code\\MOP\\src\\Strategu\\Gallery\\red\\Major.png");
public ImageIcon imageBlue = new ImageIcon(
"D:\\faculdade\\Modelação e Programação\\code\\MOP\\src\\Strategu\\Gallery\\blue\\Major.png");
ImageIcon image = null;
int value;
public String nome;
public int cx;
public int cy;
public Major(int alliance) {
super(alliance, Cx, Cy);
this.value = 7;
if (alliance == 0)
image = imageRed;
if (alliance == 1)
image = imageBlue;
this.nome = "Major";
}
#Override
public String getNome() {
// TODO Auto-generated method stub
return nome;
}
#Override
public boolean canMoveTo(int x, int y) {// movimento basico de todas as unidades expto o scout
if ((x == Piece.Cx + 1 & y == Piece.Cy) | (x == Piece.Cx & y == Piece.Cy + 1)
| (x == Piece.Cx - 1 & y == Piece.Cy) | (x == Piece.Cx & y == Piece.Cy - 1)) {
return true;
} else {
System.out.println("movimento invalido");
}
return false;
}
#Override
public ImageIcon getIcon() {
// TODO Auto-generated method stub
return image;
}
#Override
public int getValue() {
// TODO Auto-generated method stub
return value;
}
}
and this is the General piece that I don't know why is giving me so much trouble with a type mismatch error
package Strategu.Pecas;
import javax.swing.ImageIcon;
import Strategu.Piece;
public class General extends Piece {
public ImageIcon imageRed = new ImageIcon(
"D:\\faculdade\\Modelação e Programação\\code\\MOP\\src\\Strategu\\Gallery\\red\\General.png");
public ImageIcon imageBlue = new ImageIcon(
"D:\\faculdade\\Modelação e Programação\\code\\MOP\\src\\Strategu\\Gallery\\blue\\General.png");
ImageIcon image = null;
int value;
public String nome;
public int cx;
public int cy;
public General(int alliance) {
super(alliance, Cx, Cy);
this.value = 9;
if (alliance == 0)
image = imageRed;
if (alliance == 1)
image = imageBlue;
this.nome = "General";
}
#Override
public String getNome() {
// TODO Auto-generated method stub
return nome;
}
#Override
public boolean canMoveTo(int x, int y) {// movimento basico de todas as unidades expto o scout
if ((x == Piece.Cx + 1 & y == Piece.Cy) | (x == Piece.Cx & y == Piece.Cy + 1)
| (x == Piece.Cx - 1 & y == Piece.Cy) | (x == Piece.Cx & y == Piece.Cy - 1)) {
return true;
} else {
System.out.println("movimento invalido");
}
return false;
}
#Override
public ImageIcon getIcon() {
// TODO Auto-generated method stub
return image;
}
#Override
public int getValue() {
// TODO Auto-generated method stub
return value;
}
}
also I'm putting here the abstract class of the piece:
package Strategu;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import Strategu.Place.Spot;
import Strategu.board;
public abstract class Piece {
protected final int alliance; // 0 é vermelho 1 é azul
public static int Cx;
public static int Cy;
protected Piece(int alliance, int x, int y) {
this.alliance = alliance;
this.Cx = x;
this.Cy = y;
}
public void setPieceAtPlace(Place p) {
Piece peça = this;
int x = p.coordinateX;
int y = p.coordinateY;
if (p instanceof Spot) {
board.tab[x][y] = new Place.Spot(x, y, peça);
System.out.println("piece adicionada");
}
}
public void setCxCy(int n, int y) {
this.Cx = n;
this.Cy = y;
}
public void sendToGrave(Piece p) {
if (p.alliance == 1) {
Graveyard.sendToGrave(p);
} else {
Graveyard.sendToGrave(p);
}
}
public abstract String getNome();
public abstract boolean canMoveTo(int x, int y);
// public abstract Piece moveTo();
public abstract ImageIcon getIcon();
public abstract int getValue();
public String toString() {
String Ali;
if (this.alliance == 0) {
Ali = "RED";
} else {
Ali = "BLUE";
}
return Ali + " " + getNome() + " " + "value:" + getValue() + " x:" + Piece.Cx + " y:" + Piece.Cy;
}
}

How can I have access to one item's variables in another class that is not related with it?

I'm new to java and i was searching about this for a long time. How can I have access to the item's b variables in class Player??(the cod i'm posting is a part of my full programm so don't mind if you see methods or variables that are not declared in the following code)
import java.util.Random;
public abstract class Player {
private int x, y;
private String name;
private int pNumber;
private int mLine;
private int tLine;
private boolean possession;
private int c;
private int f = 0;
private int i = 0;
public int getPlx() {
return x;
}
public void setPlx(int x) {
this.x = x;
}
public int getPly() {
return y;
}
public void setPly(int y) {
this.y = y;
}
public String getPName() {
return name;
}
public void setPName(String name) {
this.name = name;
}
public int getPNum() {
return pNumber;
}
public void setPNum(int pNumber) {
this.pNumber = pNumber;
}
public int getMLine() {
return mLine;
}
public void setMLine(int mLine) {
this.mLine = mLine;
}
public int getLine() {
return tLine;
}
public void setTLine(int tLine) {
this.tLine = tLine;
}
public boolean getPos() {
return possession;
}
public void setPos(boolean possession) {
this.possession = possession;
}
private Random rand = new Random();
public void Move() { //me8odos metakinisis
c = rand.nextInt(2);
if (c == 0) {
y++;
} else {
y--;
}
}
public void Pass() {
if (this.possession == true) {
c = rand.nextInt(10);
while ((f == 0) && (i < 10)) {
if (main.barcelona.get(i).name == this.name) {}
}
}
}
public abstract void SpecialMove();
}
public class Ball {
private int x, y;
private Player formerP = null;
private Player currentP = null;
public Ball(int x, int y, Player formerP, Player currentP) {
this.x = x;
this.y = y;
this.formerP = formerP;
this.currentP = currentP;
}
public int getBX() {
return x;
}
public void setBX(int x) {
this.x = x;
}
public int getBY() {
return y;
}
public void setBY(int y) {
this.y = y;
}
void Assign(Player playerP) {
int px = playerP.getPlx();
if (this.currentP == null) {
if (((this.x - px <= 1) || (px - this.x) <= 1)
&& ((this.x - px <= 1) || (px - this.x) = 1)) {
this.currentP = playerP;
this.formerP.possession = false;
playerP.possession = true;
if (this.currentP.team == this.formerP.team) {
int pass = this.currentP.getPasses();
pass++;
this.currentP.setPasses(pass);
} else {
int mistake = this.currentP.getMistakes();
mistake++;
this.currentP.setMistakes(mistake);
}
}
}
this.formerP = this.currentP;
this.currentP = null;
this.formerP = null;
}
}
try BallClassName.getX();
You may have to make getX static
If you don't want to instantiate the class Ball in the Player class and you would like to ensure that all players are playing with the one and only ball, then consider making Ball a Singleton.
In software engineering, the singleton pattern is a design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system.
public class Ball {
private static Ball singletonBall;
private int x;
private int y;
private Player formerP;
private Player currentP;
public static Ball getSingletonBall() {
if(singletonBall == null){
singletonBall = new Ball();
}
return singletonBall;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public Player getFormerP() {
return formerP;
}
public void setFormerP(Player formerP) {
this.formerP = formerP;
}
public Player getCurrentP() {
return currentP;
}
public void setCurrentP(Player currentP) {
this.currentP = currentP;
}
}
If there is something that you need inside Player that you will be using often that won't change throughout the life of the Player object (or sub object in your case), then you might as well pass it to a local variable through the Player constructor.
Let's assume Item B is the Ball and you have a Ball class.
So in player (or sub player) declare your object you want access to:
class Player {
Ball ball;
public Player(Ball ball) {
this.ball = ball;
}
Or if it's just something that you'll be using infrequently or something that's value will change (more likely with a ball), then create a method to perform what you need on the Player object.
class Player {
.
.
.
.
.
public void dribble(Ball ball) {
// do something with the ball
ball.setPosition(10, 20);
ball.update();
}
}
Then whatever instantiates Player can access that method.
public static void main(String[] args) {
Player player = new Player();
Ball ball = new Ball();
player.dribble(ball);
}

Clones method is not working

I seem to be getting an error at the catch CloneNotSupportedException.
public class Segment extends Point implements Cloneable {
private Point p1, p2;
public Segment() {
this.p1 = new Point();
this.p2 = new Point();
}
public Segment clone() {
try {
Segment cloned = (Segment) super.clone();
cloned.p1 = (Point) p1.clone();
cloned.p2 = (Point) p2.clone();
return (cloned);
} catch (CloneNotSupportedException cnse) { // This is the error
cnse.printStackTrace();
return null;
}
}
}
package myclasses;
public class Point implements Cloneable
{
private int x, y;
public Point()
{
x = 0;
y = 0;
}
public Point(int X, int Y)
{
this.x = X;
this.y = Y;
}
public int getX()
{
return x;
}
public int getY()
{
return y;
}
private void setX(int x)
{
this.x = x;
}
private void setY(int y)
{
this.y = y;
}
public void setPoint(int newX, int newY)
{
getX();
getY();
setX(x);
setY(y);
}
public void up(int i)
{
y = getY() + i;
}
public void down(int i)
{
y = getY() - i;
}
public void left(int i)
{
x = getX() - i;
}
public void right(int i)
{
x = getX() + i;
}
public String toString()
{
return "(" + getX() + "," + getY() + ")";
}
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Point that = (Point) obj;
if (y != that.y)
return false;
if (x != that.x)
return false;
return true;
}
public Point clone()
{
try
{
return (Point) super.clone();
}
catch(CloneNotSupportedException cnse)
{
System.out.println(cnse);
return null;
}
}
}
Error reported by javac is
error: exception CloneNotSupportedException is never thrown in body of corresponding try statement
} catch (CloneNotSupportedException cnse) { // This is the error
You can declare Point.clone() like this
public Point clone() throws CloneNotSupportedException
Then javac won't complain. Or even simpler do not try to catch exception.

Point isAbove, isUnder, isRight, isLeft methods

This is my point class;
public class Point
{
private int _x;
private int _y;
public boolean isAbove (Point other)
{
if (_y <= other._y)
return false;
else
return true;
}
public boolean isUnder (Point other)
{
return isAbove(other);
}
public boolean isLeft (Point other)
{
if (_x >= other._x)
return false;
else
return true;
}
public boolean isRight (Point other)
{
return isLeft(other);
}
}
All the above methods not functional as expected and i cannot find what i am doing wrong.
For example:
Point pp1 = new Point(1, 0);
Point pp2 = new Point(0, 0);
System.out.println("isAbove: " + pp1.isAbove(pp2));
System.out.println("isUnder: " + pp1.isUnder(pp2));
System.out.println("isLeft : " + pp1.isLeft(pp2));
System.out.println("isRight: " + pp1.isRight(pp2));
Return all false.
Try this, it should work:
public boolean isAbove (Point other)
{
return _y > other._y;
}
public boolean isUnder (Point other)
{
return other.isAbove(this);
}
public boolean isLeft (Point other)
{
return _x < other._x;
}
public boolean isRight (Point other)
{
return other.isLeft(this);
}
You should negate isRight and isUnder and change <= to < and >= to >.
public class Point {
private int _x;
private int _y;
public Point(int x, int y) {
this._x = x;
this._y = y;
}
public boolean isUnder (Point other)
{
return _y < other._y;
}
public boolean isAbove (Point other) {
return _y > other._y;
}
public boolean isLeft (Point other) {
return _x < other._x;
}
public boolean isRight (Point other)
{
return _x > other._x;
}
}

Categories

Resources