I am new to java and object-oriented programming in general and got stumbled with a problem I could not find an answer to:
when typing:
Base someDerive = new Derived(2.2);
java basically creates an object which is actually of type Base
I wrote Derived instead of Base (for class type) and than everything worked as expected - but than again - I assumed That if type Base points to Derived than it should work as derived.
enough talking - time for some code:
public class test{
public static void main(String args[])
{
Base someDerive = new Derived(2.2);
System.out.println(someDerive);
System.out.println(someDerive.baseField);
System.out.println(someDerive.baseString);
System.out.println(someDerive.derivedDouble);
}}
class Base{
int baseField;
String baseString;
Base(int field, String str) {
baseField = field;
baseString = str;
}
}
class Derived extends Base{
double derivedDouble;
Derived(double someDouble) {
super(10, "some_string");
derivedDouble = someDouble;
}
}
I was expecting printout such as: "10" "some_string" "2.2"
instead I got a compilation error:
Test.java:8: error: cannot find symbol System.out.println(someDerive.derivedDouble); ^ symbol: variable derivedDouble location: variable someDerive of type Base 1 error