This week's book giveaway is in the Cloud/Virtualizaton forum.
We're giving away four copies of Mesos in Action and have Roger Ignazio on-line!
See this thread for details.
Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Acess Modifiers

 
Prashanth Lingala
Ranch Hand
Posts: 66
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class A
{
static int i;
private int j;
}

class B extends A {
public static void main(String args[]) {

i = 10;
j = 11;// Error , I Understand this
}
}

What I do not Follow:

class Box {
private double height;

Box(double h) {
height = h;
}
}

class BoxWeight extends Box {
double weight;

BoxWeight(double h, double w) {
super(h);
weight = w;
}
}

height is declared private in Box, so how is it directly accessible using super.
The compiler doesn't give me an error.Why so???
Please Enlighten me folks...
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Welcome to JavaRanch!

First, I need to make sure you realize that the constructor parameter 'h' in BoxWeight and the member variable 'h' are completely unrelated.

So, anyway, "private" doesn't mean that the outside world can have no effect on a variable. It just means that no outside code can write

Box b = ...
b.h = 37;

No code not in the "Box" class can explicitly mention 'h'. But if Box provides a public method or constructor that itself changes or reads 'h', then any code outside of Box can call that method, and so indirectly access h. The idea is that because 'h'is private, Box has complete control over what happens to 'h'.
 
Prashanth Lingala
Ranch Hand
Posts: 66
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank You
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic