Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing variable values in subclasses?

Tags:

java

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.

like image 558
milkmanjack Avatar asked Dec 17 '14 18:12

milkmanjack


1 Answers

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."

like image 139
Andy Thomas Avatar answered Sep 26 '22 22:09

Andy Thomas