Reputation:
I have the below code.
public class Test {
public static void main(String args[])
{
int i = 0;
if(i==0){
Beer obj = new Beer();
}
else {
Rum obj = new Rum();
}
System.out.println(obj.brand); //doesn't work
} }
class Drink {
}
class Beer extends Drink{
public String brand = "BeerBrand"; }
class Rum extends Drink{
public String brand = "RumBrand"; }
Upvotes: 0
Views: 4861
Reputation: 272217
Drink
should be an abstract class and provide an abstract member getBrand()
or similar, overridden by Beer
and Rum
.
Then you'd do something like:
Drink d = null;
if (...) {
d = new Beer();
}
so you instantiate the reference appropriately. Because it's still of type Drink
you can reference the brand. The Drink reference will let you access anything drink-able, and the implementation provides the specifics. Note that Drink
is abstract, since you can't instantiate a Drink
- you have to be more specific.
To answer your further questions, you could provide a base method and do something like:
if (this instanceof Beer) {
...
}
to avoid overriding. But why would you ?
To answer your second question, classes are dynamically loaded by the JVM upon reference. You can watch that occur by setting the -verbose
flag on the JVM.
Upvotes: 3
Reputation: 533442
Is there an way to make the above work without using function overriding or dynamic class loading?
The only alternative is to use reflections, but fixing the design of the classes would be much simpler/better
All classes are dynamically loaded in JVM there is no static loading like in C. Is this correct?
Yes. They can be dynamically loaded more than once and even unloaded.
Using an object orientated approach would look like this.
public class Test {
public static void main(String... args) {
Drink drink;
if (args.length == 0) {
drink = new Beer();
} else {
drink = new Rum();
}
System.out.println(drink.getBrand());
}
}
interface Drink {
public String getBrand();
}
class Beer implements Drink {
@Override
public String getBrand() {
return "BeerBrand";
}
}
class Rum implements Drink {
@Override
public String getBrand() {
return "RumBrand";
}
}
Upvotes: 1
Reputation: 1095
This code won't work because scope of 'obj' is only within if-else block. You need to declare it above if-else block of type Drink.
Upvotes: 2