Class Outer
{
...
private class Node
{
private T data;
...
private T getData()
{
return data;
}
}
}
What's the purpose of using set and get methods if the outer class can access inner class private members? What's the purpose of making inner classes private? Package access?
Java inner class is defined inside the body of another class. Java inner class can be declared private, public, protected, or with default access whereas an outer class can have only public or default access.
Accessing the Private Members Write an inner class in it, return the private members from a method within the inner class, say, getValue(), and finally from another class (from which you want to access the private members) call the getValue() method of the inner class.
It can access any private instance variable of the outer class. Like any other instance variable, we can have access modifier private, protected, public, and default modifier. Like class, an interface can also be nested and can have access specifiers.
Given these requirements, inner classes have full access to their outer class. Since they're basically a member of the outer class, it makes sense that they have access to methods and attributes of the outer class -- including privates.
Private Inner classes are written when you do not want the class to be exposed to external classes within or outside the package. They are used only inside the outer level class.
The getters and setters generally do not make sense inside a private classes because you can access the instance variables anyways.
You could skip trivial getters and setters, but often those methods are non-trivial (a common case is the 'lazy load' pattern).
Edited to add: Lazy load is when you only instantiate a member when the data is requested. It's used when getting the data is not always needed and is expensive to get.
class a
{
private:
int m_aNumber;
bigDeal *m_pBig;
public:
a() { m_aNumber = 0; m_pBig = NULL; }
~a() { if (m_pBig) delete m_pBig; }
// trivial
int get_aNumber() { return m_aNumber;}
void set_aNumber(int val) { m_aNumber = val; }
// lazy load
bigDeal *get_Big()
{
if (m_pBig == NULL)
{
// bigDeal::bigDeal() downloads data from Mars Rover
// takes 20 minutes, costs $1.2 million dollars to run
m_pBig = new(bigDeal);
}
return m_pBig;
}
void set_Big(bigDeal *val)
{
m_pBig = val;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With