Inheritance casting - java

I have two class.
class Vector{
........
Vector(int x, int y, int z){...........}
public Vector sum(Vector vc){
Vector result;
...........//all working and store to Vector result.
return result;
}
public Vector subtract(Vector vc){................//codes}
}
class Velocity extends Vector{
Velocity(int x, int y, int z){......}
................
}
class Test{
public static void main(String args){
Velocity v1=new Velocity(14,14,14);
Velocity v2=new Velocity(14,14,14);
Vector result=v1.sum(v2); //here I want to get this result as Velocity
//I don't know how to get it....
}
}
In similar manner I have Acceleration, Force, Momentum, Displacement class which extends Vector class....And all have same problem......besides this

Vector.java:
public interface Vector<T extends Vector> {
public int getX();
public int getY();
public int getZ();
public T sum(T other);
}
BaseVector.java:
public abstract class BaseVector<T extends Vector> implements Vector<T> {
private final int x;
private final int y;
private final int z;
public BaseVector(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
protected abstract T createNew(int x, int y, int z);
#Override
public T sum(T other) {
return createNew(x + other.getX(), y + other.getY(), other.getZ());
}
#Override
public int getX() {
return x;
}
#Override
public int getY() {
return y;
}
#Override
public int getZ() {
return z;
}
#Override
public String toString() {
return "BaseVector [x=" + x + ", y=" + y + ", z=" + z + "]";
}
}
Velocity.java:
public class Velocity extends BaseVector<Velocity> {
public Velocity(int x, int y, int z) {
super(x, y, z);
}
#Override
protected Velocity createNew(int x, int y, int z) {
return new Velocity(x, y, z);
}
}
Test.java:
public static void main(String[] args) {
Velocity v1 = new Velocity(14, 14, 14);
Velocity v2 = new Velocity(14, 14, 14);
Velocity result = v1.sum(v2);
System.out.println(result);
}
}

Vector result = ((Velocity)v1).sum(v2);
=========================================================
This will not help, because you defined sum in Vector, returning Vector. To make result a Velocity you would need a sum method returning type Velocity, rather than the one in Vector that returns a Vector.
A better alternative might be to provide a Velocity constructor that takes a Vector
Velocity result = new Velocity(v1.sum(v2));

Related

Cannot find symbols while using abstract classes

Practicing abstract classes with shapes. The goal is to get the total area of the 3 shapes using abstract classes. So far this is what I have.
I'm not sure whether I did this part right:
static double sumArea(Shape[] arr){
// Sum up the areas of all the shapes using getArea()
return arr.getArea();
}
I keep getting error saying that it doesn't find the symbol h (height), w (width), tw (top_width). Anybody know why it's not finding these symbols?
public class TestShape{
public static void main(String args[]){
Point p = new Point(1, 1);
Shape[] arr = {
new Rectangle(p, 3, 4),
new Parallelogram(p, 5, 6, Math.PI/6.0),
new Trapezoid(p, 5, 6, 2)
};
System.out.println("SUM_AREA = " + sumArea(arr));
}
static double sumArea(Shape[] arr){
// Sum up the areas of all the shapes using getArea()
return arr.getArea();
}
}
class Point{
double x, y;
Point(){
this(0, 0);
}
Point(double x, double y){
this.x = x;
this.y = y;
}
public String toString(){
return "[" + x + ", " + y + "]";
}
}
abstract class Shape{
Shape(){
}
Shape(Point p){
this.p = p;
}
public Point getPosition(){
return p;
}
public void setPosition(Point p){
this.p = p;
}
// Abstract method
public abstract double getArea();
}
abstract class Quadrangle extends Shape{
protected double width, height;
Quadrangle(Point p, double w, double h){
this.p = p;
this.width = w;
this.height = h;
}
public double getWidth(){
return w;
}
public double getHeight(){
return h;
}
public void setWidth(double w){
this.weight = w;
}
public void setHeight(double h){
this.height = h;
}
}
class Rectangle extends Quadrangle{
Rectangle(Point p, double w, double h){
this.p = p;
this.width = w;
this.height = h;
}
public boolean isSquare(){
if(w == h){
return "Error";
}
}
#Override /** Return Area */
public double getArea(){
return w * h;
}
}
class Parallelogram extends Quadrangle{
protected double angle;
Parallelogram(Point p, double w, double h, double angle){
this.p = p;
this.weight = w;
this.height = h;
this.angle = angle;
}
public double getAngle(){
return angle;
}
public void setAngle(double a){
this.angle = a;
}
#Override /** Return Area */
public double getArea(){
return w * h;
}
}
class Trapezoid extends Quadrangle{
protected double top_width;
Trapezoid(Point p, double w, double h, double top_width){
this.p = p;
this.width = w;
this.height = h;
this.top_width = top_width;
}
public double getTopWidth(){
return top_width;
}
public void setTopWidth(double tw){
this.top_width = tw;
}
#Override /** Return Area */
public double getArea(){
return ((w + tw) / 2) * h;
}
}
The names w, tw and so on only exist as parameters. When you want to access the values you save in the constructors, you have to use the left hand side name: this.[width or whatever].
Also, rewrite sumArea to something like this:
static double sumArea(Shape[] arr){
// Sum up the areas of all the shapes using getArea()
double totalArea = 0;
for (Shape shape : arr) {
totalArea += shape.getArea();
}
return totalArea;
}

Trying To Implement Player Gravity For My Test Block for Player Class (RealtutsGml Platformer Tutorial)

I am following realTutsgml Tutorial in attempt to implement gravity for the player class which I am using a Linklist to refer to my Gameobject class.
public class Player extends GameObject {
private float width = 32, height = 64;
private float gravity = 0.05f;
public Player(float x, float y, ObjectId id) {
super(x, y, id);
}
public void tick(LinkedList<GameObject> object) {
x += velX;
y += velY;
if(falling||jumping)
{
velY += gravity;
}
}
I was able to draw the test block onto the screen which an instance was created in the game class in the init method
handler.addObject(new Player(100, 100, ObjectId.Player));
GameObject Class
public abstract class GameObject
{
protected float x, y;
protected ObjectId id;
protected float velX = 0, velY = 0;
protected boolean falling = true;
protected boolean jumping = false;
public GameObject(float x, float y, ObjectId id)
{
this.x = x;
this.y = y;
this.id = id;
}
public abstract void tick(LinkedList<GameObject> object);
public abstract void render(Graphics g);
public abstract Rectangle getBounds();
public float getX() {
return x;
}
public float getY() {
return y;
}
public void setX(float x) {
this.x = x;
}
public void setY(float y) {
this.y = y;
}
public float getvelX() {
return velX;
}
public float getvelY() {
return velY;
}
public void setvelX(float velX) {
this.velX = velX;
}
public void setvelY(float velY) {
this.velY = velY;
}
public boolean isFalling() {
return falling;
}
public void setFalling(boolean falling) {
this.falling = falling;
}
public boolean isJumping() {
return jumping;
}
public void setJumping(boolean jumping) {
this.jumping = jumping;
}
public ObjectId getId() {
return id;
}
}
I added the getters and setters to generate the return value for the jumping and falling boolean values.

Java - The left-hand side of an assignment must be a variable

I'm trying to make a small program that locates different cities as my first Java project.
I want to access the variables of my class 'GPS' from the class 'City' but I keep getting this error: The left-hand side of an assignment must be a variable. Anyone can explain to me what am I am doing wrong here and how to avoid such mistake in the future?
public class Gps {
private int x;
private int y;
private int z;
public int getX() {
return this.x;
}
public int getY() {
return this.y;
}
public int getZ() {
return this.z;
}
}
(I want to leave the variables as private)
And this class 'Citiy' should have the coordinates:
class City {
Gps where;
Location(int x, int y, int z) {
where.getX() = x;
where.getY() = y; //The Error Here
where.getZ() = z;
}
}
The error speaks for itself: you cannot assign a value to something that is not a field or a variable. Getters are for getting values stored in the class. Java uses setters to deal with storing the values back:
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
Now you can set values by invoking the setter:
City(int x, int y, int z) {
where.setX(x);
...
}
However, this solution is not ideal, because it makes Gps mutable. You can keep it immutable by adding a constructor:
public Gps(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
Now City can set where in one shot:
City(int x, int y, int z) {
where = new Gps(x, y, z);
}
Don't set properties with getter. It should be done like that:
public class Gps {
private int x;
private int y;
private int z;
public int getX() {
return this.x;
}
public int getY() {
return this.y;
}
public int getZ() {
return this.z;
}
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}
public void setZ(int z) {
this.z = z;
}
}
class City {
Gps where;
City(int x, int y, int z) {
this.where = new Gps();
where.setX(x);
where.setY(y);
where.setZ(z);
}
}

Java how to implement and design an abstract class

I've run into a design problem in my java code. My application uses missiles, and there are different types of missiles that all work identical except they have 3 unique attributes. The constructor of a missile must know these attributes. I decided to make missile an abstract class, but I can't assign values to protected variables in a subclass outside of a method/constructor. Also I can't declare the variables in the constructor, because I must make the call to the super-constructor first thing.
How can I be smart about this problem?
public abstract class Missile {
private int x, y;
private Image image;
boolean visible;
private final int BOARD_WIDTH = 390;
protected final int MISSILE_SPEED;
protected final int MISSILE_HEIGHT;
protected String file;
public Missile(int x, int y) {
ImageIcon ii =
new ImageIcon(this.getClass().getResource(file));
image = ii.getImage();
visible = true;
this.x = x;
this.y = y - Math.floor(MISSILE_HEIGHT/2);
}
public Image getImage() {
return image;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public boolean isVisible() {
return visible;
}
public void move() {
x += MISSILE_SPEED;
if (x > BOARD_WIDTH)
visible = false;
}
}
And there is an ideal implementation of a subclass, except it doesn't work. (it can't recognize the protected variables). What do I do?
public class Laser extends Missile {
MISSILE_SPEED = 2;
MISSILE_HEIGHT = 5;
file = "laser.jpg";
public Laser(int x, int y) {
super(x, y);
}
}
I think the best way to do what you want it to do is make abstract methods in Missile that the subclasses have to implement. For example, add these to Missile:
public abstract int getMissileSpeed();
public abstract int getMissileHeight();
public abstract int getFileName();
Then your subclass has to implement it, and you can make it constant like so:
public class Laser extends Missile {
public Laser(int x, int y) {
super(x, y);
}
public int getMissileSpeed() {
return 2;
}
public int getMissileHeight() {
return 5;
}
public String getFileName() {
return "laser.jpg";
}
}
edit: And then of course anywhere that you want to retrieve the constant value you just call those methods.
Change the base class fields and constructors to
protected final int speed;
protected final int height;
public Missile(int x, int y, int speed, int height, String file) {
ImageIcon ii =
new ImageIcon(this.getClass().getResource(file));
image = ii.getImage();
visible = true;
this.speed = speed;
this.height = height;
this.x = x;
this.y = y - Math.floor(height/2);
}
And the subclass to:
public class Laser extends Missile {
public Laser(int x, int y) {
super(x, y, 2, 5, "laser.jpg");
}
...
}
The attributes are already in the base class, so they must not be redefined in the subclass. All-uppercase naming is reserved to constants in Java.
I'm not sure if missile needs to be an abstract class, but I think something like this might be what you're going for:
public abstract class Missile {
private int x, y;
private Image image;
boolean visible;
private final int BOARD_WIDTH = 390;
protected final int MISSILE_SPEED;
protected final int MISSILE_HEIGHT;
public Missile(int x, int y, int speed, int height, String file) {
MISSILE_SPEED = speed;
MISSILE_HEIGHT = height;
ImageIcon ii = new ImageIcon(this.getClass().getResource(file));
image = ii.getImage();
visible = true;
this.x = x;
this.y = y - Math.floor(MISSILE_HEIGHT/2);
}
}
public class Laser extends Missile {
public Laser(int x, int y) {
super(x, y, 2, 5, "laser.jpg");
}
}
Create an interface and put all your final fields in it.
Now implement this interface within Missile and Laser both. At least that would solve the issue of access.

mass change values of arraylist

I have array list of circles, whitch are drawing by canvas. And everything is OK. But I need change all X,Y coordinates of circles, by during the program.
static ArrayList<Circle> mCircles;
private static void createCircles() {
if (mCircles == null) {
mCircles = new ArrayList<Circle>();
}
int rana = 66/(koeficient);
mCircles.add(new Circle(80, 200, rana));
}
public static void AddCircle() {
int rana = 66/(koeficient);
mCircles.add(new Circle(80, 200, rana));
}
private void Drawing(Canvas canvas) {
for (Circle c : mCircles) {
canvas.drawCircle(c.getCurrentX(), c.getCurrentY(), c.getRadius(),
mMalovani);
}
}
public static Circle findCircleClosestToTouchEvent(float x, float y) {
Circle c = mCircles.get(mCircles.size() - 1);
return c;
}
public class Circle extends Shape {
final float mRadius;
public Circle(float x, float y, float r) {
super(x, y);
mRadius = r;
}
final float getRadius() {
return mRadius;
}
}
public class Shape extends Activity {
protected float mStartX = 0f;
protected float mStartY = 0f;
public float mCurrentX = 30f;
public float mCurrentY = 30f;
protected float mActionDownX;
protected float mActionDownY;
protected float mActionMoveOffsetX;
protected float mActionMoveOffsetY;
// x y coordinate of a move action
public Shape (float x, float y) {
mStartX = x;
mStartY = y;
mCurrentX = x;
mCurrentY = y;
}
public void setStartX(float x) { mStartX = x; }
public void setStartY(float y) { mStartY = y; }
public float getCurrentX() { return mCurrentX; }
public float getCurrentY() { return mCurrentY; }
public void setCurrentX(float x) { mCurrentX = x;
}
public void setCurrentY(float y) { mCurrentY = y; }
public void setActionMoveOffsetX(float x) { mActionMoveOffsetX = x; }
public void setActionMoveOffsetY(float y) { mActionMoveOffsetY = y; }
public float getActionMoveOffsetX() { return mActionMoveOffsetX; }
public float getActionMoveOffsetY() { return mActionMoveOffsetY; }
public void setActionDownX(float x) { mActionDownX = x; }
public void setActionDownY(float y) { mActionDownY = y; }
public float getActionDownX() { return mActionDownX; }
public float getActionDownY() { return mActionDownY; }
public void restoreStartPosition() {
mCurrentX = mStartX;
mCurrentY = mStartY;
}
}
Assuming you have setCurrentX and setCurrentY methods opposite the getter methods, just loop through the list of circles.
private void changeCoordinates(List<Circle> circles, int x, int y){
for(Circle c:circles){
c.setCurrentX(x);
c.setCurrentY(y);
}
}

Categories

Resources