I understand how to use and import outside packages, but I've never packaged my own classes before. I read the Oracle Tutorial on Creating a Package, and looked at In Java, what's the difference between public, default, protected and private in addition to several sites/SO threads on packages. For the life of me, I can't figure out why this extraordinary simple example doesn't work:
package PTest;
public class A
{
protected final int SIZE = 10;
public void printSize()
{
System.out.println(SIZE);
}
}
package PTest;
public class B
{
public static void main(String[] args)
{
System.out.println(SIZE);
hello();
}
}
I used eclipse's autopackaging feature, so I assume that the actual packing is correct. Here's an image to show that they are indeed packaged correctly:
As you can see, neither the protected SIZE or the public hello() are recognized. I've tried this outside of eclipse, also to no avail. Any help would be greatly appreciated.
SIZE is an instance field of A objects. You need to make it a static field. Even then, it'll be a member of the A class, so you have to specify A.SIZE to use it in B.
Class methods cannot access instance variables or instance methods directly—they must use an object reference.
Errors you getting are fixed here
package PTest;
public class B
{
public static void main(String[] args)
{
A MyClassA = new A();
System.out.println(MyClassA.SIZE);
MyClassA.printSize();
}
}
You can not directly access methods or fields which are not static (instance members) being in a static scope(main) other than using an object and then access or making those instance members as staic.(class members)
Related
There are to separate classes class One and class Two. Both of classes are in same package. I want to access one class data into other class how can i access variable data. My program is very lengthy ,I just want the logic of this.Thanking you in advance.
Class A.java
public class A
{
public static void main(String ar[])
{
int a=100;
}
}
Class B.java
public class B extends A
{
public static void main(String m[])
{
A obj=new A();
System.out.println("Variable of class A is :"+ obj.a);
}
}
I have done this thing to get access like i declared variable a as Static so that i can directly get access but it's not working. and when i am compiling B.java It giving me error
cannot find symbol at := System.out.println("Variable of class A is :"+ obj.a);
And
Illegal start of expression (when i am delaring variable a as public)
:-(error)public int a=100; [in class A].
Why are you using the static main method? Besides that the field a is local and not accessible outside the scope. Use this instead.
public class A
{
public int a;
public A()
{
a=100;
}
}
You don't have two true object-oriented classes above, but rather little more than two receptacles for static main methods. To combine code from two classes well, you will want to scrap that code and make OOP-compliant classes, complete with instance fields and methods. For more on this, check out the OOP section of the Java tutorials: link to OOP tutorial.
First, get rid of main() in A. You only want one main() in your application, and it's in B (since the one in A doesn't actually do anything):
public class A {
}
Now, you want A to have a class-level int value:
public class A {
private int a;
}
And you want it to have a default value of 100, yes? A constructor is a good place to do that:
public class A {
private int a;
public A() {
this.a = 100;
}
}
Now any time you do this:
A obj = new A();
you will have an object with a value. In order to access that value from outside that object, you need a "getter":
public class A {
private int a;
public A() {
this.a = 100;
}
public int get_a() {
return this.a;
}
}
Now in B (or anywhere, really), you can create an instance of A and access that value by using the "getter":
A obj=new A();
System.out.println("Variable of class A is :"+ obj.get_a());
Semantically, don't think of it as "accessing a variable from another class". Instead, think of what your objects are and what they represent. If it were a physical, real-world object which internally contained some kind of value.
When you create an instance of that object, the instance would internally have that value somewhere. From the outside of that object, it doesn't really matter how that value is internally maintained. There just needs to be some kind of interface to see the value. Which is what the "getter" method does.
One-liner answer: To access a variable outside a class, make it class-level. You have written a method-level variable that's accessible only inside that scope (method).
To elaborate:
There are to separate classes class One and class Two. Both of classes are in same package. I want to access one class data into other class how can i access variable data.
So basically you know that to by extending, you should be able to access parent class data into your subclass. For that, simply make the data in your parent class as class level.
class A {
int var = 10; //class level, but non-static, so to access you need A object
void method() {
int var = 20; //this is method local and can not be accessed outside
}
}
public class B extends A {
public static void main(String[] args) {
A aObj = new A();
System.out.println(aObj.var);
}
}
Illegal start of expression (when i am delaring variable a as public)
Its illegal. Because access modifiers like public, private etc. are applicable to class-level stuff like the first var or the main method in class B you see.
Said that:
You need to immediately go here: https://docs.oracle.com/javase/tutorial/
rather than just trying to run some classes when you lack language basics.
If I understand the meaning of each keyword correctly, public means the method is accessible by anybody(instances of the class, direct call of the method, etc), while static means that the method can only be accessed inside the class(not even the instances of the class). That said, the public keyword is no use in this situation as the method can only be used inside the class. I wrote a little program to test it out and I got no errors or warnings without putting the public key word in front of the method. Can anyone please explain why public static methods are sometimes use? (e.g. public static void main(String[] args))
Thank you in advance!
Static methods mean you do not need to instantiate the class to call the method, it does't mean you cannot call it from anywhere you want in the application.
Others have already explained the right meaning of static.
Can anyone please explain why public static methods are sometimes use?
Maybe the most famous example is the public static void main method - the standard entry point for java programs.
It is public because it needs to be called from the outside world.
It is static because it won't make sanse to start a program from an object instance.
Another good examle is a utility class, one that only holds static methods for use of other classes. It dosen't need to be instantiated (sometimes it even can't), but rather supply a bounch of "static" routines to perform, routines that does not depend on a state of an object. The output is a direct function of the input (ofcourse, it might also be subject to other global state from outside). this is actually why it is called static.
That said, the static keyword is not always used because you want to have access to some members in a class without instantiating it, but rather because it makes sense. You keep a property that is shared among all instances in one place, instead of holding copies of it in each instance.
That leads to a third common use of public static (or even public static final) - the definition of constants.
A public static method is a method that does not need an instance of the class to run and can be run from anywhere. Typically it is used for some utility function that does not use the member variables of a class and is self contained in its logic.
The code below chooses a path to store an image based on the image file name so that the many images are stored in a tree of small folders.
public static String getImagePathString(String key){
String res = key.substring(3, 4)+File.separator+
key.substring(2, 3)+File.separator+
key.substring(1, 2)+File.separator+
key.substring(0, 1);
return res;
}
It needs no other information (it could do with a safety check on the size of key)
A quick guide to some of the options...
public class Foo {
public static void doo() {
}
private static void dont() {
}
public Foo() {
doo(); // this works
dont(); // this works
Foo.doo(); // this works
Foo.dont(); // this works
this.doo(); // this works but is silly - its just Foo.doo();
this.dont(); // this works but is silly - its just Foo.dont();
}
public static void main(String[] args) {
doo(); // this works
dont(); // this works
Foo.doo(); // this works
Foo.dont(); // this works
Foo foo = new Foo();
foo.doo(); // this works but is silly - its just Foo.doo();
}
}
public class Another {
public static void main(String[] args) {
Foo.doo(); // this works
Foo.dont(); // this DOESN'T work. dont is private
doo(); // this DOESN'T work. where is doo()? I cant find it?
}
}
package penny_pinch_v2;
public class Prizes {
public static String[] prizes = { "Puzzle", "Poster", "Ball", "Game", "Doll" };
}
===========Separate Class File============
package penny_pinch_v2;
public class RunPennyPinch {
public static void main(String[] args) {
System.out.print(prizes[1]);
}
}
I'm trying to access the array 'prizes' in a different class, but it keeps saying that 'prizes' cannot be resolved. If you could tell me how to fix this that would be great.
If you are referencing a static field in another class you will need to use the name of that class to reference the field, so basically you need to change your main to this:
public class RunPennyPinch {
public static void main(String[] args) {
System.out.print(Prizes.prizes[1]);
}
}
This is called a namespacing issue. Let's pretend you could do what you're trying to do. What if you make another class called Prizes2 and put another variable in it, also named prizes? How does RunPennyPinch know which prizes variable it should be using?
Perhaps you could solve this problem by saying, "only one prizes variable is allowed to exist in any program at one time". If this were a real limitation, you would quickly run out of meaningful names to give to variables.
The solution that Java came up with is namespacing: To give a variable a context it lives in. Two variables can have the same name, but as long as they have a different context, they won't clash. The price you pay is you have to tell the program which context you want to use when you're referring to a variable.
Here's how to fix the problem:
package penny_pinch_v2;
public class Prizes {
public static String[] prizes = { "Puzzle", "Poster", "Ball", "Game", "Doll" };
}
//===========Separate Class File============
package penny_pinch_v2;
public class RunPennyPinch {
public static void main(String[] args) {
System.out.print(Prizes.prizes[1]);
}
}
There's something else you should know: If you don't explicitly state a context, it defaults to using this as the context. As an unrelated example, these two methods do the same thing and both work:
package foo;
public class Bar {
public String baz = "Puzzle";
public void impliedThis() {
System.out.println(baz);
}
public void explicitThis() {
System.out.println(this.baz);
}
}
You have to prefix the variable with the class name as the variable is not within the RunPennyPinch class.
System.out.print(Prizes.prizes[1]);
You may also have to import the Prizes class, depending on your set-up.
The variable itself doesn't exist in that context. It's a static member of another class. So you need a reference to that class:
System.out.print(Prizes.prizes[1]);
The main advantage of static is that you dont have to create an object to access that variable. You just have to call that variable by Classname.variablename (Classname is the name of class in which that variable was present)
System.out.print(Prizes.prizes[1]);
How do you define Global variables in Java ?
To define Global Variable you can make use of static Keyword
public class Example {
public static int a;
public static int b;
}
now you can access a and b from anywhere
by calling
Example.a;
Example.b;
You don't. That's by design. You shouldn't do it even if you could.
That being said you could create a set of public static members in a class named Globals.
public class Globals {
public static int globalInt = 0;
///
}
but you really shouldn't :). Seriously .. don't do it.
Another way is to create an interface like this:
public interface GlobalConstants
{
String name = "Chilly Billy";
String address = "10 Chicken head Lane";
}
Any class that needs to use them only has to implement the interface:
public class GlobalImpl implements GlobalConstants
{
public GlobalImpl()
{
System.out.println(name);
}
}
You are better off using dependency injection:
public class Globals {
public int a;
public int b;
}
public class UsesGlobals {
private final Globals globals;
public UsesGlobals(Globals globals) {
this.globals = globals;
}
}
Lots of good answers, but I want to give this example as it's considered the more proper way to access variables of a class by another class: using getters and setters.
The reason why you use getters and setters this way instead of just making the variable public is as follows. Lets say your var is going to be a global parameter that you NEVER want someone to change during the execution of your program (in the case when you are developing code with a team), something like maybe the URL for a website. In theory this could change and may be used many times in your program, so you want to use a global var to be able to update it all at once. But you do not want someone else to go in and change this var (possibly without realizing how important it is). In that case you simply do not include a setter method, and only include the getter method.
public class Global{
private static int var = 5;
public static int getVar(){
return Global.var;
}
//If you do not want to change the var ever then do not include this
public static void setVar(int var){
Global.var = var;
}
}
Truly speaking there is not a concept of "GLOBAL" in a java OO program
Nevertheless there is some truth behind your question because there will be some cases where you want to run a method at any part of the program.
For example---random() method in Phrase-O-Matic app;it is a method should be callable from anywhere of a program.
So in order to satisfy the things like Above "We need to have Global-like variables and methods"
TO DECLARE A VARIABLE AS GLOBAL.
1.Mark the variable as public static final While declaring.
TO DECLARE A METHOD AS GLOBAL.
1. Mark the method as public static While declaring.
Because I declared global variables and method as static you can call them anywhere you wish by simply with the help of following code
ClassName.X
NOTE: X can be either method name or variable name as per the requirement and ClassName is the name of the class in which you declared them.
There is no global variable in Java
Nevertheless, what we do have is a static keyword and that is all we need.
Nothing exists outside of class in Java. The static keyword represents a class variable that, contrary to instance variable, only has one copy and that transcends across all the instances of that class created, which means that its value can be changed and accessed across all instances at any point.
If you need a global variable which can be accessed beyond scopes, then this is the variable that you need, but its scope exists only where the class is, and that will be all.
Nothing should be global, except for constants.
public class MyMainClass {
public final static boolean DEBUGMODE=true;
}
Put this within your main class. In other .java files, use it through:
if(MyMainClass.DEBUGMODE) System.out.println("Some debugging info");
Make sure when you move your code off the cutting room floor and into release you remove or comment out this functionality.
If you have a workhorse method, like a randomizer, I suggest creating a "Toolbox" package! All coders should have one, then whenever you want to use it in a .java, just import it!
There is no such thing as a truly global variable in Java. Every static variable must belong to some class (like System.out), but when you have decided which class it will go in, you can refer to it from everywhere loaded by the same classloader.
Note that static variables should always be protected when updating to avoid race conditions.
Understanding the problem
I consider the qualification of global variable as a variable that could be accessed and changed anywhere in the code without caring about static/instance call or passing any reference from one class to another.
Usually if you have class A
public class A {
private int myVar;
public A(int myVar) {
this.myVar = myVar;
}
public int getMyVar() {
return myVar;
}
public void setMyVar(int mewVar) {
this.myVar = newVar;
}
}
and want to access and update myvar in a class B,
public class B{
private A a;
public void passA(A a){
this.a = a;
}
public void changeMyVar(int newVar){
a.setMyvar(newVar);
}
}
you will need to have a reference of an instance of the class A and update the value in the class B like this:
int initialValue = 2;
int newValue = 3;
A a = new A(initialValue);
B b = new B();
b.passA(a);
b.changeMyVar(newValue);
assertEquals(a.getMyVar(),newValue); // true
Solution
So my solution to this, (even if i'm not sure if it's a good practice), is to use a singleton:
public class Globals {
private static Globals globalsInstance = new Globals();
public static Globals getInstance() {
return globalsInstance;
}
private int myVar = 2;
private Globals() {
}
public int getMyVar() {
return myVar;
}
public void setMyVar(int myVar) {
this.myVar = myVar;
}
}
Now you can get the Global unique instance anywhere with:
Globals globals = Globals.getInstance();
// and read and write to myVar with the getter and setter like
int myVar = globals.getMyVar();
global.setMyVar(3);
public class GlobalClass {
public static int x = 37;
public static String s = "aaa";
}
This way you can access them with GlobalClass.x and GlobalClass.s
If you need to update global property, a simple getter/setter wrapper class can be used as global variable. A typical example is shown below.
public class GlobalHolder {
private static final GlobalHolder INSTANCE = new GlobalHolder();
private volatile int globalProperty;
public static GlobalHolder getInstance() {
return INSTANCE;
}
public int getGlobalProperty() {
return globalProperty;
}
public void setGlobalProperty(int globalProperty) {
this.globalProperty = globalProperty;
}
public static void main(String[] args) {
GlobalHolder.getInstance().setGlobalProperty(10);
System.out.println(GlobalHolder.getInstance().getGlobalProperty());
}
}
public class GlobalImpl {
public static int global = 5;
}
you can call anywhere you want:
GlobalImpl.global // 5
Creating an independent file, eg. Example.java to use the 1st solution, is just fine. You can do that also within the app, if e.g. the global variables are special to your current app, etc.:
Create a class at the beginning and declare your variables in there:
class Globals {
static int month_number;
static String month_name;
}
You can then access these variables -- using them as 'Globals.month_number', etc. -- from averywhere in your app.
very simple:
class UseOfGlobal
{
private static int a;
private static int b;
}
but it is always good to have local variables defined inside method blocks where ever possible.
As you probably guess from the answer there is no global variables in Java and the only thing you can do is to create a class with static members:
public class Global {
public static int a;
}
You can use it with Global.a elsewhere. However if you use Java 1.5 or better you can use the import static magic to make it look even more as a real global variable:
import static test.Global.*;
public class UseGlobal {
public void foo() {
int i = a;
}
}
And voilà!
Now this is far from a best practice so as you can see in the commercials: don't do this at home
There are no global variables in Java, but there are global classes with public fields. You can use static import feature of java 5 to make it look almost like global variables.
Generally Global variable (I assume you are comparing it with C,Cpp) define as public static final
like
class GlobalConstant{
public static final String CODE = "cd";
}
ENUMs are also useful in such scenario :
For Example Calendar.JANUARY)
To allow an unqualified access to static members of another class, you can also do a static import:
import static my.package.GlobalConstants;
Now, instead of print(GlobalConstants.MY_PASSWORD);
you can use the Constant directly: print(MY_PASSWORD);
See What does the "static" modifier after "import" mean? to decide about.
And consider the answer of Evan Lévesque about interfaces to carry the Constants.
// Get the access of global while retaining priveleges.
// You can access variables in one class from another, with provisions.
// The primitive must be protected or no modifier (seen in example).
// the first class
public class farm{
int eggs; // an integer to be set by constructor
fox afox; // declaration of a fox object
// the constructor inits
farm(){
eggs = 4;
afox = new fox(); // an instance of a fox object
// show count of eggs before the fox arrives
System.out.println("Count of eggs before: " + eggs);
// call class fox, afox method, pass myFarm as a reference
afox.stealEgg(this);
// show the farm class, myFarm, primitive value
System.out.println("Count of eggs after : " + eggs);
} // end constructor
public static void main(String[] args){
// instance of a farm class object
farm myFarm = new farm();
}; // end main
} // end class
// the second class
public class fox{
// theFarm is the myFarm object instance
// any public, protected, or "no modifier" variable is accessible
void stealEgg(farm theFarm){ --theFarm.eggs; }
} // end class
Going by the concept, global variables, also known as instance variable are the class level variables,i.e., they are defined inside a class but outside methods. In order to make them available completely and use them directly provide the static keyword.
So if i am writing a program for simple arithmetical operation and it requires a number pair then two instance variables are defined as such:
public class Add {
static int a;
static int b;
static int c;
public static void main(String arg[]) {
c=sum();
System.out.println("Sum is: "+c);
}
static int sum() {
a=20;
b=30;
return a+b;
}
}
Output: Sum is: 50
Moreover using static keyword prior to the instance variables enable us not to specify datatypes for same variables again and again. Just write the variable directly.
In general, Java doesn't have any global variables. Other than local variables, all variables comes under the scope of any class defined in the program.
We can have static variables to have the scope of global variables.
without static this is possible too:
class Main {
String globalVar = "Global Value";
class Class1 {
Class1() {
System.out.println("Class1: "+globalVar);
globalVar += " - changed";
} }
class Class2 {
Class2() {
System.out.println("Class2: "+globalVar);
} }
public static void main(String[] args) {
Main m = new Main();
m.mainCode();
}
void mainCode() {
Class1 o1 = new Class1();
Class2 o2 = new Class2();
}
}
/*
Output:
Class1: Global Value
Class2: Global Value - changed
*/
Object-Oriented Programming is built with the understanding that the scope of variables is closely exclusive to the class object that encapsulates those variables.
The problem with creating "global variables" is that it's not industry standard for Java. It's not industry standard because it allows multiple classes to manipulate data asyncronized, if you're running a multi-threaded application, this gets a little more complicated and dangerous in terms of thread-safety. There are various other reasons why using global variables are ineffective, but if you want to avoid that, I suggest you resort to Aspect-Oriented Programming.
Aspect-Oriented Programming negates this problem by putting the parent class in charge of the scope through something called "advices", which adds additional behavior to the code without actually modifying it. It offers solutions to cross-cutting concerns, or global variable usage.
Spring is a Java framework that utilizes AOP, and while it is traditionally used for web-applications, the core application can be used universally throughout the Java framework (8.0 included). This might be a direction you want to explore more.
To define Global Variable you can make use of static Keyword
public final class Tools {
public static int a;
public static int b;
}
now you can access a and b from anywhere by calling
Tools.a;
Tools.b;
Yoy are right...specially in J2ME...
You can avoid NullPointerException by putting inside your MidLet constructor
(proggy initialization) this line of code:
new Tools();
This ensures that Tools will be allocated before any instruction
that uses it.
That's it!
Once a class is loaded is there a way to invoke static initializers again?
public class Foo {
static {
System.out.println("bar");
}
}
Edit:
I need to invoke the static initializer because I didn't write the original class and the logic I need to invoke is implemented in the static initializer.
Put the initalisation code in a separate public static method, so you can call it from the static initializer and from elsewhere?
One circumstance in which the logic would be run more than once is if the class is loaded multiple times by different ClassLoaders. Note that in this instance, they are essentially different classes.
Generally, though, these are one-shot deals. If you want to be able to invoke the logic multiple times, do as others have suggested and put it in a static method.
I agree with Earwicker's answer. Just extract the static initialization to a separate static method.
public class Foo {
static {
Foo.initialize();
}
public static void initialize() {
System.out.println("bar");
}
}
In case you really want the exact answer to your exact question, the answer is no. It's not possible to invoke a static initializer or an instanceInitializer via reflection.
The docs clearly says :
for getDeclaredMethod(String name) :
If the name is "<init>" or "<clinit>" a NoSuchMethodException is raised.
for getDeclaredMethods() :
The class initialization method is not included in the returned array.
So no, it's not possible to invoke it, even via reflection.
you could try extending the class which contains the static code, and then put in your own static initializer. Not quite sure if it works, but :
public class OldBadLibraryClass {
static {
System.out.println("oldBadLibrary static init");
}
}
//next file
public class MyBetterClass extends OldBadLibraryClass {
static {
System.out.println("MyBetterClass init");
}
}
public class Test {
public static void main(String[] args) {
new MyBetterClass();
}
}
see if the above prints in the order you expect. On my machine, it worked.
Though this is totally a hack, and is quite brittle. It would really be much better to modify the old class to have an init() method that can be overridden.
Here https://stackoverflow.com/a/19302726/2300018 is a post from me, where I re-load a utility class to re-run the static initializer for unit testing.