can we make a method as private in encapsulation in java? - java

To achieve encapsulation we make members as private (variables) and use getter and setter methods for data hiding and that's how we achieve data hiding. So in the same way can we make a method as private and access it with getter or setter method ? (or is there any other way to do it)

In Java private methods are the methods having private access modifier and are restricted to be accessed in the defining class only and are not visible in their child class due to which are not eligible for an override. However, we can define a method with the same name in the child class and could access in the parent class.
I don't think there can be getters and setters method for the same reason.

Certainly you can define a method as private, so that it can only be called (essentially) from other methods in the same class. This is a pretty common practice. For example, I might provide a method getFoo(), where the actual value of foo is not not simply an instance variable, but something derived by calculation using other (private) methods. To the user of the class, getFoo() returns some data called 'foo', but it can't see where it comes from -- whether it's stored, or derived, or some combination.

Related

Why doesn't java allow to assign weaker access privileges to static methods in a child class?

I understand why java doesn't allow to set weaker access privileges for overridden methods, but why is it the same for static methods? I mean, these methods only hide each others, right? So what's the problem from the encapsulation point of view?
P.S.
I know that there are 5 rules for hiding a method
The method in the child class must have the same signature as the method in the parent
class.
The method in the child class must be at least as accessible or more accessible than the
method in the parent class.
The method in the child class may not throw a checked exception that is new or
broader than the class of any exception thrown in the parent class method.
If the method returns a value, it must be the same or a subclass of the method in the
parent class, known as co-variant return types.
The method defined in the child class must be marked as static if it is marked as
static in the parent class (method hiding). Likewise, the method must not be marked
as static in the child class if it is not marked as static in the parent class (method
overriding).
But after all, I don't get the idea from the encapsulation prospective
The same rules are valid and for method hiding
https://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.4.8.3
Static methods have special access permissions that allow friend access to members within a instance. For example, you could have a static method called create that creates a default instance of the class and directly modifies data within the instance without using instance properties or instance methods (just for a usage example, not necessarily a usage recommendation).
Because of this special access, lower access permissions to the static methods could allow you to create an object in a state that you could not otherwise use, or modify an object in an unpredictable and non-encapsulated way.
This is only a minor annoyance for most user-defined classes, but allowing this when sub-classing e.g. containers could expose serious undefined behavior problems.

Control access in methods

I have a question about Java.
I have a class Say.java that has some methods, like sayHello(), saySomething(), sayBye(), ...
I have other classes too. I have a class Person, and two subclasses of Person: Senior and Junior.
My job to do is the following:
I have to set the Say.java class to be private, and create a public class SayFactory.java, with a method called getInstance. Then, to create a new instance of the Say.java class, I have to call my getInstance method with one argument: an instance of either Senior.java or Junior.java. If I create an instance of Say.java using a Senior.java object, I must be able to access all of the methods of Say.java. But if I do the same thing with Junior.java, I should be able to access all of Say.java's methods EXCEPT saySomething().
Can someone please explain how to do this and how it works?
Apologies by the way - I'm from Spain so my English isn't that great. If you don't understand the question, let me know and I'll try to write it out more clearly.
First refer to this as answer to making a class private: Java: Why can we define a top level class as private?
For the objects that you want "private" you will have to make all the fields and possibly methods of it private (depending on what you need). Then as #user1071777 mentioned set up public getters and setters.
Some basic information on calling methods of an object:
http://docs.oracle.com/javase/tutorial/java/javaOO/usingobject.html
To create the connection between classes you can have a class have another class as part of its definition and set it up through constructor or public setter.
I know that I can't write Private Class but I can do a inner class.
I have a class SayFactory and within this I got another called Say
The SayFactory have a method called getInstance(), and in this method I create an object of Say class and return this object. The problem is, how to deny access to method saySomething() if the parameter of getInstance() is a object of Junior.

Class variable: public access read-only, but private access r/w

In my current project I have a class which stores its Instance in a variable. This Instance should be accesible by all other classes in the project, but it may only be altered by its own class.
How can I achieve this?
Write a public getter but no public setter. And the field itself private
In short that is called immutable object, state of Object cannot change after it is constructed.
String is a common example of immutable Class.
Make a class immutable by following-
ensure the class cannot be overridden - make the class final, or use
static factories and keep constructors private.
make fields private and final
force callers to construct an object completely in a single step,
instead of using a no-argument constructor combined with subsequent
calls to setXXX methods.
do not provide any methods which can change the state of the object
in any way - not just setXXX methods, but any method which can change
state
if the class has any mutable object fields, then they must be
defensively copied when passed between the class and its caller.
Someone suggests "public getter but no public setter for the private field."
Caution: This would only work if the field is primitive type.
If it is an object with setters, the content can still be modified; thus not read-only.
It will be interesting to see Java language provide some constructs to make a return type read-only without having to do a deep-copy / clone.
i'm imaging like
ReadOnly getEmployee() {
...}
The boilerplate code for instantiating a singleton can be found in many places, see for example http://www.javacoffeebreak.com/articles/designpatterns/index.html
Be aware that many consider the singleton to be an antipattern because it's pretty hard to get rid of once your application is littered with references to the singleton.

Java Reflection - Methods Introspection

Method[] theMethods = myClass.getMethods();
for( Method m : theMethods ){
...
}
Will the array include all the methods of the class? public, private, protected and all inherited?
Will I have access to all of them mainly the private and protected ones?
If not, how can I get all the methods of a class and also have access to all?
The Javadoc makes this pretty clear:
Returns an array containing Method objects reflecting all the public member methods of the class or interface represented by this Class object, including those declared by the class or interface and those inherited from superclasses and superinterfaces.
To get at non-public methods, use getDeclaredMethods.
To get all methods of a class you need to recursively call getDeclaredMethods() on the class and all it's superclasses. Depending on what you want to achive with it you might need to remove duplicates which can occur due to method overloading.
From the API doc:
Returns an array containing Method
objects reflecting all the public
member methods of the class or
interface represented by this Class
object, including those declared by
the class or interface and those
inherited from superclasses and
superinterfaces.
So it gets you only public methods. To get all methods, you have to use getDeclaredMethods() on the class and all its superclasses (via getSuperclass()).
In order to call non-public methods, you can use setAccessible(true) on the Method object (if the security manager allows it).

Accessing private instance variables of parent from child class?

Let's say we have a class foo which has a private instance variable bar.
Now let us have another class, baz, which extends foo. Can non-static methods in baz access foo's variable bar if there is no accessor method defined in foo?
I'm working in Java, by the way.
No, not according to the java language specification, 3rd edition:
6.6.8 Example: private Fields, Methods, and Constructors
A private
class member or constructor is
accessible only within the body of the
top level class (ยง7.6) that encloses
the declaration of the member or
constructor. It is not inherited by
subclasses.
But regardless of this language restriction, you can access private fields through reflection:
Field privateStringField =
MyClass.class.getDeclaredField("privateString");
privateStringField.setAccessible(true);
String fieldValue = (String) privateStringField.get(privateObject);
System.out.println("fieldValue = " + fieldValue);
No, for that you should use protected.
For questions like this, where is a table found on the website here: http://java.sun.com/docs/books/tutorial/java/javaOO/accesscontrol.html
Basically you want public or protected variable to be declared in foo since these are the variables that subclasses inherit from their parent and therefore seen in baz.
To use a private variable of a super class in a sub class, an accessor method is required.
Else use the protected modifier instead of private.
Child classes can not access private members (which is the whole point of private access control).
...if there is no accessor method defined in foo?
You need accessors. Besides, take care of inheritance, Should that var really be in parent? Remember IS-A check..
You cannot access private variables in descendent classes. Normally you'd want to use "protected" or "package" (the default) level access for this. However if you want to be really tricky, you can resort to using reflection and AccessibleObject to get at it.
I wouldn't recommend doing that for production code unless you are really in a bind; for testing, etc., it's fine.
The private variable(s) of a class invariably has a scope inside that class. If it has to be shared among the subclasses, it should be declared "protected"
Private members exist(inherited) in instances of child classes .Since, object of Sub class is also an object of Super class, but it is not visible for the sub class
They are accessible indirectly through non-private methods of Super class. These methods can access and manipulate private members
No,bar variable will not be accessible to baz. bar varible should be either protected or public .
Without an accessor method, it's not possible. You have to use a getter setter to access private data members from the superclass.

Categories

Resources