Results 1 to 4 of 4
- 03-14-2009, 03:48 AM #1
Member
- Join Date
- Oct 2008
- Posts
- 1
- Rep Power
- 0
Private or Protected access for super class variables
What is the best practice...
Assume there is a class hierachy like
Person (Super class) / StaffMember/ Professor (Sub class)
1) The best way is to keep all the instance variables of each and every class private and access the private variables of super classes through subclass constructors (calling "super()")
Ex:-
public class Person {
private String empNo;
public Person (String empNo) {
this.empNo = empNo;
}
}
public class Professor extends Person {
private String ........;
private int ...........;
public Professor (String pEmpNo) {
super(pEmpNo);
}
}
OR
2)Changing the access level of the super class variables into "protected" or "default" and access them directly within the sub classes...
Ex:-
public class Person {
protected String empNo;
public Person () {
}
}
public class Professor extends Person {
String ........;
int ...........;
public Professor (String empNo) {
this.empNo = empNo;
..............
..............
}
}
Thank you...
- 03-14-2009, 04:52 AM #2
Senior Member
- Join Date
- Dec 2008
- Location
- Hong Kong
- Posts
- 473
- Rep Power
- 5
i prefer to keep all the variable instances private and access the variables of super classes through protected method
- 03-14-2009, 07:03 AM #3
Moderator
- Join Date
- Feb 2009
- Location
- New Zealand
- Posts
- 4,537
- Rep Power
- 11
Also crossposted on Sun forums
- 03-14-2009, 07:22 AM #4
Senior Member
- Join Date
- Jan 2009
- Posts
- 671
- Rep Power
- 5
I'm not convinced there is a best practice. Default protections are what the Java designers had in mind as best practice, but this tends to lead to sloppy encapsulation, since default methods *and member variables* can be accessed by any class in the package. YUCK!
Protected doesn't help.
Private is too restrictive. Even subclasses are locked out.
IMHO, the default protection *should* shield methods and member variables from access by anything other than the class of interest or it's subclasses and inner classes. Other classes in the package should not have access. I code this way when I own the package, but mistakes can be made.
Similar Threads
-
How to access private data types from public classes?
By kevzspeare in forum New To JavaReplies: 3Last Post: 03-07-2009, 04:19 AM -
Ask for help on Java access to protected methods
By fangzhong in forum Advanced JavaReplies: 3Last Post: 02-17-2009, 01:50 PM -
Class Reflection: Finding super class names
By Java Tip in forum java.langReplies: 0Last Post: 04-23-2008, 08:12 PM -
Error: Cannot access protected member long getTimeInMillis() in class Calendar
By cachi in forum Advanced JavaReplies: 1Last Post: 08-07-2007, 07:53 AM -
help with protected method in vector class
By katie in forum Advanced JavaReplies: 1Last Post: 08-06-2007, 10:59 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks