0

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

guyr79
  • 169
  • 1
  • 11
  • Thanks for the extremely fast reply azurefrog. I thought that Base can point to Derived without changing its values. Isn't it the point when we extend classes? So that Base can reference to Derived while Derived keeps its features? – guyr79 Jul 11 '19 at 18:37

1 Answers1

2

when typing:

Base someDerive = new Derived(2.2);

java basically creates an object which is actually of type Base

You have that backwards. It creates an object whose type is Derived and assigns a reference to that object to a variable whose type is Base.

You're getting a compile error because the variable is of type Base, and there's no derivedDouble field in the Base class. Even though at runtime the object being referred to is a Derived, at compile time the compiler only knows what type the variable is.

If you want to access a field defined in Derived, you need to cast the variable to that type:

System.out.println(((Derived)someDerive).derivedDouble);
Community
  • 1
  • 1
azurefrog
  • 10,785
  • 7
  • 42
  • 56
  • Thanks azurefrog. it worked! It looks a bit ugly though. Is this the only way to make it work? I mean, when ever I want to use some feature that belongs exclusively to Derived, I need to downcast? Thanks in advance! – guyr79 Jul 11 '19 at 18:44
  • 1
    @guyr79 no, this isn't the only way: the best way would be to declare `Derived someDerive` in the first place. – Andy Turner Jul 11 '19 at 20:25