I’m currently learning Java, coming from PHP.
Now I’m a bit lost because I’ve just noted that it seems like there is nothing like the concept of late binding I’m used to use from PHP.
Does this mean, I cannot provide methods in a base class, which every child class can use with its own member values?
I mean, there must be concept for it, since it’s hard to imagine, that you have to add such methods and functions to every single child class…
Let me give a concrete example, just in case it is not clear what I am wondering about.
How would I solve something like the following PHP structure in Java?
abstract class BaseClass {
protected String $value = 'Base';
public function getValue(): String {
return $this->value;
}
}
class ChildClass extends BaseClass {
protected String $value = 'Child';
}
$obj = new ChildClass();
print $obj->getValue(); // Shall print "Child"
Thank you very much for any hints/clarification.
>Solution :
If you put the initialization in the constructor, you can initialize a field to different values based on the class.
public abstract class Base {
String value;
public Base() {
value = "Base";
}
public String getValue() {
return value;
}
}
public class Child extends Base {
public Child () {
value = "Child";
}
public static void main(String[] argv) {
Base x = new Child();
System.out.println(x.getValue());
}
}