Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Alternative concept for late binding in Java

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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());
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading