Results 1 to 4 of 4
  1. #1
    counterfox is offline Member
    Join Date
    Mar 2009
    Posts
    45
    Rep Power
    0

    Default Inheritance - accessing private variables

    Hi, im really a beginner at java but just trying to understand some basic inheritance theory.

    I understand how to make a subclass and make a constructor in the subclass but what i'm confused with is accessing the superclass' private variables.

    For example say a subclass has a method which calculates its private variable with a private variable from its superclass. I'm pretty sure:

    (superclasses variable)*(subclass variable)

    will produce an error with how the superclass variable is private.

    I read that getter methods are used to access private variables values from a superclass. I'm just wondering in the subclass' method, how is this done to use these getter methods to get the value I(from superclass private variable) and make the calculation?

    Any explainations or examples are much appreciated. I've looked on the net for examples but there either not related to what i'm after or just way to in depth with information which isn't where my java knowledge is yet ^.^
    Last edited by counterfox; 04-20-2010 at 02:31 AM.

  2. #2
    iluxa is offline Senior Member
    Join Date
    Mar 2010
    Posts
    266
    Rep Power
    5

    Default

    Java Code:
    class SuperClass {
      private int x;
      protected int y;
    
      // getter
      public int getX () {
        return x;
      }
    }
    
    class SubClass extends SuperClass {
      private int z;
    
      public int calculateStuff () {
        return z * y * getX ();
      }
    }

  3. #3
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,224
    Rep Power
    20

    Default

    Even better, simply provide an accessor to the private variable, whether protected or public...and final in both cases. "final" because you will almost never want a subclass to be able to overwrite that logic.

    The general rule (and as with all general rules, there will be exceptions) is attributes should be inaccessible except via accessors.

  4. #4
    counterfox is offline Member
    Join Date
    Mar 2009
    Posts
    45
    Rep Power
    0

Similar Threads

  1. OOP Question re. private variables and extending classes
    By ImplicitCharm in forum New To Java
    Replies: 7
    Last Post: 07-28-2009, 04:46 PM
  2. accessing variables
    By emp in forum New To Java
    Replies: 3
    Last Post: 04-23-2009, 05:36 AM
  3. Replies: 3
    Last Post: 03-14-2009, 08:22 AM
  4. [SOLVED] Accessing private constructor
    By piyu.sha in forum New To Java
    Replies: 2
    Last Post: 10-06-2008, 06:45 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •