Using getter / setter other than open for binary compatibility?

I read "Practical API Design" and find the following paragraph:

"Another reason to prefer methods over fields can be found in the JVM specification. You are allowed to move a method from a class to one of its superclasses and maintain binary compatibility. Thus, the method is first introduced as Dimension javax. Swing.JComponent. GetPreferredSize (Dimension d) can delete in the new version and move to Dimension java.awt.Component.getPreferredSize (Dimension d), because JComponent is a subclass of Component. This change really happened in JDK 1.2, and this can only be done because the field was encapsulated using the method. Similar operation e is allowed to field. After the field is defined in the class, it has to stay there forever, to maintain binary compatibility, is another reason to keep private fields "

as I agree using getter / setter is better. But I don’t understand why moving an open field to a parent class violates binary compatibility? You should still have access to this field through the child class while it is publicly available in the parent.

+5
source share
2 answers

Once a field is defined in a class, it must remain there forever to maintain binary compatibility.

That would be very surprising:

The Java language specification, Java SE 7 Edition, defines the binary name of an expression for unqualified access to a field as follows:

, C, (Β§13.4.9) f, (, ) D, :

  • Primary.f, :
    • Primary (Β§4.9) V1 ... Vn, V1.
    • , Primary .

( Java 1.5 )

, , , , , , .

,

package p;

public class Super {

}

package p;

public class Sub extends Super {
    public String message;

    @Override
    public String toString() {
        return message;
    }
}

package p;

public class Super {
    public String message;
}

package p;

public class Sub extends Super {
    @Override
    public String toString() {
        return message;
    }
}

package p;

public class Main {
    public static void main(String[] args) {
        Sub sub = new Sub();
        sub.message = "hello";
        System.out.println(sub);
        System.out.println(sub.message);
    }
}

hello
hello

LinkageError.

, Java 7. , JDK 1.4 , 5 . , , / ?

+3

, , . , Java ( , Java).

. , .

0

All Articles