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

i'd think that you'd be better off relaying your initial values through the super class's constructor that way you'll get cleaner code, there's a possibly of inconsistency with option 2. i.e. you can then write code in your super classes to generally handle and properly initialize the instance variables while in the case of option 2, you'll have arbitrary constructors performing arbitrary initialization procedures

Similar Messages

  • Accessing a Sub class variable in a Super Class

    Hi ,
    Is there any easiest way to access a Subclass Variable in a Super Class.
    Class Super1{
    Class sub extends Super1
    private String substring1;
    In my application the 'substring1' values is not null .But all fields in Super1 class are null .
    How can i access the value of the Subclass Variable in Super class .
    Thanks

    This would be a way to make the superclass dependent on subclass behavior. Of course this only makes sense if getSubString() is likely to have multiple different implementations in different subclasses.
    public abstract class Super {
      public String getString() {
       return "SuperString" + getSubString();
      protected abstract String getSubString();
    public class Sub extends Super {
      private String substring;
      protected String getSubString() {
       return substring;
    }Using this just to access a variable whose contents differ from subclass to subclass is overkill. If you want each subclass to provide a different substring, create a constructor with a substring parameter in the superclass instead:public class Super {
      private String substring;
      protected Super(String substring) {
       this.substring = substring;
      public String getString() {
       return "SuperString" + substring;
    public class Sub extends Super {
      public Sub() {
       super("substring");
    }

  • How to access the parent class variable or object in java

    Hi Gurus,
    I encounter an issue when try to refer to parent class variable or object instance in java.
    The issue is when the child class reside in different location from the parent class as shown below.
    - ClassA and ClassB are reside in xxx.oracle.apps.inv.mo.server;
    - Derived is reside in xxx.oracle.apps.inv.mo.server.test;
    Let say ClassA and ClassB are the base / seeded class and can not be modified. How can i refer to the variable or object instance of ClassA and ClassB inside Derived class.
    package xxx.oracle.apps.inv.mo.server;
    public class ClassA {
        public int i=10;
    package xxx.oracle.apps.inv.mo.server;
    public class ClassB extends ClassA{
        int i=20;   
    package xxx.oracle.apps.inv.mo.server.test;
    import xxx.oracle.apps.inv.mo.server.ClassA;
    import xxx.oracle.apps.inv.mo.server.ClassB;
    public class Derived extends ClassB {
        int i=30;
        public Derived() {
           System.out.println(this.i);                  // this will print 30
           System.out.println(((ClassB)this).i);  // error, but this will print 20 if Derived class located in the same location as ClassB
           System.out.println(((ClassA)this).i);  // error, but this will print 20 if Derived class located in the same location as ClassA
        public static void main(String[] args) { 
            Derived d = new Derived(); 
    Many thanks in advance,
    Fendy

    Hi ,
    You cannot  access the controller attribute instead create an instance of the controller class and access the attribute in the set method
    OR create a static method X in the controller class and store the value in that method. and you can access the attribute by 
    Call method class=>X
    OR if the attribute is static you can access by classname=>attribute.
    Regards,
    Gangadhar.S
    Edited by: gangadhar rao on Mar 10, 2011 6:56 AM

  • Generic Data Access For All Class

    Hello
    I am doing one experiment on Data Access. In traditional system We have to write each Insert, Update, Delete code in data access for each table.
    My City Table Class:
    public class TbCitiesModel
    string _result;
    int _cityID;
    int _countryID;
    string _name;
    int _sortOrder;
    bool _enable;
    DateTime _createDate;
    string _countryName;
    public string result
    get { return _result; }
    set { _result = value; }
    public int cityID
    get { return _cityID; }
    set { _cityID = value; }
    public int countryID
    get { return _countryID; }
    set { _countryID = value; }
    public string name
    get { return _name; }
    set { _name = value; }
    public int sortOrder
    get { return _sortOrder; }
    set { _sortOrder = value; }
    public bool enable
    get { return _enable; }
    set { _enable = value; }
    public DateTime createDate
    get { return _createDate; }
    set { _createDate = value; }
    public string countryName
    get { return _countryName; }
    set { _countryName = value; }
    Traditional Code:
    public List<TbCitiesModel> DisplayCities()
    List<TbCitiesModel> lstCities = new List<TbCitiesModel>();
    using (SqlConnection connection = GetDatabaseConnection())
    using (SqlCommand command = new SqlCommand("STCitiesAll", connection))
    command.CommandType = CommandType.StoredProcedure;
    SqlDataReader reader = command.ExecuteReader();
    while (reader.Read())
    lstCities.Add(new TbCitiesModel());
    lstCities[lstCities.Count - 1].cityID = Convert.ToInt32(reader["cityID"]);
    lstCities[lstCities.Count - 1].countryID = Convert.ToInt32(reader["countryID"]);
    lstCities[lstCities.Count - 1].name = Convert.ToString(reader["name"]);
    lstCities[lstCities.Count - 1].sortOrder = Convert.ToInt32(reader["sortOrder"]);
    lstCities[lstCities.Count - 1].enable = Convert.ToBoolean(reader["enable"]);
    lstCities[lstCities.Count - 1].createDate = Convert.ToDateTime(reader["createDate"]);
    return lstCities;
    The above code is used to fetch all Cities in the table. But when There is another table e.g  "TBCountries" I have to write another method to get all countries. So each time almost same code but just table and parameters are changing.
    So decided to work on only one global Method to fetch data from Database.
    Generic Code:
    public List<T> DisplayCitiesT<T>(T TB, string spName)
    var categoryList = new List<T>();
    using (SqlConnection connection = GetDatabaseConnection())
    using (SqlCommand command = new SqlCommand(spName, connection))
    command.CommandType = CommandType.StoredProcedure;
    foreach (var prop in TB.GetType().GetProperties())
    string Key = prop.Name;
    string Value = Convert.ToString(prop.GetValue(TB, null));
    if (!string.IsNullOrEmpty(Value) && Value.Contains(DateTime.MinValue.ToShortDateString()) != true)
    command.Parameters.AddWithValue("@" + Key, prop.GetValue(TB, null));
    SqlDataReader reader = command.ExecuteReader();
    while (reader.Read())
    int i = 0;
    TB = Activator.CreateInstance<T>();
    int colCount = reader.FieldCount;
    foreach (var prop in TB.GetType().GetProperties())
    if (prop.Name != "result" && i <= (colCount - 1))
    prop.SetValue(TB, reader[prop.Name], null);
    i++;
    categoryList.Add(TB);
    return categoryList.ToList();
    Calling method:
    TbCitiesModel c = new TbCitiesModel();
    Program p = new Program();
    List<TbCitiesModel> lstCities = p.DisplayCitiesT<TbCitiesModel>(c,"STCitiesAll");
    foreach (TbCitiesModel item in lstCities)
    Console.WriteLine("ID: {0}, Name: {1}", item.cityID, item.name);
    Now Its working fine but I have tested with 10,00,000 Records in TBCities Table following are the result.
    1. The Traditional method took almost 58 - 59 -  58 - 59 - 59 seconds for 5 time
    2. The Generic Method is took 1.4 - 1.3 - 1.5 - 1.4 - 1.4  [minute.seconds]
    So by the results of test is generic method is probably slower in performance [because its have 3 foreach loops] but the data is very big almost 10,00,000 lakes records. So it might work good in lower records.
    1. So My question is can I used this method for real world applications ?? Or is there any performance optimization for this method?
    2. Also we can use this for the ASP.NET C# projects??
    Owner | Software Developer at NULLPLEX SOFTWARE SOLUTIONS http://nullplex.com

    Hi
    Mayur Lohite,
    Q1:It is not reasonable compared Generic Code with Traditional Code. The main issue not Generic.
    After take a look at your Generic Code.  Reflection code get slower in performance.
    TB = Activator.CreateInstance<T>();
    As Reflection is truly late bound approach to work with your types, the more Types you have for your single assembly the more slow you go on. Basically few people try to work everything based on Reflection. Using reflection unnecessarily will make your application
    very costly.
    Here is a good article about this issue, please take a look.
    Reflection is Slow or Fast? A Practical Demo
    Q2:Or is there any performance optimization for this method?
    The article presents some .NET techniques for using Reflection optimally and efficiently.
    optimizing object creation with reflection
    Note optimize
    reflection with Emit
    method.
    Best regards,
    Kristin
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.
    Hello Kristin
    Please can you tell how I optimize reflection in my code.
    public List<T> DisplayCitiesT<T>(T TB, string spName)
    var categoryList = new List<T>();
    using (SqlConnection connection = GetDatabaseConnection())
    using (SqlCommand command = new SqlCommand(spName, connection))
    command.CommandType = CommandType.StoredProcedure;
    foreach (var prop in TB.GetType().GetProperties())
    string Key = prop.Name;
    string Value = Convert.ToString(prop.GetValue(TB, null));
    if (!string.IsNullOrEmpty(Value) && Value.Contains(DateTime.MinValue.ToShortDateString()) != true)
    command.Parameters.AddWithValue("@" + Key, prop.GetValue(TB, null));
    SqlDataReader reader = command.ExecuteReader();
    while (reader.Read())
    int i = 0;
    TB = Activator.CreateInstance<T>();
    int colCount = reader.FieldCount;
    foreach (var prop in TB.GetType().GetProperties())
    if (prop.Name != "result" && i <= (colCount - 1))
    prop.SetValue(TB, reader[prop.Name], null);
    i++;
    categoryList.Add(TB);
    return categoryList.ToList();
    Thank you.
    Owner | Software Developer at NULLPLEX SOFTWARE SOLUTIONS http://nullplex.com

  • Accessing thirdy party class variable...

    I am pretty new to JAVA, and I was wondering if the following is doable.
    I have a class A and when it runs it invokes two different classes B and C. Is there anyway I can access a variable in B from C or vice versa? Any help would be greatly appreciated. Thanks!
    sincerely,
    Yosep

    accessing a 3rd party class variable?
    C.someClassVariableOr do you mean a instance variable.
    Depends on the scoping too by the way.
    Anyway way, if you want to access an instance variable, you'll have to have a reference to the object instance it's from.

  • Sub class will allocate seperate memory for super class  instance variable?

    class A
    int i, j;
    void showij()
    System.out.println("i and j: " + i + " " + j);
    class B extends A
    int k;
    void showij()
    System.out.println("i and j: " + i + " " + j);
    what is size of class B will it be just 4 byte for k or 12 bytes for i, j and k ?
    will be a seperate copy of i and j in B or address is same ?
    thank u

    amit.khosla wrote:
    just to add on...if you create seprate objects of A and B, so the addresses will be different. We cant inherit objects, we inherit classes. It means if you have an object of A and another object of B, they are totally different objects in terms of state they are into. They can share same value, but its not compulsary that they will share same values of i &j.
    Extending A means to making a new class which already have properties & behaviour of A.
    Hope this help.That is very unclear.
    If you create two objects, there will be two "addresses", and two sets of member variables.
    If you create one object, there will be one "address", and one complete set of non-static member variables that is the union of all non-static member variables declared in the class and all its ancestor classes.

  • Best Practice for  initialising class variables, should they be null?

    class Person
    private String name, address;
    public String getName()
    return name
    public void main()
    Person me = new Chris()
    ..........loads of code........
    if(me.getName==null)
    do something
    else
    do something else
    So my question is : whats the best behaviour when declaring variables? In this case should I have initialized the Strings to the empty string?
    I think i need to make a decision because I'm constantly unsure if the method should return null or empty string. So i find myself doing this occasionally :
    if(person.getName()==null || person.getName().equalIgnoreCase(""))
    Thanks
    Chris

    I believe that when you create an object it should be 100% ready for use. That means all private member variables set to a non-null, sensible value.
    You shouldn't force clients to know what's safe and what's not:
    public class Person
        private String name;
        private Date birthDate;
        public static void main(String [] args)
            Person p = new Person();
            System.out.println("age: " + p.getAge());
        public Person() { // do nothing; name is null }
        public String getName() { return name; }
        public void setName(String newName) { name = newName; }
        public Date getBirthDate() { return birthDate; }
        public void setBirthDate(Date newBirthDate) { birthDate = new Date(newBirthDate.getTime()); }
        public int getAge()
            int age = 0;
            // calculating age with a null birth date will be a problem.
            return age;
    }You might argue that it's perfectly reasonable to expect a user to call setters to initialize an object after it's created, but I don't like that idiom. There's no guarantee that it'll be done properly.
    %

  • Super class variables

    This is the situation:
    abstract Class NiftySuperClass
        int anInteger;
        NiftySuperClass(int someArgument)
            // do something with someArgument. Not important.
    public class SubClass extends NiftySuperClass
        SubClass(int someArgument)
            super(someArgument);
            anInteger = 100; //This is the important thing
        public int getAnInteger()
            return anInteger;
    }Now, let's say that I create an instance of the SubClass and assign the result of getAnInteger() to a variable...
    SubClass sc = new SubClass(15);
    int anotherInteger = sc.getAnInteger();For some reason, it seems as if anotherInteger is assigned the value zero (0). Which would make perfect sense to me, of course, had I not initialized the variable in the constructor of the subclass. As it is written, though, I really would expect getAnInteger() to return 100. Please explain, if possible, why I should not expect it to do so.
    And yes, I would expect a zero result if I had an integer variable called anInteger in the SubClass, and did something like this (since the variable would be determined by the kind of reference, sorta):
    NiftySuperClass sc = new SubClass(15);
    int anotherInteger = sc.getAnInteger();However, the variable in question comes from the SuperClass, and that (according to my own logic, at least) is assigned the value 100 in the constructor in the subclass. Hmm. Hope you follow me.
    Thanks in advance,
    smorgasbord

    Either you are doing something you haven't told us, or you have a bug in your compiler or JVM. Could you post a small but complete, compilable and executable example?
    The code you have posted is clearly not the code you are executing (as it wouldn't compile). When posting code to the forums, please create and test a complete example and then cut and paste the code (and preview it before posting).

  • Accessing SPML Object class variable on SUN IDM Form or workflow

    Hi All,
    Can anyone suggest me how we can access the SPML variable on SUN IDM Form and workflow?
    e.g
    I have object class deffination in SPML configuration with schema deffination as below
    <Configuration name='SPML'>
    <Extension>
    <Object> <Attribute name='classes'>
    <List>
    <Object name='person'>
    <Attribute name='type' value='User'/>
    <Attribute name='form' value='SPMLPerson'/>
    <Attribute name='default' value='true'/>
    <Attribute name='identifier' value='uid'/>
    </Object>
    </List>
    </Attribute>
    <Attribute name='schemas'>
    <List>
    <String>
    <![CDATA[
                       <schema xmlns="urn:oasis:names:tc:SPML:1:0"
                      ...SPML standard schema...
                      </schema>
                       ]]>
    </String>
    <String>
    <![CDATA[
                       <schema xmlns="urn:oasis:names:tc:SPML:1:0"
                       ...Waveset custom schema...
                       </schema>
                       ]]>
    </String>
    </List>
    </Attribute>
    </Object>
    </Extension>
    </Configuration>
    Where I deffine my custom schema with all attributes that I want to view on SUN IDM custom form.
    I am able to set value from ModifyRequest for the variable but not able to get it on the Form or workflow.
    I did try with below expression to get the variable but no luck.
    <ref>attribute_name</ref>
    <ref>SPML.attribute_name</ref>
    <ref>SPML.Object_name.attribute_name</ref>
    Please suggest how we can access the variable?
    Any information will be appricated.
    Regards,
    vinash

    Hi All,
    Can anyone suggest me how we can access the SPML variable on SUN IDM Form and workflow?
    e.g
    I have object class deffination in SPML configuration with schema deffination as below
    <Configuration name='SPML'>
    <Extension>
    <Object> <Attribute name='classes'>
    <List>
    <Object name='person'>
    <Attribute name='type' value='User'/>
    <Attribute name='form' value='SPMLPerson'/>
    <Attribute name='default' value='true'/>
    <Attribute name='identifier' value='uid'/>
    </Object>
    </List>
    </Attribute>
    <Attribute name='schemas'>
    <List>
    <String>
    <![CDATA[
                       <schema xmlns="urn:oasis:names:tc:SPML:1:0"
                      ...SPML standard schema...
                      </schema>
                       ]]>
    </String>
    <String>
    <![CDATA[
                       <schema xmlns="urn:oasis:names:tc:SPML:1:0"
                       ...Waveset custom schema...
                       </schema>
                       ]]>
    </String>
    </List>
    </Attribute>
    </Object>
    </Extension>
    </Configuration>
    Where I deffine my custom schema with all attributes that I want to view on SUN IDM custom form.
    I am able to set value from ModifyRequest for the variable but not able to get it on the Form or workflow.
    I did try with below expression to get the variable but no luck.
    <ref>attribute_name</ref>
    <ref>SPML.attribute_name</ref>
    <ref>SPML.Object_name.attribute_name</ref>
    Please suggest how we can access the variable?
    Any information will be appricated.
    Regards,
    vinash

  • Inner class access to outer class variables

    class X extends JTextField {
    int variable_a;
    public X() {
    setDocument(
    new PlainDocument() {
    //here i need access to variable_a
    i don't want to make variable_a a static member though, so does anyone know how to do it?

    Generally, you can reference your variable_a just as you would any other variable except if your inner class also defines a variable_a. However, to produce a reference to the enclosing outer class object you write "OuterClassName.this". So, to get to your variable I think you would write "X.this.variable_a". I hope this helps.

  • Need a simple network accessibility for RMI class files.

    I am trying to get an RMI server working and need a way to make the class files network accessible. The link: http://java.sun.com/javase/technologies/core/basic/rmi/class-server.zip does seem to have the server anymore. Anyone know where to get a copy of it?
    Is there a way to do this with Jini?
    Can oc4j be used?

    I am trying to get an RMI server working and need a way to make the class files network accessible. The link: http://java.sun.com/javase/technologies/core/basic/rmi/class-server.zip does seem to have the server anymore. Anyone know where to get a copy of it?
    Not much point really. That class file server only served .class files, not even JARs.
    Is there a way to do this with Jini?No.
    Can oc4j be used?Not by itself.
    Anything that will serve HTTP requests will do. Such as an HTTP server. Such as the one built into the JDK for example.

  • Private, protected Access Modifiers with a class

    Why cant we use private and protected access modifiers with a class?
    Thanks.

    Matiz wrote:
    >
    Public access allows you to extend a parent class in some other package. If you only want users to extend your class rather than instantiate it directly, make the class abstract and design for extension.Agreed. However, would the same argument be not true for the default access at the class level? No. Default access would only allow you to extend a parent class in the same package (as opposed to some other package).
    Now my confusion is why is a class allowed default access at the top level and not protected?Because protected for a top-level class makes no sense. The protected keyword provides member access to any other class in the same package and extending classes outside the package. A top-level class isn't a member of a class, by definition, so there's nothing that protected would do provide differently than public.
    So, the two access modifiers for a top-level class are public and default. Public allows access to the class outside the package, whereas default restricts access to the class within the package.
    ~

  • Inherit protected attribute from a Super class

    Hi All,
    I am inheriting a standard class which has many instance protected attributes. how do i access the super classes protected attributes from the sub class.  i.e i need the value present in the super class attribute to be used in a sub class method.
    will i be able to get the value of an instance attribute??
    Thanks in advance,
    Arun.

    Hi marc,
    I was also wondering as to how we can make use of the public attributes in the sub classes.as in, what the syntax we need to follow.
    It'd be great if you could give a simple example with one protecetd attribute accessed in the subclass.
    I've written a sample prog.
    REPORT  YA_TEST_OO.
          CLASS s_abc DEFINITION
    CLASS s_abc DEFINITION.
      PRIVATE SECTION.
        DATA: d_abc TYPE i.
    ENDCLASS.                    "s_abc DEFINITION
          CLASS sb_abc DEFINITION
    CLASS sb_abc DEFINITION INHERITING FROM s_abc.
      public SECTION.
    DATA: sb_d_abc TYPE c." VALUE d_abc.
        METHODS: m_abc.
    ENDCLASS.                    "sb_abc DEFINITION
          CLASS sb_abc IMPLEMENTATION
    CLASS sb_abc IMPLEMENTATION.
      METHOD m_abc.
       sb_d_abc = d_abc + 1.
      ENDMETHOD.                    "m_abc
    ENDCLASS.                    "sb_abc IMPLEMENTATION
    It doesn't work though.
    Thanx,
    Zid.

  • Airport Extreme & Remote Access for database application

    Hi There,
    I have spent an entire week of my time between apple, apple consultants and networking experts trying to get a access remotely to a simple database program inside an wireless network. I have read the discussions on remote access thru the AEBS and port mapping.
    I'm hoping an user here can help me with a foolproof solution that the 'apple experts' can seem to design?
    All that is required to get this program up and running remotely is the ip address of my computer inside my wireless network. I have set that this computer to a static address but since my dsl provider uses dynamic IP's this doesn't seem to work (or it does for about 12 hours until the IP address of my AEBS is changed). Will port mapping work for me or is my only solution an up-charged static IP?
    Thanks in advance for any suggestions......the thought of spending another week on this is frightening!

    If your ISP is refreshing the dynamic host configuration of the public ip address assigned to the ISP provided router you will need to request a static ip address from your service provider.
    The addresses that are used "inside of your network" are private ip addresses. If you are using the (1) public address for your router (APE)(Apple airport extreme) from the ISP what you are trying to do will not work very well since your router (APE) will use the Public IP address to provide access to the public internet for your private network using the private ip addresses you have used to create your subnet and told your router (APE) about. Three private IP address schemes can be used for a private internet. One for each class. Class A 10.x.x.x/8, Class B 172.16.0.0/12 and Class C 192.168.0.0/24. Translated using dynamic NAT (network address translation with overload) making your LAN hosts using private IP addresses to seem as if they are using a public ip address allowing access to the public internet where only public ip addresses can be used.
    PAT (port address translation) is what you are trying to accomplish. For PAT you must have a valid public ip address from your ISP and a private address from your network assigned to interesting host. Use the private ip assigned to the interesting host in the port mapping panel of airport admin that you wish to allow access to via the global internet as well as the tcp or udp port number for the traffic to be directed. For example port 5003 for FileMakerPro or port 20 and 21 for ftp. You should also implement security policies to protect your network and hosts.
    Since you said that it works for 12 hours you must have the basics set up correctly. All you need now is to get a static ip address assigned to you from your ISP or use a service such as http://www.dyndns.com/
    Hope I didn't ramble on too much

  • How to inherit super class constructor in the sub class

    I have a class A and class B
    Class B extends Class A {
    // if i use super i can access the super classs variables and methods
    // But how to inherit super class constructor
    }

    You cannot inherit constructors. You need to define all the ones you need in the subclass. You can then call the corresponding superclass constructor. e.g
    public B() {
        super();
    public B(String name) {
        super(name);
    }

Maybe you are looking for