java - Best Practices for Class Design (subclass + overriding) -


I want to design square hierarchy. There is an abstract method in superclass, sub class has to override this method, but my problem is this: This method uses the data of the Super Class (instance variable).

I have prepared some style to solve this problem:

Style 1: Use personal example variable and create other instance variables in the sub class

  class SuperClass {Private T data; Public Super Class (T Data) {/ * ...} / Public Summary Void Zero doSomething (); } Class all class superclass {enhances personal tee data; // Use other variable folk subclass (t data) {super (data); This.data = data; } Public Zero doSomething () {// use 'data' int length = data.getLength (); // example ...}}   

Style 2: Use the protected example variable:

  Class SuperClass {Protected T information; Public Super Class (T Data) {/ * ...} / Public Summary Void Zero doSomething (); } Superclass expanded into class sub-class {public zero doSomething () {// 'data' use int length = data. GetLength (); // example ...}}   

Style 3: Use the private instance variable and protected method:

  Class SuperClass {Private T data; Public Super Class (T Data) {/ * ...} / Public Summary Void Zero doSomething (); Protected T getData () {Return data; }} Class sub-class enhances SuperClass {Public Zero doSomething () {// 'data' use int length = getData.getLength (); // for example ...}}   

Which of them is better? Or have more solutions to solve my problem better?

The third approach is generally preferred and if you select public sub -Designing for clasing, it is absolutely necessary. A superclass wants to maintain as much control as possible on its interior.

If, on the other hand, you are developing a closed hierarchy that is all in the same package, or in at least one project, you can expose the protected var as protected, If there can be any benefits.

Duplication of a personal version in subclass is a failure on all matters, although I can not think of any scenario where this would help anything.

Comments