java - Superclass' fields: private+accessors vs protected -


snippet #1:

public abstract class superclass {     protected int i;    }  public class subclass extends superclass {     public void method() {         = doanythingwithi(i); // example     } } 

snippet #2:

public abstract class superclass {     private int i;         protected int geti() {         return i;     }         protected int seti(int i) {         this.i = i;     } }  public class subclass extends superclass {     public void method() {         seti(doanythingwithi(geti())); // example     } } 

any reason why using 1 snippet instead of other one? common way process?

one of more common uses of abstract class have abstract methods not implemented in abstract class, implemented in subclasses in java program. not use case. however, abstract class can used way of preventing instantiating class supposed extended first. assuming desire.

furthermore, assume trivial nature of example illustration. having 2 classes "manage" single primitive 'int' suspect otherwise!

given , 2 choices snippet #2 closer being correct. reason being desire of "type" encapsulate state, data, , behavior. snippet #1 violates , discouraged.

the method "doanythingwithi" begs discussion though. not declared in examples. if operates solely upon "i" , not subject alteration concrete class, belongs in abstract base class.

if can vary multiple implementations extend superclass, should defined abstract method in superclass , implemented sub-classes.


Comments

Popular posts from this blog

java - JavaFX 2 slider labelFormatter not being used -

Detect support for Shoutcast ICY MP3 without navigator.userAgent in Firefox? -

web - SVG not rendering properly in Firefox -