It's been quite awhile since I worked on anything in Java, and I really have very limited experience making anything with it at all, for the most part I write in higher level specified languages, scripting languages and the sort.
I assume I'm not understanding the concept behind assigning the default value of a class's members.
// parent
public class A {
protected int value = 0;
public void print() {
System.out.println(value);
}
}
// child class
public class B extends A {
int value = 1;
}
To keep it short, creating an instance of B and calling print() prints the original value of "value" set in A.
I assume rather than being some kind of general identifier for "a variable named 'value' owned by this object," the defined function on A has a completely different context for "value" than B does.
What other method is there to organize common variations of a certain class but creating a child of said class? Some kind of factory object? It doesn't seem to be interfaces are the answer because then I have to redefine every single facet of the class, so I've gained nothing in doing so.
Any help would be much appreciated, thanks.
Subclass fields do not override superclass fields.
You can set a default value through constructors, as illustrated below.
// parent
public class A {
private int value = 0;
public A( int initialValue ) {
value = initialValue;
}
public void print() {
System.out.println(value);
}
}
// child class
public class B extends A {
public B() {
super( 1 );
}
}
Also, in most cases, your life will be easier if you avoid protected fields.
Protected fields open your data to direct access and modification by other classes, some of which you may not control. The poor encapsulation can allow bugs and inhibit modification. As suggested in the Java tutorials on access control:
"Use the most restrictive access level that makes sense for a particular member. Use private unless you have a good reason not to."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With