Results 1 to 3 of 3
  1. #1
    lam5442 is offline Member
    Join Date
    Feb 2011
    Posts
    2
    Rep Power
    0

    Default Can you use the super keyword when variables in parent class are private?

    If I have this code:

    public class A
    {
    int k = 10;

    }

    public class B extends A
    {
    public void m()
    {
    System.out.println(super.k);
    }

    public static void main(String[] arguments)
    {
    B b = new B();
    b.m();
    }

    }

    I get 10.

    If I make k private, then I can't access k and can use a get method:



    public class B extends A
    {
    public void m()
    {
    System.out.println(getInt());
    }

    public static void main(String[] arguments)
    {
    B b = new B();
    b.m();
    }
    }

    public class A
    {
    private int k = 10;

    public int getInt()
    {
    return k;
    }

    }

    Is there a way to use the super keyword when variables are private? Also, when given a choice, which of these two methods is preferred?


  2. #2
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,336
    Blog Entries
    7
    Rep Power
    20

    Default

    If the variable in the super class is private you have to use a getter method; if there is no such method you're out of luck; it either was a bad design or that variable is none of your busyness.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  3. #3
    danieland is offline Member
    Join Date
    Jun 2011
    Location
    Romania, Cluj Napoca
    Posts
    2
    Rep Power
    0

    Default

    Hy, you can use with super only the public, and protected variables

Similar Threads

  1. Why make class variables private?
    By PrinceSendai in forum New To Java
    Replies: 3
    Last Post: 10-18-2010, 11:01 AM
  2. rule for using the super keyword
    By javastuden in forum New To Java
    Replies: 2
    Last Post: 10-01-2010, 09:02 AM
  3. Inheritance - accessing private variables
    By counterfox in forum New To Java
    Replies: 3
    Last Post: 04-26-2010, 01:21 AM
  4. Private constructor and super()
    By Basit56 in forum Advanced Java
    Replies: 9
    Last Post: 08-21-2009, 06:19 AM
  5. Replies: 3
    Last Post: 03-14-2009, 07:22 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
  •