Importing a class in Java? - java

In order to make this program run, I have to import the "derp" method out of the Shape class and into the rectangle class. But no matter what myself or the tutors try, we cannot make it work. What I actually need to accomplish is that the "derp" method from Shape needs to be able to work in Rectangle. However, the task of importing the method has us stumped.
public abstract class shape{
shape(){
}
shape(int length, int width, int thing ){
length = 0;
width = 0;
}
public int derp(int thing, int length) {
thing = (int) Math.random() * 9 ;
length = thing;
return length;
}
}
public class Rectangle extends shape {
public static void main(String args[])
{
shape.getLength(Length, Width);
//r1 will take all default value
Rectangle r1 = Rectangle();
//r2 will take all supplied value
Rectangle r2 = Rectangle(4, 5);
//r3 will take supplied length. width will take default value
Rectangle r3 = Rectangle(10);
//r4 will take the same value of r2
Rectangle r4= r2;
//the rest of the code
}
private static void Rectangle(int width2, int length2) {
// TODO Auto-generated method stub
}
}

It seems to me like you should reverse the inheritance. It should be Rectangle extending shape, since a rectangle is a shape
EDIT 1
When you reverse the inheritance you should be able to call the derp method on Rectangle.
RectAngle r = new Rectangle();
r.derp(thing, length);
EDIT 2
You shouldn't really hardcode your variables into your Shape instance either. Thats not a really usefull way to do it. There is two ways you can do it. Either let The shape class have variables which is protected (means it will be be inherited). Then you shape class should look like:
public abstract class shape{
protected int length;
protected int width;
shape(){
}
shape(int length, int width){
this.lenght = length;
this.width = width;
}
public int derp() {
int thing = (int) Math.random() * 9 ;
length = thing;
return length;
}
}
Or if you dont wanna make this big change to your class you can just pass the parameters directly into the method like
r.derp(1, 100);
But I do agree with tieTYT that you should spend some time learning some more java syntax. Since this is a very wierd way of doing your calls :).

Rectangle should be extending Shape, not the other way around.
Also remove this line
Rectangle.derp(int thing, int length, int width);

You don't import methods out of classes into other classes. Logically you'd want Rectangle to extend shape (also should be Shape in accordance with naming conventions), but you're doing the other way around.
However there are many things that don't make sense in your code, so you might want to explain in clear English what you're trying to accomplish.

There is no way, this could work, since you are trying to access a Method of the child-class from the superclass. the superclass dont know its children. You either can use the Methods of the superclass from the subclass or place the method from the subclass into the superclass to use it there.

Rectangle.derp(int thing, int length, int width);
This is not a method declaration. This syntax is all wrong. Are you trying to declare derp as a method you can use, or are you trying to call derp? As a reader, that is unclear.
Logically, Rectangle should extend Shape, not the other way around.
This doesn't do anything:
shape(int length, int width, int thing ){
length = 0;
width = 0;
}
You're just assigning parameters to different values.
Take a break and spend some time learning the syntax of Java.

Ok..so your class Shape extends Rectangle...we will ignore that unusual logic.
Rectangle.derp(int thing, int length, int width);// wrong
First of all you cannot call method derp by declaring parameters inside call. You could have a call like this for example:
int thing = 1, length = 2, width = 3;
Rectangle.derp(thing, length, width);//with condition that derp method
//declaration to be public static
Rectangle r1 = Rectangle();//wrong
That is the class constructor. You declare it as public unless you want to make your class a Singleton ..but I doubt. An you instantiate it with the 'new' keyord like this:
Rectangle r1 = new Rectangle();
Same for the one with 1 and 2 parameters.
Complete code for the Rectangle class here:
public class Rectangle {
public Rectangle(int width2, int length2) {
// TODO: Process width and length here
}
public Rectangle() {
// TODO: process default values here
}
public Rectangle(int value) {
// TODO: Process value here
}
public static void derp(int thing, int length, int width) {
}
public static void main(String args[]) {
int thing = 1, length = 2, width = 3;
Rectangle.derp(thing, length, width);
// r1 will take all default value
Rectangle r1 = new Rectangle();
// r2 will take all supplied value
Rectangle r2 = new Rectangle(4, 5);
// r3 will take supplied length. width will take default value
Rectangle r3 = new Rectangle(10);
// r4 will take the same value of r2
Rectangle r4 = r2;
// the rest of the code
}
}

Related

How do I return the x position of an object of 2D shapes without using fixed numbers?

I have a 2D rocket, the rocket is a collection of 3 objects, a nose(triangle), body(square) and a jet(circle), all together they make the rocket.
I have to set the body(square) relative to the nose(triangle), so that they align with each other.
So far I have this;
public Rocket(Triangle t, Square s, Circle c) {
this.nose = t;
this.body = s;
this.jet = c;
this.nose.setXPos(50);//initial positions of the nose X
this.nose.setYPos(300);//initial positions of the nose Y
this.body.setXPos(getBodyXPos());//sets the body relative to the nose X
this.body.setYPos(getBodyYPos());//sets the body relative to the nose Y
I also have the methods;
private int getBodyXPos()
{
return this.xPos;
}
private int getBodyYPos()
{
return this.yPos;
}
private int getJetXPos()
{
return this.xPos;
}
private int getJetYPos()
{
return this.yPos;
}
I am not aloud to use fixed number, but need to use the helper method in some way to make the shapes appear in the correct place on the screen.
I have been stuck on this for a few days and would love some help. Many thanks in advance.
you simply set the position of the various parts relative to each other with the appropriate offset
int rocketx = 50;
int rockety = 300;
this.nose.setXPos(rocketx);
this.nose.setYPos(rockeyy);
this.body.setXPos(rocketx);
this.body.setYPos(rockety+this.nose.height());
this.jet.setXPos(rocketx);
this.jet.setYPos(rockety+this.nose.height()+this.body.height());
instead of fixed values for height, you might have a method on nose and body to find out their height, and use that instead. If your rocket is flying horizontal, then you will need to do the same for X and NOT for Y.

Creating and storing a varying number of shapes in an arraylist in javafx

I have been messing around with javafx for practice and ran across something I couldn't figure out. I want to put a varying number of rectangles into an arraylist. Right now, instead of that, I am storing each rectangle as an double array (double[]) of the various properties, then setting a base rectangle to those values and returning that.
public class example{
Rectangle myRectangle = new Rectangle(0,0,25,25);
ArrayList<double[]> rectangles = new ArrayList();
double[] tempArray = [0,0];
public void addRect (double x, double y){
this.tempArray[0] = x;
this.tempArray[1] = y;
this.rectangles.add(this.tempArray);
};
public Rectangle getRect (int id){
this.myRectangle.setX(this.rectangles.get(id)[0]);
this.myRectangle.setY(this.rectangles.get(id)[1]);
return(this.rectangle);
};
}
In this example, when I call getRect, it sets the x and y of the base rect, then returns that rect. This works, but I am wondering if there is a way to store multiple instances of Rectangle in the ArrayList. The main issue I saw doing this is the fact that you have to name the instance(in the example above, myRectangle). I imagine that if there is a way around this issue, it would be to name the instance based on a string, in other words:
Rectangle "myRectangle" = new Rectangle();
which is not possible, as far as I know.
I am fairly new to Javafx and Java in general so if there is anything else off with my code feel free to correct that. Thanks!
You just need to make an ArrayList<Rectangle> and add rectangles to it.
public class Example {
private List<Rectangle> rectangles = new ArrayList<>();
public void addRectangle(double x, double y, double width, double height) {
rectangles.add(new Rectangle(x, y, width, height));
}
public Rectangle getRectangle(int index) {
return rectangles.get(index);
}
}
You should note that your original code really doesn't work as expected at all. For example, try:
// please do NOT name classes with lower case...
example e = new example();
e.addRectangle(0, 0);
e.addRectangle(100, 100);
Rectangle rect1 = e.getRectangle(0);
System.out.println("Rectangle 1: ["+rect1.getX()+", "+rect1.getY()+"]");
Rectangle rect2 = e.getRectangle(1);
System.out.println("Rectangle 2: ["+rect2.getX()+", "+rect2.getY()+"]");
// but:
System.out.println("Rectangle 1: ["+rect1.getX()+", "+rect1.getY()+"]");
// oops.
System.out.println("Rectangle 1 and 2 are the same: " + (rect1==rect2) );

Syntax error, regarding to changing variables in an object from a class

class anyName
{
int Tcol = 0;
int fc = 0;
int x = 0;
float randx = (random(1, 1000));
float randy = (random (0, 600));
int Tsizes = 1;
{
if (fc >= x) { //Random Ellipse 3
stroke (Tcol);
fill (Tcol);
ellipse (randx, randy, Tsizes, Tsizes);
}
}
}
anyName ranx1 = new anyName();
ranx1.x = 100;
Hi, I am trying to add a class/object to my code and it is not working. This is the class I have so far, but when I instantiate one object from that class (ranx1), and then try change one of the variables inside it (x), it says there is a error. Is there anything I need to change? I would really appreciate any help.
Since I instantiated an object from that class, how would I change the variables for the new object? For example, if in the class x = 0, then I made a copy and this time I want x to = 100, but all the other variables such as Tcol and fc to stay the same. I know this is possible because my teacher taught it, but it is not working right now for me.
I am a really newby programmer, so I think this should be easy for someone to answer.
If you want the entire code, please put your email in the answer, so that I can email the entire thing to you.
ranx1.x = 100;
You need a setter in your anyName-class. And then you call the setter:
public void setX(int x) {
this.x = x;
}
and
ranx1.setX(100) for example.

Getting X & Y coordinates from graphics object

I have a problem. I'm creating this maze game using java for the very first time,
and I have lots and lots of graphics(g) drawings/objects drawn through their own class.
What I want to get is the X and Y coordinate out of one of them.
public static int seems too hard to use in this case, without created an equal number of integers as there are drawings.
So, I need something to use instead of getY():
public void keyPressed(KeyEvent e){
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT) {
for (int i=0; i<=42; i++) {
if(cx != rektangel[i].getY()) // I tried "getY()" with fail(kind of dumb since it's used for mouselistener?
cirkel[0].move(-10, 0);
this.cx += -10;
repaint();
}
}
Information you might need to know in this code:
rektangel(the name) = rectangle in english.
cirkel is one object/drawing ==> I simply used a static int cx & cy for this guy to see it's coordinates.
Where it says i<42; ==> shows that it's ALOT of drawn objects. (static int won't be optimal)
=============ANSWERED======ANSWERED=======ANSWERED=======ANSWERED==========
Sorry, but for some reason I can't comment your answers. The result is ridiculously laughable. I'm currently staying up late to finish my code for a homework I have. Thanks for your solution, and MadProgrammers comment. Here's my rectangle-class:
public class Rektangel {
private int width,height;
private int x,y; <---this row private
Color c;
public static int karta = 1;
public static int rx = 0;
public static int ry = 0;
}
The easiest thing in the world.. I had tried using rectangle[i].x in the previous code, but didn't work. Know why? Because I wrote private instead of public x & y. Sorry for the inconvenience and once again, Thanks!
You should maintain the position and size of each object within itself and provide a getX, getY and getWidth and getHeight method for each, this way, they become self managing, knowing where they are and how big they should be...

Does LSP also make sense for dynamic typed language like Ruby? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Consider the classic example in Java
// Violation of Likov's Substitution Principle
class Rectangle
{
protected int m_width;
protected int m_height;
public void setWidth(int width){
m_width = width;
}
public void setHeight(int height){
m_height = height;
}
public int getWidth(){
return m_width;
}
public int getHeight(){
return m_height;
}
public int getArea(){
return m_width * m_height;
}
}
class Square extends Rectangle
{
public void setWidth(int width){
m_width = width;
m_height = width;
}
public void setHeight(int height){
m_width = height;
m_height = height;
}
}
class LspTest
{
private static Rectangle getNewRectangle()
{
// it can be an object returned by some factory ...
return new Square();
}
public static void main (String args[])
{
Rectangle r = LspTest.getNewRectangle();
r.setWidth(5);
r.setHeight(10);
// user knows that r it's a rectangle.
// It assumes that he's able to set the
// width and height as for the base class
System.out.println(r.getArea());
// now he's surprised to see that the area is 100 instead of 50.
}
}
I think the whole point is that object of child class can be treated(type casting?) like parent class in static typed language like Java:
Rectange rectange = new Square();
but in Ruby I don't think that make any sense, same thing in Ruby:
class Rectangle
attr_accessor :width, :height
def getArea()
#width * #height
end
end
class Square < Rectangle
def width=(number)
super(number)
#height = number
end
def height=(number)
super(number)
#width = number
end
end
s = Square.new(100)
puts s.class
s.width = 50
puts s.height
become I can alway check the class of the object by using:
rectange.class
in this case, if the code in Ruby it will return Square
so I won't treat it like Rectange.
Could anyone explain me the point for applying LSP in dynamic typed language like Ruby?
Although I still don't know what problem it may cause to let Square be a child of Rectangle. but now I learn to tell whether it violet the LSP or not by using the way:
for square object is an instance of Square Class, rectangle object is an instance of Rectangle class
the width= is a method in both of them
width= in square can not be replaced by width= in rectangle
because it won't set the height as the one defined in 'square' does.
Am I wrong with this way of thinking?
And Also I learned to use the violet the contact of 'width=' method in the Rectangle Class to analysis this problem:
for width= in 'Rectangle' class
precondition: #width and #height has some value.
postconditon: #width change to the new value, #height remain the untouched.
for 'width=' in Square class
precondition: same as above
postconditon: '#width' change to the the new value, #height change to the new value
according to the principle : require no more, promise no less
the #height is changed, so promise is not fulfilled, thus it can't be inheritance
Does anyone can give me some advice about my way of analysis this problem by using DBC?
LSP still applies, even in dynamically-typed languages like Ruby. Your reasoning:
I can alway check the class of the object by using:
rectange.class
in this case, if the code in Ruby it will return Square so I won't treat it like Rectangle.
Isn't specific to Ruby; you can, in fact, check the actual class of the variable in Java, too. Doing so doesn't provide a "solution" to this problem.
The key observation from this example is that, while a square is a rectangle in geometry, a Square isn't a Rectangle from an OOP standpoint—a Square's behavior is incompatible with that of a Rectangle.

Categories