Public access only to class that owns an object - java

I've always wondered. I have this Vertex class that's part of a generic Graph class. This Vertex class owns an object that's an entity. In my system everything happens trough the Vertex, you can't directly access the entity object with a getter. I realized though that I had to create public methods in my entity class so they can be called from the Vertex class. Is there a way to only expose methods to a class that owns said object?
Because right now I can instantiate an Entity and use it's public methods, but it doesn't make sense outside of the Vertex class. I don't know if there's a pattern or something people do to only let owners use methods of whatever they hold.
I'm using Java right now, but C++ is fine too. I believe in C++ you can use the friend keyword.
//Vertex.java
public class Vertex
{
private NodeDrawable _node;
...
}
//NodeDrawable.java
public class NodeDrawable
{
private disable();
}
I'd like to make Vertex the only class that's allowed to access NodeDrawable methods. Inner classes are cool, but I don't like having multiple classes in a single file.

First, I would ask myself if it is feasible to expose the Entity class at all. After that, you can make the Entities methods private, your Vertex class can still access them and everybody else don't - compares to protected methods which could be accessed by classes in the same source code package.
Edit
You will have to choose the access modifiers out of the Java possibilities and Java does not enable you to specify a single "friend" class - the Java way of doing this are inner classes.

One should have minimal required access to the object and its elements. If you don't require access to entity and it makes sense to have it's access through Vertex only, Make all object handles and methods private within Vertex.

I think want you want is simulate the c++ friend modificator in java look at this this question. Hope it helps.

You can use an inner class. The inner class has access to its containing class' variables and methods, and vice-versa. If you would like only the outer class to have access to the inner class, you can make the inner class private. Then not even other classes in the same package could call Outer.Inner (or in your case, Vertex.Entity). See docs.oracle.com/javase/tutorial/java/javaOO/nested.html

Related

What is the purpose of creating a class-level variable in Java?

I was writing a piece of code that goes like this,
public class Grades
{
public int marks; // what's the purpose of this?
...
...
}
Objects are data and methods encapsulated together into a single software component.
Classes are templates ("cookie cutters") from which you can create one or more instances in memory ("cookies"). Each one is independent; each can have its own state.
By declaring the variable outside of any methods you've made it an attribute of the class. This means that any method in the class can access it, and depending on its encapsulation (public/private/protected/package private) other classes can access it as well.
As for that specific variable's purpose in that specific class, that cannot be determined without seeing more code.

Is this a good situation for a Nested Class? If so, should it be static? [duplicate]

This question already has answers here:
When to use inner classes in Java for helper classes
(10 answers)
Closed 8 years ago.
So I have a ClassA:
public ClassA {
String key;
List<ClassB> value;
}
And this ClassA is mapped to a database table (with 2 columns having key -> list of values) and the values here get stored as a row in there.
public ClassB {
Integer data1;
...
String dataN;
/* constructors and some getters/setters follow */
}
To clarify, ClassB just contains some data that is being stored in database.
When ClassA is being saved, List<ClassB> is being converted to JSON string and getting saved.
There are 2 ways to define ClassB.
Either have it as a regular class
Define it as a inner class(not sure if static or not) inside classA.
ClassB is currently not being used anywhere else in the project.
What do you think should be the right way and why?
I am bit confused regarding nested classes and I cannot distinguish if they are being misused or not.
Personally, if the class is small (for example just an helper) and is not to be used anywhere else, I would prefer doing an inner class. However, this is mostly a matter of opinion.
I think the best in these case is to make sure everyone in your dev team work the same way so it is easier for everyone to debug.
Note that there is a difference between inner class and nested class. A nested (static) class is an inner class declared static, while a simple inner class is normally not static.
Nested static class can be accessed anywhere using Class.NestedStaticClass.
See Nested class documentation for more details and example.
Here an interesting quote from the link I gave u before :
Serialization of inner classes, including local and anonymous classes,
is strongly discouraged. When the Java compiler compiles certain
constructs, such as inner classes, it creates synthetic constructs;
these are classes, methods, fields, and other constructs that do not
have a corresponding construct in the source code. Synthetic
constructs enable Java compilers to implement new Java language
features without changes to the JVM. However, synthetic constructs can
vary among different Java compiler implementations, which means that
.class files can vary among different implementations as well.
Consequently, you may have compatibility issues if you serialize an
inner class and then deserialize it with a different JRE
implementation. See the section Implicit and Synthetic Parameters in
the section Obtaining Names of Method Parameters for more information
about the synthetic constructs generated when an inner class is
compiled.
You might also consider using Anonymous inner class. An anonymous inner class is a class coded directly in the instanciation. For example
new ParentClassName(constructorArgs) {
members..
}
ClassB is currently not being used anywhere else in the project.
I think the key word here is "currently".
If you imagine a situation in which ClassB might be useful in other places in the project (say, if that project grows in a particular way, or if there are other tables that might map to the same structure in the future), then it should probably be a "normal" class.
If the class is logically tied to ClassA. For example, ClassA represents a train and ClassB train cars, which are always related to trains and never to other vehicles which are not trains, then you should define it as a nested class or inner class of ClassA.
Whether to make it nested or inner depends on the type of connection between an object of class ClassB and one of ClassA. It's not always a clear-cut issue, but remember that static nested classes can exist independently of their parent class. (e.g. you can manufacture a train car before you ever create a train object that it will be part of, and you can move train cars between trains), while inner classes always contain an invisible reference to their parent object, and such an object has to exist before you can create an object of the inner class.
All else being equal, I think I would gamble on a static nested class as an initial solution. If I realize that there are other places that need the same class, it's going to be relatively easy to refactor it.

What are the purposes of inner classes

I am reviewing the concept of inner classes in java. so far from what I've understood and applied java inner classes has a link or access to the methods and fields of its outer/ enclosing class.
My Question:
When should create or define an inner class?
are inner classes considered to be called as "Helper classes" ?
What are the indicators for you to make an inner class and what's their other purpose?
Inner classes are best for the purpose of logically grouping classes that are used in one-place. For example, if you want to create class which is used by ONLY enclosing class, then it doesn't make sense to create a separate file for that. Instead you can add it as "inner class"
As per java tutorial:
Compelling reasons for using nested classes include the following:
It is a way of logically grouping classes that are only used in one
place.
It increases encapsulation.
It can lead to more readable and maintainable code.
A classic use for an inner class is the implementation of an iterator inside a container (ArrayList, for example - look for class Itr). All the container wants to expose to the rest of the world is an Iterator. However, it has to create some concrete implementation of that iterator, possibly familiar with the internals of the container. Using an inner class hides the implementation, while keeping it close to the container's implementation. And being inner (i.e. non-static), it is bound to a specific instance of that container, which lets it access private container members.
There are a few types of inner classes - non-static nested class, local classes and anonymous classes. Each one has a somewhat different purpose, so when asking about an inner class, you should specify what kind are you talking about.
Assuming you're referring to non-static inner classes, I'd say the reason to use them is the same as using regular classes (namely abstraction and dividing code into logical units), but there's no reason to make this use of classes visible to the rest of the world. You can also make nested classes public, of course, in which case you'd make them nested instead of independent in order to express their tight relation with the outer class.
See the Java tutorial for the main reasons.
If by "helper class" you mean something for internal use only, then no, not necessarily. You might want to do something like
class Outer {
private static class Inner implements InterestingInterface {
// whatever
}
public InterestingInterface make_something_interesting() {
return new Inner();
}
}
Here, Inner is not a "helper class" in the sense that the outside world does get to see instances of it, but its implementation is entirely hidden -- the outside world only knows it gets some object that implements InterestingInterface.
As a general rule, objects should be designed for a single responsibility (Highly cohesive). In other words, any object designed well, should perform a single coherent task. This would be considered best practice for object orientated design.
Sometimes, however, a developer may design a class that requires a separate specialized class in order to work. This separate specialized class could be considered a helper class.
If the helper class is not used by any other class, then it would be considered a prime candidate as an inner class
As elicited by ncmathsadist above, an example of inner class use would be in the implementation of Event handlers.
For example, in designing a graphical user interface (GUI), a developer may have created a button that performs a particular task after the user presses it.
The button would need an event handler which listens for when that particular button is pressed.
In this case, creating the event handler for the button as an inner class would be best practice as the inner class would not be utilized anywhere else other than with the specific button within the GUI class.
One purpose of inner classes is to attach listeners. For example, suppose you have a JMenuItem. You can make it quit your app as shown in this code:
JMenuItem quitItem = new JMenuItem("Quit");
quitItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
//cleanup code before exiting
System.exit(0);
}
});
You may also want a class to have access to outer class state variables which is entirely subservient to that class. For example, consider writing a simple color calculator. It might have a text area into which you type a hex code. When you hit enter, you want a JPanel to display the color. Here is a crude outline of what you might do.
public class ColorCalc extends JPanel implements Runnable
{
Color displayedColor;
JTextArea colorEnterArea;
public ColorCalc()
{
displayedColor = Color.white
colorEnterArea = new JTextArea();
}
public void run()
{
//build GUI here
}
public static void main(String[] args)
{
ColorCalc cc = new ColorCalc();
javax.swing.SwingUtilities.invokeLater(cc);
}
//subservient inner class with access to outer class state variable.
class ColorPanel extends JPanel
{
public void paintComponent(Graphics g)
{
g.setColor(displayedColor);
g.fillRect(0,0,getWidth(), getHeight());
}
}
}
This is a style question. Anything that can be done with an inner class can also be done as a as series of external classes. Inner classes are especially useful for classes that are lightweight or tightly bound to the enclosing class. For example, a comparator is frequently both these things. It needs intimate knowledge of the implementation of the class, and may only be a few lines long. It may be an ideal candidate as an internal class.
If you find that there is enough code which could be better done by class as class provides us to specify stats and
behavior with fields and methods and you don't want this class needs to be used outside of enclosing class. you should use inner class.
Here the inner class is hidden from the outside world.
Inner class can access the private member of enclosing class which provides us encapsulation.
Let me give example..
Suppose you want to set the gear to cycle and you have a business rule like there are only up to 6 gears.
So you can create Inner Class Cycle which would have a method to set the gear.
That method has some validation which are checked before setting gear.like the cycle is running...gear number is less than 6...
best example is event handling code uses inner classes(sometimes anonymous inner classes) to create events and listeners without creating separate Event Object and Event Listener classes for your event..
The inner class used for grouping classes logic, for example, if you have class B and this class used only at class A, So it is better to put class B as an inner class at class A, as this will give readability and reusability for your code.
Happy code :)
Adding from my personal notes, for future visitors:
Sources: https://docs.oracle.com/javase/tutorial/java/javaOO/whentouse.html
Lets say you have a type and its a class, called OuterClass, in a package called "com.custom.classes".
Then here is how you begin to need an inner class or static class:
Case 1:
you need to package a group of classes
but also kind of need certain global variables exposed to all these classes at that package level
you understand you can do no such things with packages but realise that you could achieve this with inheritance, where the parent class members can act as global variables that become available for all of its child class instances.
but you don't like the idea that you need to inherit the parent class and also that you need to instantiate the child class to access the global variables. Thats like asking to buy a coffee shop in order to have a coffee.
and so you realise that you can create an OuterClass with the static members and house all the classes in this OuterClass as inner class or static class as needed and lo! The OuterClass static members become available as global variables for these nested classes and you could even access them without instantiating them.
This code should explain better
public class InnerClassTester{
public static void main(String []args){
// without the need to instantiate any class
// static class without instantiation
System.out.println(OuterClass.NestedStaticClass1.incrGlobalNum()); // outputs 1
// static class instantiated
OuterClass.NestedStaticClass2 koolObj = new OuterClass.NestedStaticClass2();
// works with instantiation as well
System.out.println(koolObj.incrGlobalNum()); // outputs 2
// inner classes always need to be instantiated
// and they can only be instantiated from within an instance of outer class
// think of them as instance member of outer class and this would make sense
OuterClass.NestedInnerClass1 koolObj2 = new OuterClass().new NestedInnerClass1();
// works with inner classes as well
System.out.println(koolObj2.incrGlobalNum()); // outputs 3
}
}
class OuterClass{
// global variable thats only accessible for select classes (or nested classes)
// we also learn a purpose for private static fields
private static int privateGlobalValue = 0;
// classes to be grouped
// static class
public static class NestedStaticClass1{
// no need to instantiate this class to access/update the global value
public static int incrGlobalNum(){
return ++privateGlobalValue;
}
}
public static class NestedStaticClass2{
// instantiate and still manipulate the global value
public int incrGlobalNum(){
return ++privateGlobalValue;
}
}
// inner class
public class NestedInnerClass1{
// instantiate and still manipulate the global value
public int incrGlobalNum(){
return ++privateGlobalValue;
}
}
}
Does this remind you of closures in Javascript ? :)
Most applications of nested classes see it being applied on basis of design decisions. What that means is, every case of a nested class can be replaced with other designs.
But having said that, it is also true that we can also replace the inheritance pattern with composition pattern (and it is gaining momentum lately) although an inheritance pattern is definitely better when the dependencies between the classes is so much so that composing the dependencies entirely would be ugly.
Case 2:
you need to implement 2 interfaces, IShark and IMosquito, with the same signature, a public bite method, on the OuterClass.
but you want to display 2 different messages since a shark's bite is a tad different from that of a mosquito's.
however you know that's not possible since only one bite method can be implemented
you know you can create 2 different classes in the same package that implement either interfaces and also implement separate bite methods and have them composed in OuterClass.
but you wanted to get it done within OuterClass because it was your design decision to encapsulate the bite behaviour within it, maybe because there was a dependency on a private variable within the class.
soon you realise you can implement both the interfaces via private static inner classes and make it appear to the outside world as though it was composed.
Take a look at this code:
// no additional classes in the package
public class InterfaceTester{
public static void main(String []args){
// same class returns 2 instances - both compliant to
// either interfaces and yet different output
IShark shark = OuterClass.getSharkInstance();
System.out.println(shark.bite()); // outputs "Die fast bosedk!"
IMosquito mosquito = OuterClass.getMosquitoInstance();
System.out.println(mosquito.bite()); // outputs "Die slow bosedk!"
}
}
interface IShark{
public String bite();
}
interface IMosquito{
public String bite();
}
class OuterClass implements IShark{
// dependency of inner class on private variable
private static String dieSlow = "Die slow bosedk!";
private static String dieFast = "Die fast bosedk!";
private static OuterClass outerInst;
private static InnerClass innerInst;
// private constructor to stop regular instantiation
private OuterClass(){}
// get a shark !
public static IShark getSharkInstance(){
return outerInst != null ? outerInst : new OuterClass();
}
// get a mosquito !
public static IMosquito getMosquitoInstance(){
return innerInst != null ? innerInst : new InnerClass();
}
// an implementation of bite
public String bite(){
return dieFast;
}
// inner class that implements the second interface
private static class InnerClass implements IMosquito{
// different implementation of bite
public String bite(){
return dieSlow;
}
}
}
These kind of design decision cases are numerous and all of the answers above list several such cases. So it would not be wrong to think that this feature was introduced more as a new pattern than as a feature or functionality.
Conceptually inner classes can be used to represent types in the universe that would not exist without that parent type. In other words, with a language that allows inner classes, the types are all 'type definers'. A type can then be considered something that explicitly or implicitly defines new types.
For example, imagine we have a universe where "Food" can be applied to anything. Even itself. Food is a fundamental concept in our universe. We introduce a subclass of Food called Meat. Without that concept, there is no such thing as "Meat Eater". So we can (note 'can') define a nested type "Meat.Eater" (which could implement an IEater interface) and define animals as being a containment structure of lists of different IEaters.
Once we remove Meat from the universe, Meat Eater disappears to.
This same philosophy applies neatly to more abstract and technically useful arrangements such as Mementos in the Memento Design Pattern , a configuration object defined as a nested class, and other type-specific behaviours or structures.
It also increases encapsulation because inner classes can be declared private.
I would just consider that this is just a feature of language. I would not recommend to use it if we adopt OOD and obey the SOLID principle.

using interface to communicate between 2 java classes

I have 2 classes A and B.
class A implements Constants{
private int state;
}
class B implements Constants{
foo(){
//want to set state variable of class A like this
state = state1
}
}
interface Constants{
public final int state1;
public final int state2;
}
I don't want to have an instance of class A in class B. How should I do this?
If I have a function to set the variable in the interface, then both the classes must implement this function. That would be wrong right? Because then 2 definitions for the same function would conflict?
There is nothing called functions in java. They are methods.
You can have getters and setters in your classes for the properties to set and get them from external classes.
Your question is unclear.
If your B class extends the A class, then through the constructor of the B class, you can set the properties of the A class that is the super class.
Hope it helps!
Having an interface does not mean that the variable will be shared between the classes, it is more of a way to define classes that MUST override the functions in the interface. You can read the very basics on them here. To share a variable between two classes, you can either make the variable static and put it in another class that both your classes extend (in effect a global variable, which is bad practice and not thread safe), or have one of the classes have an instance of the other and call getters/setters.
EDIT: there is a similar question here that shows you what I mean about the static variable.
You generally want to avoid writing any method in a class that attempts to alter the internal state of another class. Whatever trick you come up with to accomplish such a thing, you are breaking the principle of encapsulation which is the whole reason for using classes in the first place.
If there is some state that you wish to have accessible from multiple classes, I would recommend breaking that state out into it's own class and have each of the two classes interact with it through getter/setter or utility methods.

Stuck on Object scope in Java

I'm working my way through an exercise to understand Java, and basically I need to merge the functionality of two classes into one app.
I'm stuck on one area though - the referencing of objects across classes.
What I have done is set up a gui in one class (test1), and this has a textfield in ie.
chatLine = new JTextField();
in another class(test2), I was planning on leaving all the functionality in there and referencing the various gui elements set up in test1 - like this test1.chatLine
I understand this level of referencing, I tested this by setting up a test method in the test2 class
public static void testpass() {
test1.testfield.setText("hello");
}
I'm trying to understand how to implement the more complex functionality in test2 class though, specifically this existing code;
test1.chatLine.addActionListener(new ActionAdapter() {
public void actionPerformed(ActionEvent e) {
String s = Game.chatLine.getText();
if (!s.equals("")) {
appendToChatBox("OUTGOING: " + s + "\n");
Game.chatLine.selectAll();
// Send the string
sendString(s);
}
}
});
This is the bit I'm stuck on, if I should be able to do this - as it's failing on the compile, can I add the actionadapter stuff to the gui element thats sat in test1, but do this from test2 - I'm wondering if I'm trying to do something that's not possible.
Hope this makes sense, I'm pretty confused over this - I'm trying to understand how the scope and referencing works.
Ideally what i'm trying to achieve is one class that has all the main stuff in, the gui etc, then all the related functionality in the other class, and target the first class's gui elements with the results etc.
Any thoughts greatly appreciated.
If you can access chatLine in the first place, you can call its (public) methods, including addActionListener. To access chatLine directly, you need to make it public, and if you want to make it specific to the class (as opposed to a different chatLine for each instance of the class), it needs to be static.
Note, however, that it's often desirable to not make variables public. An important reason for having classes and objects in the first place is encapsulation. You might consider hiding the implementation inside the classes by making it private and only providing higher level public methods to access what is needed, e.g. do not expose the "raw" JTextField but rather expose the functionality you use it to provide.
I'm not clear on whether chatLine is a local variable, an instance variable, or a static variable. Any of these things could be the source of your compile error, which you didn't specify -- what's the error?
If it's an instance or static variable, it can be made visible from anywhere by making it public. This doesn't mean that's a good idea.
At least, it should be private and exposed via a getChatLine() method.
Even then, there's some question about whether this design is the right one, but at least you'd be doing it right at a compiler level and basic data encapsulation level.
Generally speaking everything in Java is referenced but primitive types.
The so called visibility of objects is another matter:
public scoped members are visible
to all
'Package Friendly' members (those
that have no scope explicitly
mentioned) are visible to all abjects
belonging to the same package
protected scoped members are both
'Package Friendly' and visible to all
inheriting class objects
Finally, private scoped members are
visible only to the object itself
[Objects from the same class can view
each other's private members (as far
as I can recall)]
Now,
an inner static class can access its
enclosing class's static members.
A 'normal' inner class (without the
static modifier) can access its
enclosing class's static members
and enclosing object's instance
members - that goes as well to
anonymous inner class.
Finally any chain of method/field calls as below is valid (but ugly) as long as no part of the chain 'references' a null:
myObj.getThatObject().somePublicField.doSomthing().activate().someOtherPublicField
One recommendation though is not to declare members as public...

Categories