General programming question about scope - java

This is more of a general programming question so the code examples I give will just be pseudo-code. I program in C++, Java, and Python so the pseudo-code is a mix of those. I am not too sure what the name of this is called so if you could give me a name for this, I can Google for more information about it I would greatly appreciate it.
Let's say I have a class called A. In this class, I create an instance of a class called B:
class A {
//instance variables
classB;
variable1;
variable2;
//instance methods
instanceFunction(parameter1, parameter2) {
//Do Stuff
}
function1(parameter1) {
classB = new B(some parameters);
}
setVariable1(value) {
variable1 = value;
}
getVariable2() {
return variable2;
}
}
In class B, I want to make changes to or make use of instance variables in class A. I can do this by passing a reference to A into B. So my A::function1 would look like this:
function1(parameter1) {
variable1 = new B(this, other parameters);
//Python syntax:
//variable1 = B(self, other parameters)
}
and my class B would look like this:
class B {
//instance variables
parentClass;
variable2;
//instance methods
instanceFunction(classA, other parameters) {
parentClass = classA;
}
function1() {
parentClass.setVariable1(someValue);
}
function2() {
variable2 = parentClass.getVariable2();
}
}
What other ways are there to have use of the variables in class A inside of class B?
If the code was C++ or Java, assume all variables are private and all methods and functions are public. Also assume all variables are passed by references or a pointers.
Edit:
First, thanks for all the responses!
Some clarification:
The reason I am asking this question is I have done a good amount of Qt programming in C++ and Python. In Qt, there are signals and slots. This lets inner objects tell the outer object to do something. For example I have an object A with objects B and C inside of it. Some change happens to object B and B needs to let A and C know. So B will emit a signal. A will catch this signal and do what it needs to do. Then, A will also let C know that B emitted this signal. This way C can do what it needs to do.
The reason I asked my question is because I was wondering how I can do something like I described without using the Qt libraries.
Also, let's assume B "is not" an A so I can't/don't want to use inheritance.

I am not too sure what the name of this is called...
I am having trouble following your pseudo-code, but you might be able to accomplish what you're looking for via:
Inheritance, which allows derived classes to access protected variables from a base class (static or instance variables)
Friend functions (C++) (which allows functions to have access to private instance variables on a class)
Dependency Injection (But probably only if you have more complex requirements than you're actually stating in your question. In this super-simple case, you'd just be accessing public properties or fields when an instance is passed in to a function - you might have to access them through a public getter/setter, since you want the variables to be private)
Edit:
After your edits, it is pretty clear that you want the Observer Design Pattern. This allows you to decouple the code that responds to a state change from the code that signals the state change.
That pattern is less about access to variables (as my first links were about), than it is about responding to events (or "state transitions", if you think about your class as a Finite State Machine).

Given the edit you made; It may be practical to implement a sig/slot mechanism using boost::signals, or the threadsafe signals2 (also in boost). This is implying that you are looking for a behaviour similar to Qt's sigslot mechanism. There are also many alternatives, look at the SO question here.

Explicitly passing this (or perhaps a proxy around this) is pretty much the only (sane, anyway) way to do it, assuming they need to be seperate objects. An object can't and shouldn't need to know number and location of its references. And even if you could get a list of all references to itself, that list could easily contain local variables, items in collections, potentially several instances of A, etc. - how is it supposed to know which one to chose as its parent?
If a B actually "is an" A, you should just make it a subclass.

What other ways are there to have use of the variables in class A
inside of class B?
Since your variables are not static, they are instance variables, so variable1 and variable2 are only meaningful in the context of a specific instance of A - so there needs to be a reference to that instance, not matter how you shape it.
For example, inner classes in Java can use variables of the enclosing outer class directly, but in reality this is just an illusion maintained by the compiler, and in the bytecode, the inner class actually keeps a reference to the outer class instance.

In C++, there is a concept of friend classes: a class A can declare another class B to be its friend, something which gives B access to the private variables of A. Simply write friend class B; inside of A. (As #delnan reminds us, you still need to manually give B a reference to A.)
In Java, if you declare B inside of A, B will become an inner class. Inner classes can only be instantiated from an instance of the outer class, and the instance of the inner class will be tied to the corresponding instance of the outer class, and may access its private variables.
(I agree with #mellamokb, though: This is probably a bad idea, as it creates very tight coupling between the two classes. You might want to rethink your class structure. What exactly are you trying to use this for?)

To reduce coupling between the objects, you shouldn't let B have a reference to A - you should give it a reference to an interface implemented by A. The difference is subtle, but it really makes you think about what actions or data really need to be shared across the interface boundary.

Related

Can you access sub class variable via super class in Java

Can I access my subclass variable via super class instance?
For instance I create my super class object in Main, and then I want to know the value of variable in the sub class. Is it possible to do so? Thanks.
No this goes against the inheritance principle. It is like asking if a previous gen device will have access to the newer features introduced in the next gen device based on this.
A subclass can access non private members of parent class but not vice versa. It doesnt make sense as the language syntax doesn't ever allow access to child from parent while the opposite is possible through methods and keywords like super.
So it is better that you rethink the way you are thinking of using inheritance abd refactor your core to meet the requirement as this certainly wont work
If class B extends class A and you have an A object, then you can always convert it to its subclass, B in this case. Consider the following:
A a = new A();
B b = (B)a;
afterwards, you can always reach B members via b. You can do it in an inline manner as well, via ((B)a).

Why can I instantiate an interface without declaring a class? [duplicate]

This question already has answers here:
Why are only final variables accessible in anonymous class?
(15 answers)
Closed 6 years ago.
So in Java it's possible to instantiate an interface without creating an explicit class
public interface Foo {
public void OnNotify()
}
Say I do the following somewhere else, say in a method Subscribe
public void Subscribe()
{
final int someInt = 5;
Foo bar = new Foo() {
final int value = someInt;
#Override
public void OnNotify()
{
Log.d("Debug", "You are being notified that I hold the value " + value);
}
}
someObject.AddSubscription(bar);
}
This is used extensively in Android for setting listeners to events.
Why is this possible, and does this kind of instantiation have a special name? Is this related to lambda functions in some way perhaps?
And why do I need to make a 'final' variable if I want to give it to this instantiated interface to hold. Say for example I wanted to pass the current iteration 'i' of a for loop to identify what index of an array a subscription references. I need to declare a final variable to hold 'i', and then pass it into the instantiated interface.
Edit:
I'm still asking why I can instantiate an interface without making a class first, and what it's called. Not knowing what this is, there's no way I could have found the duplicate question, which doesn't cover what a Java anonymous class is.
Why is this possible, and does this kind of instantiation have a special name? Is this related to lambda functions in some way perhaps?
I don't know of any "special name" for this. I generally refer to it as a "interface implementation declaration." That's just me though, and maybe that's not accurate or correct.
I believe they are not, because aside from syntax differences, I look to lambdas as a method-class like structure, and this form is overriding methods from an object type. When passing an interface object, you're passing reference of a type.
And why do I need to make a 'final' variable if I want to give it to this instantiated interface to hold.
The way I have looked at it, and understood it to be, is because this declaration inline and not in a separate class doesn't quite change what an Interface still is. In the Java programming language, an interface is a reference type, similar to a class, that can contain only constants, method signatures, default methods, static methods, and nested types Link
An interface is required to have a constant, and to me final is a keyword that works similarly to the C/C++ keyword const in that it isn't holding the value but a reference to the type that you've declared. These values are immutable, preventing any copies and changes, as they only contain a reference to the location of the value.
So, overall, I believe that an interface declaration like how you illustrate is not working as declaring an instance of the actual interface class, but rather it's creating an object of that type and that object is a new location in memory that holds references to these methods and members (like a class).
Hope this helps some. I don't normally like to volunteer answers to something I am not 100% sure on, and wish this was a comment more (but lack the rep still for that), but hopefully it helps clear some things.
You can read the Java Language Specification here for more information on Interfaces too. Hope that helps.

How should i implement an interface in Java? [Code-Correctness]

First of all this is not a question about how to implement an interface in Java, or about an error with interfaces. This is a question about the right way to do it, depending on the situation.
First of all i would like to apologize if this is not the correct "stack" to post this question, please let me know and i'll move it to another one.
Let's begin.
What i'm trying to guess is which is the best way to implement an interface in Java. Let's say we have a class A like:
public Class A {
public A(){}
public void fooA() {}
}
And an interface
public interface MyListener {
public void fooListener();
}
Inside fooA() I'm making use of interface B this way:
...
something.setFooListener(/**Doubts here**/)
....
What should we type inside setFooListener(...)
Options are (As far as i know):
A) Define the behavior inside the setFooListener function:
new MyListener.fooListener() {
/** Implementation of fooListener() **/
}
Pros:
Easy and readable as you're reading the function.
You can access directly to FINAL variables defined in fooA().
Cons:
If your implementation is long enough it would end up in a lack of readability and a too long function.
If you're implementing the interface in a few places on the same class you are going to repeat a lot of code.
B) Create an inner class implementing the interface:
private class MyListenerImplementation implements MyListener {
private String var1;
private int var2;
public MyListenerImplementation() {/** constructor **/}
public void fooListener() {
/** Do logic here **/
}
}
Pros:
You can keep a reference to the object MyListenerImplementation.
You can define variables, functions and everything as it's an object like any other one.
Cleaner code.
Cons:
Maybe needs more memory.
Maybe creating unnecessary classes
C) Hold a variable with a reference to the interface implementation
private MyListener.FooListener myListenerVar = new MyListener.FooListener() {
/** Logic goes here **/
};
Pros:
I actually can't sees anyone comparing to B, but a lot of cons.
Cons:
Not a clean code. Doing this on top of your class would be, at least, a war crime.
I don't think it's correct to assign a block of code to a variable.
I don't like how this looks ;)
D) The last one i could think of; define a function and inside return the implementation
private MyListener.fooListener createMyListener() {
return new MyListener.fooListener() {
/** Logic goes here **/
}
}
Pros:
It's cleaner than C.
Reusability
Cons:
Almost the same ones as C.
I don't think it's correct to return a whole block of code.
To sum up: Which i like the most is "B", but i would like to know what does SO thinks of this.
Thanks in advice.
Option A is not syntaxically correct. Your pros and cons are valid.
Option B:
Maybe needs more memory: no.
Maybe creating unnecessary classes: no. Option A also creates a class. It's anonymous, but it's a class, that must be loaded by the ClassLoader like any other class.
Option C: it's exactly the same as A (anonymous class usage), except you initialize a field with the listener. The rule is the same as for any other variable: reduce its scope as much as possible. If you need a field scope, use this option. If you only need the listener in one method, then use a local variable (option A).
Option D: once again, it's the same as A, except you return the created listener instead of only using it.
My recap: you're mixing three orthogonal problems here.
Should I use an anonymous inner class, a named nested class, or a top-level class. This depends on the amount of code contained in the class, and on where you need to use this class: in a single top-level class, or in many top-level classes.
Should I use local variables or instance variables. it's a matter of scope and state, not a matter of interface implementations. Your field or local variable can be initialized with an instance of any kind of your interface implementation
Should you use a factory method returning instances, or should you use new directly. Once again, that has nothing to do with how your interface is implemented. If you want to be loosely coupled, because the factory method might return different implementations of the same interface, use a factory. Otherwise, new is fine.

Java member object inside class of same type

I am looking at a codebase and I often see something like:
public class SomeClass
{
protected static SomeClass myObject;
//...
public static SomeClass getObject()
{
return myOjbect
}
}
I'd like to make sure I understand the purpose behind this. Is it to ensure one instance of the class gets shared even if it is instantiated multiple times? I am not sure about the vocabulary here, or else I'd search for the answer, so if this pattern has a name, please let me know.
Also, this seems a little chicken-and-egg definition because the class includes an object of the type of the class. Why isn't this actually paradoxical?
Thanks!
This is really only common with the Singleton Pattern where there is only this one instance of the class. While it has its uses, Singleton is over- and misused more often than not (usually to disguise procedural programming as OO). It also occurs very often in example code for Java AWT or Swing, where you typically subclass Frame / JFrame, and create an instance in a main method inside the same class.
Also, this seems a little
chicken-and-egg definition because the
class includes an object of the type
of the class. Why isn't this actually
paradoxical?
Why do you think it is? The class mainly describes what members instances of this type have - but a static member does not belong to an instance, it belongs to the class itself, so it doesn't have anything to do with the "blueprint" role of the class. Static members are really somewhat un-OO because of that.
But even on the instance level you can have references of the same type. For example, an entry in a linked list would typically have two references to the next and previous entries, which are of the same class.
This is called the Singleton design pattern.
You are correct in stating that the purpose is to ensure only one instance of the class gets created.
Wikipedia has a preyty good article on the pattern.
The pattern you mentioned is called "Singleton", but from your code sample it is not clear if this is really what is intended. Due to the fact that the member is protected, I would guess not - if there are subclasses, then there would probably not be a single instance.
It's called Singleton. You ensure the creation of just ONE (1) object of a given class.
You should add a private Constructor, so the only one who create the object is the class.
public class SomeClass
{
// Using private constructor
protected static SomeClass myObject = new SomeClass();
private SomeClass(){
//...
}
public static SomeClass getObject()
{
return myOjbect
}
}
Much much more here, in Wikipedia
You may want to take a look to Factory Pattern
It's not all that uncommon; it can be a good way to implement the Singleton pattern. There can be other uses as well - sometimes you will want a handful - and no more - of objects of a given class; that class is a good place to hang onto them. In the event that you don't want other classes to be able to create objects of this class, it is common to give the class a private constructor as well.
It's not paradoxical, because the compiler can be aware of a reference to the class before it has fully compiled the class. Later - if you like to think of it this way - it can "fill in the blanks".

Is a function kind of like a static method?

I'm a java programmer and am trying to understand the difference between a method (java methods) and a function (such as in c++). I used to think that they are the same, just different naming conventions for different programming languages. But now that I know they are not, I am having trouble understanding the difference.
I know that a method relates to an instance of a class and has access to class data (member variables), while a function does not (?). So is a function kind of like a static method?
See here for explanations I read which led me to think this.
A function is simply a generic name for a portion of code within a program. The word "method" is a synonym for function. So are "subroutines" and "procedures," etc.
Java and C++ functions are for the most part exactly the same thing.
The word "method" tends to be used for subroutines associated with an instance, while "function" tends to be used for those that are global/static.
But even then, "methods" are generated by the compiler as though they were "functions."
Consider this C++ code:
class Foo
{
public:
void DoFoo(int param)
{
printf("%d, %d\n", param, member);
}
private:
int member;
};
int main()
{
Foo f;
f.DoFoo(42);
return 0;
}
The compiler generates code to something equivalent to this:
struct Foo
{
int member;
};
void Foo_DoFoo(Foo* this, int param)
{
printf("%d, %d\n", param, this->member);
}
int main()
{
Foo f;
Foo_DoFoo(&f, 42);
return 0;
}
So the distinction between "method" and "function" is merely a convention.
This is strictly a vocabulary difference. Some consider a method an operation that belongs to an object or a class, and a function an operation that doesn't. Others, like the C++ crowd, call them both functions but refer to free functions or non-member functions when the function doesn't belong to a class or an object. I personally use the two interchangeably.
All in all, in the C++ jargon when you wish to refer to specific kinds of functions (non-members, members, returning no value, ...) you add an adjective to the noun function: a friend function, a void function, a member function and so on.
In C all "functions" are "top level" in the sense that they were not associated with a type. If they were in your scope (e.g., via an include), you could refer to them and they could be linked.
In C++ you can create classes and place methods in them. Methods marked as static are invoked via a particular class but are not associated with an instance of the class. In that sense they are like functions. However, they are allowed some privileges associated with the class (e.g., they can be made private and can access private static members). However, you can still use C-style functions, for example for library functions.
In Java every method is associated with a class, so there are static methods but no C-style functions.
Lets put it really simple a function is the same as a Java static method, however a function does not require a class to exist, which turns it as Uri says in a top level piece of code.
One of the advantages of this is that it won't require an object instantiation to be called.
Is a function kind of like a static method?
Kind of. But I'd rather say that a static method is like a function that has been enslaved and shackled to an object. For an elaboration of this point of view see Execution in the Kingdom of Nouns.

Categories

Resources