Reputation: 31
I'm super new to Java and I'm trying to figure out how to dynamically establish whether or not to use a particular subclass.
Here is my broken code:
if(length == width){
Square myBox = new Square();
}else{
Rectangle myBox = new Rectangle();
}
What I'm trying to do is use the "Square" subclass when the length and width (entered by the user) are equal. I have no idea how to make it do what I'm wanting so I used "general coding logic" from my more extensive experience with PHP (obviously to no avail; my biggest hurtle in learning Java so far has been switching from PHP to Java in my head, haha)
So I'm wondering if there's a way to do this. If not then that's fine, I'll scrap it. I just thought I'd ask.
Upvotes: 1
Views: 920
Reputation: 288
A major difference between Java en PHP is early vs. late binding. In Java you must state the data type and may not alter that later on. The following would make sense:
Rectangle myBox;
if(length == width){
myBox = new Square();
}else{
myBox = new Rectangle()
}
This would compile OK if Square
is a subclass of Rectangle
:
class Square extends Rectangle{};
Upvotes: 0
Reputation: 6947
You can do this, if the classes involved share a common ancestor and that ancestor is good enough for your purposes. In that case, declare the variable as the common ancestor type, but assign it a new MoreSpecificType()
depending on the criteria needed.
What you need to do to make this work like you want is to move the variable declaration outside of the if
statement-blocks. The reason for this is that in Java, the variable goes out of scope when the block in which it is declared ends, so in your code you can only actually do anything with myBox
within the ...
parts of if() { ... } else { ... }
.
Upvotes: 0
Reputation: 8245
First, you are declaring these variables inside the branches of the if
statement - their scope is limited to these branches. So the variable myBox
will only be visible between those brackets. Which is probably not what you want.
Second, as was already pointed out by @Robby Cornelissen - if Square
is a subclass of Rectangle
, you'll want to use Rectangle
.
But, although in mathematics a Square is a special case of a Rectangle, this is a classic example of object-oriented logic being a little different. A Rectangle has one more property than a Square. A square has only the length of one side, a Rectangle has both width and height. So you'll want Rectangle
to be derived from Square
, even though that is a bit counter-intuitive.
Upvotes: 1
Reputation: 97140
I'm assuming that Square
is a subclass of Rectangle
. In that case:
Rectangle myBox;
if (length == width) {
myBox = new Square();
} else {
myBox = new Rectangle();
}
Upvotes: 5