Is it possible to declare a class level variable from within a method?
I'm simply trying to create a static counter, but I only want to create it if needed. The class calling it should live longer than the function itself.
My need for this is rare, but I'm interested if it would work.
Not it is not possible to declare class level field, unless you're doing some metaprogramming stuff like insane bytecode level modification that wouldn't pay for itself. All declaration is done at compile time.
"Is it possible to declare a class level variable from within a method?"
If literally - yes :) it is possible with method-local classes :
void method() {
class LocalClass {
private Object variable;
}
}
'static ... when needed' is a contradiction in terms. The answer is 'no'.
Related
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.
As we use "default" keyword as a access specifier, and it can be used in switch statements as well with complete different purpose, So i was curious that is there any other keywords in java which can be used in more then one purposes
The "default" in the case of access modifier isn't a keyword - you don't write:
default void doSomething()
However, when specifying the default value of an attribute of annotations - it is.
switch (a) {
default: something();
}
and
public #interface MyAnnotation {
boolean bool() default true;
}
That, together with final as pointed out by Jon Skeet seems to cover everything. Perhaps except the "overloaded" for keyword:
for (initializer; condition; step) and for (Type element : collection)
You can't use default as an access specifier, so I don't think even that counts. (EDIT: As Bozho pointed out, it can be used in annotations.)
final means "can't be derived from / overridden" and "is read-only" which are two different - but related - meanings.
default can be used both in a switch and as a default value in an annotation (as pointed out by Bozho)
final means "can't be derived from / overridden" and "is read-only" which are two different - but related - meanings (as pointed out by Jon)
extends can be used both to specify the supertype of a class and can be used in wildcards and type variables to put a constraint (related but not exactly the same) (List<? extends Foo>)
super can be used to specify to something in a superclass of the current class, or in a wildcard to put a constraint (List<? super Foo>)
static means both "part of the class, not an instance" (for methods, attributes or initializers) and as a static import
class to declare a class (class Foo {}), or to refer to a class literal (Foo.class) (as answered by ILMTitan)
(for can be used in a normal for loop and the "enhanced" for, but that's more like overloading (as Bozho puts it so nicely) than really having two meanings)
Something no one else has mentioned yet: the class keyword has two different uses.
Declaring a class:
class Test{};
and indicating a class literal:
Class<Test> testClass = Test.class;
The final keyword can mean different things.
When modifying classes is means that the class cannot be subclassed.
When modifying a method, it means that the method cannot be Overridden.
When modifying a variable, it means that the variable cannot point to any other variable.
The default keyword is not used as an access specifier. The absence of private, protected and public means use of default.
Example:
class Test { // default access for class.
int A; // default access for the class member.
}
Some examples of Java keywords which find different use are:
final : A final class cannot be subclassed, a final method cannot be overridden, and a final variable can occur at most once as a left-hand expression.
Super: Used to access members of a class inherited by the class in which it appears, also used to forward a call from a constructor to a constructor in the superclass.
Static: Used to create static initialization blocks, also static members and static imports.
for:Used for the conventional for loop and the newer Java 1.5 enhanced for loop.
The static keyword associates methods and fields with a class instead of instances of that class, but it's also used to signify static initialization sections as in:
public class MyClass
{
private static int a;
static
{
a = 1;
}
public static void doSomethingCool()
{
...
}
}
Pascal's comment reminded me of static imports:
import static MyClass.doSomethingCool;
public class MyOtherClass
{
public void foo()
{
// Use the static method from MyClass
doSomethingCool();
}
}
I gave a look at java keywords but it seems that keywords are unique.. you can check yourself.
By the way default can't used as an access specifier, it's inherited when noone is specified.
Do we really use default as an access specifier? No specifier at all is "default". But you don't use the keyword that way.
final has different uses:
in a variable declaration it means a variable can't be changed.
In a method signature it means a method can't be overridden
In a parameter list it means a variable can't be altered in a method.
The "extends" keyword can be for single inheritance (either implementation or "pure abstract class" aka "interface inheritance" in Java).
The "extends" keyword can also be used for multiple (interface) inheritance.
The ones who always argue that Java doesn't support multiple inheritance will hence have a hard time arguing that "extends" in those two cases is doing exactly the same thing.
Now I'm in the other camp: I consider that multiple interface inheritance is multiple inheritance and that implementation inheritance is just an OOP detail (that doesn't exist at the OOA/OOD level) and hence I consider that "extends" is really doing the same thing in both case and that hence my answer doesn't answer the question :)
But it's an interesting keyword nonetheless :)
You can think of the following things
Default
final
super
":" (colon) used at different places , which has a different meaning at different places
As all the other answers have stated, there are many keywords that server multiple purposes depending on context. I just wanted to add that there is a reason for this: There is a strong aversion to adding keywords because such additions break existing code, so when new features are added existing keywords are used if they make a reasonable fit, such as super and extends for generics and default for annotations, or they are just skipped as in the colon used in the enhanced for loop.
So my point is to expect that as the language continues to evolve even more uses are found for existing keywords rather than introducing new ones.
BTW there is no such thing as an access specifier in Java. The term in the JLS is 'access modifier'.
Can final keyword be used for a method?
Absolutely! The final keyword can be applied to just about anything, in each case meaning "you don't get to change this anymore."
Here's what it means when applied to...
a variable: You simply cannot assign the variable a new value (rendering it a constant, of course)
a method: You cannot re-implement (i.e., override) this method in a subclass
a class: You cannot define a subclass
In each case we're simply indicating: once this thing is declared, this is the last value (or implementation) you'll ever see for it.
Yes, it is possible to declare a method as final. That will mean that a method cannot be overridden by its subclasses.
From The Java Language Specifications, Third Edition, Section 8.4.3.3:
A method can be declared final to
prevent subclasses from overriding or
hiding it. It is a compile-time error
to attempt to override or hide a final
method.
For more information, the Writing Final Classes and Methods page from The Java Tutorials has more information.
Yes.
You can make a method final
public class A {
public static final void f() {
System.out.println("test");
}
}
There are typically two reasons for making a method final
When a method is final, it "may" be inlined.
When a method is final, the method is impossible to override.
Sure can. Making it impossible to override.
Sure, check out The Final Word on the Final Keyword
public abstract class AbstractBase
{
public final void performOperation() // cannot be overridden
{
prepareForOperation();
doPerformOperation();
}
protected abstract void doPerformOperation(); // must override
}
Yes.
A final method cannot be overridden by subclasses. This is often used to prevent subclasses from altering crucial behaviors of the class.
As a note to the other answers. You can use final. In practice I rarely see people using it and I'm not sure why.
A lot of the code I write these days is intended for multi-threaded environments and I tend to make the class final an immutable (if its a value class) so that it is threadsafe.
The problem with marking some methods as final (and not others) is that you are stating that there is something special about that method and nothing special about the others. That's rarely what people actually mean in my experience.
If a class is intended for inheritence you need to keep it clean and keep it small to prevent unwanted side-effects. All this depends on whether you are writing code for your self and your team or whether you are writing for a wider audience - i.e. a public api on an Open Source project or a commercial project.
yes, final keyword can be used for a method. It will preserve the immutability. it prevents between methods from being broken. For example, suppose the implementation of some method of class X assumes that method M will behave in a certain way. Declaring X or M as final will prevent derived classes from redefining M in such a way as to cause X to behave incorrectly.
I wonder if there's a way to define a class in such a way that instances of it will never be members of another class (only local variables), or the other way round - only members but never local.
Is there any way in which a class can dictate the scope of it's prospective instances?
I don't think so. But I have no definitive proof.
To limit the scope you'd some sort of class annotation or class modifier and the virtual machine needed the functionality to check, whether a class (or any subclass of this restricted class) was assigned to a member or local variable and violated the constraint.
Just imagine, you had a class with the - just invented - 'onlylocal' modifier, indicating that you only allow instances in local variables.
public onlylocal class LocalUseOnlyClass implements Serializable {
//...
}
and in another class someone just did in a constructor:
private Object member;
public MyOtherClass(Serializable something) {
this.member = something
}
The Compiler couldn't detect, if you passed an instance of LocalUseOnlyClass to that constructor, so the JVM had to check and throw an exception or an error.
BTW & OT: what's your intention? - maybe there's an alternative to fulfill your underlying requirement.
no. member and local variable can be assigned to each other.
I want to know what could be the equivalent keyword in java which could perform same function as "Static keyword in C".. I want to do recursion in java, performing same function that a static keyword in C does...
Please help..
C has two entirely different uses of the static keyword, and C++ adds a third use:
// Use 1: declare a variable or function to be local to a given module
// At global scope:
static int global_var;
static void func();
In this case, the global variable global_var and the function void func() can only be accessed inside the file in which they are declared; they cannot be accessed by any other file.
// Use 2: declare a variable inside a function with global scope
void func(void)
{
static int x;
}
In this case, the variable x is effectively a global variable, in that there is only one instance of it -- multiple calls to func() (including recursive calls) will always access the same variable.
// Use 3 (C++ only): declare a global variable with class scope
class Widget
{
public:
static int var;
};
In this case, this declares the variable Widget::var as a global variable, but its scope is different. Outside of class member functions, it has to be named as Widget::var; inside class member functions, it can be named as just var. It can also be made protected or private to limit its scope even more.
Now, what are the analogs of these 3 uses in Java?
Case 1 has no direct analog; the closest is declaring objects with package scope, which is done by omitting a public, protected, or private:
class Widget // Declare a class with package scope
{
int x; // Declare a member variable with package scope
void func() {} // Declare a member function with package scope
}
In this case, the declared objects are only accessible by classes within the same package; they are not accessible to other packages.
Case 2 also does not have an analog in Java. The closest you can get is by declaring a global variable (that is, a static class variable, since Java doesn't have true global variables in the strictest sense):
class Widget
{
private static int func_x;
public static void func()
{
// use func_x here in place of 'static int x' in the C example
}
}
Case 3 is the only case that has a direct analog in Java. In this case, the static keyword serves exactly the same purpose.
The "static" keyword in C actually serves two functions depending on where it's used. Those functions are visibility and duration (these are my terms based on quite a bit of teaching, the standard, if you're interested in that level of detail, uses different terms which I often find confuses new students, hence my reticence in using them).
When used at file level, it marks an item (variable or function) as non-exported so that a linker cannot see it. This is static as in visibility, duration is the same as the program (i.e., until the program exits). This is useful for encapsulating the item within a single compilation unit (a source file, in its simplest definition). The item is available to the whole compilation unit (assuming it's declared before use).
When used within a function, it controls duration (visibility is limited to within the function). In this case, the item is also created once and endures until the program exits. Non-static variables within a function are created and destroyed on function entry and exit.
I gather what you're after is the first type, basically a global variable since I can't immediately see much of a use for the other variant in recursion..
It can't be done since, in Java, everything must belong to a class. The workaround is to create a class holding the "globals" and either:
pass that object around so you can reference its members; or
construct a singleton item so you can access its members.
Java doesn't have global variables, so there isn't a direct equivalent. However, there's a static keyword in Java that shares the state of a field with all instances of a class, which is a good approximation to what you're describing.
I want to do recursion in java, performing same function that a static keyword in C does...
However, if you're looking to do recursion, are you sure that static variables are what you need? Any special state needed for a recursive function call is almost always passed back to itself, not maintained separately.
The concept of static in Java doesn't adhere with the concept of static in C. However, there is a static keyword in Java as well. But its more like a static in C++ then C, with some differences.
You can simulate a static class in java as follows:
/**
* Utility class: this class contains only static methods and behaves as a static class.
*/
public abstract class Utilities
{
// prevent inheritance
private Utilities()
{
}
// ... all your static methods here
public static Person convert(string) {...}
}
This class cannot be inherited (like final because although abstract it has a private constuctor), cannot be instantiated (like static because abstract) so only static methods in it can be called.