How to access static block variables outside of class in java [duplicate] - java

This question already has answers here:
What is the scope of variables declared inside a static block in java?
(4 answers)
Closed 3 years ago.
I was working on some code in which I need to access the variable "hs" present in the static block of one class from another.
Note: Both the class are preset in different packages.
Code is as follow:
public class A{
static {
HashSet<String> hs = new HashSet<>();
}
}
I Googled about it but nothing found anything helpful.
Your help would be very appreciable.
EDIT: I am not allowed to make changes in this file still need to access it from the other file.
Why I need to do this cause I am doing unit testing by JUnit and there is nothing what this block is returning which I can put assertEquals() on. So the option I left with is to test the side-effects and this variable "hs" value is getting changed as a side-effect. That's why I need to access it from another file.

Declare it as public static inside the class and initialize it in static block
class A1{
public static HashSet<String> hs;
static {
hs= new HashSet<>();
}
}

Need create getter and setter for variable "hs".
Class 1:
public class Test {
public static HashSet<String> hs;
static {
hs = new HashSet<>();
hs.add("Test14");
hs.add("Test15");
hs.add("Test16");
}
public static HashSet<String> getHs() {
return hs;
}
public static void setHs(HashSet<String> hs) {
Test.hs = hs;
}
}
Class 2
If you need to use "hs" variable in without static method then:
public class Test2 {
public void test() {
Test ts = new Test();
ts.getHs();
}
}
If you need to use "hs" variable in with static method then:
public class Test2 {
public static void test() {
Test.getHs();
}
}

Related

Method Calls Not Working [duplicate]

This question already has answers here:
What is the reason behind "non-static method cannot be referenced from a static context"? [duplicate]
(13 answers)
Non-static variable cannot be referenced from a static context
(15 answers)
Closed 4 years ago.
The method calls at the end of the main method are giving me an error saying "non-static method cannot be referenced from a static context" I'm not sure what I'm doing wrong in the method call.
public static void main(String[] args)
{
ArrayList<Candidate> voteCount = new ArrayList<Candidate>();
//add objects to voteCount
printListResults(voteCount);
totalListVotes(voteCount);
printListTable(voteCount);
}
public void printListResults(ArrayList<Candidate> election)
{
//some code
}
public int totalListVotes(ArrayList<Candidate> election)
{
//some code
}
public void printListTable(ArrayList<Candidate> election)
{
//some code
}
You simply need to declare these methods as static
public static void printListResults(ArrayList<Candidate> election) {
//some code
}
public static int totalListVotes(ArrayList<Candidate> election) {
//some code
}
public static void printListTable(ArrayList<Candidate> election) {
//some code
}
An alternative approach would be to instantiate an object of your class, as pointed out in the answer from JoschJava. Either way will work. Which approach you choose is partly a matter of taste and partly depends upon the needs of your application (which is beyond the scope of this question).
The problem is that you're trying to call a class method from a static method. You need to instantiate your class:
YourClass classObj = new YourClass();
classObj.printListResults(voteCount);

Unable to retrieve value of static variable in JAVA [duplicate]

This question already has answers here:
Why doesn't the main method run?
(3 answers)
Closed 5 years ago.
I want to access a static variable set in one Java class in another class. I am using the syntax properly I guess but I am getting null everytime.
Could someone help with this?
Class 1:
public class Test {
public static List<String> dbobj;
public static void main(String args[]) {
List<String> accnos= new ArrayList<String>();
accnos.add("1");
accnos.add("2");
accnos.add("3");
dbobj=accnos;
System.out.println("dbobj"+dbobj);
}
}
Class 2 :
public class Test2 {
public void main(String args[]) {
List<String> list1= Test.dbobj;
System.out.println("List value"+list1); **//COMING AS NULL**
}
}
You have two entry points (programs) which absolutely independent of each other.
When you are calling a Test.dbobj, the main method from the Test is not executed, therefore its initialisation dbobj=accnos; is not called.
It is a bit awkward, but you could call the Test.main(args); before printing to execute that init process.
When you're within the main method of Test2, the main of Test has not been called.
The static variable dbobj has therefore its initial value, being null.
First of all you can't have 2 main functions and expect it to run both, so the better way to do this would be using a static code block in Class1 like this
static {
List<String> accnos= new ArrayList<String>();
accnos.add("1");
accnos.add("2");
accnos.add("3");
dbobj=accnos;
System.out.println("dbobj"+dbobj);
}
Try this changes in your class Test2:
Test.main(args); // added
List<String> list1= Test.dbobj;
Problem is you are using static variable dbobj from class Test without initializing that given variable. As of now, dbobj is assigned value inside Test.main(), so likewise you need to invoke that method.
There is no code executed that initialized the dbobj list, when your invoke main method in Test2 class. Therefore it points to NULL.
The easiest fix is to initialize it right when it is declared :
public static List<String> dbobj list = new ArrayList<>() {
{ add("str1"); add("str2"); }
};
The other solution is to fix Test1 class as below:
public class Test {
public static List<String> dbobj;
public static void init() {
List<String> accnos = new ArrayList<>();
accnos.add("1");
accnos.add("2");
accnos.add("3");
dbobj=accnos;
System.out.println("dbobj"+dbobj);
}
}
public class Test2 {
public void main(String args[]) {
Test.init();
List<String> list1 = Test.dbobj;
System.out.println("List first value" + list1[0]); // should be OK
}
}

How can I create object of class whose constructor is defined as private [duplicate]

This question already has answers here:
How to create objects from a class with private constructor?
(6 answers)
Closed 7 years ago.
I want to create object of Base class in another class but Base class constructor is defined as private
Here is my Code
public class Main
{
public static void main(String ... args)
{
//Base objBase = new Base();
//objBase.show();
}
}
class Base
{
private Base()
{
}
public void show()
{
System.out.println("Base Class Show() Method");
}
}
Code inside Base is still allowed to call the constructor, which means it's possible to create objects in a static method:
class Base
{
private Base()
{
}
public void show()
{
System.out.println("Base Class Show() Method");
}
public static Base createBase() {
return new Base();
}
}
and then call the method to create an object:
Base objBase = Base.createBase();
objBase.show();
You cannot create objects of classes if they have private constructors. Objects can be constructed, but only internally. That is how it is.
There are some common cases where a private constructor can be useful:
Singletons
Classes containing only static methods
Classes containing only constants
Type safe enumerations
Hoping this helps.

Can not make static reference to non static method? [duplicate]

This question already has answers here:
Static Classes In Java
(14 answers)
Closed 3 years ago.
So, in short. I have two classes.
package rpg;
public class Engine {
public void main(String args[]) {
Start.gameStart();
System.out.println(menuResult);
}
}
and
package rpg;
public class Start {
int menuResult = 3;
public int gameStart()
{
return menuResult;
}
public int getMenuResult()
{
return Start.menuResult;
}
}
It keeps throwing up the error 'Cannot make static reference to non-static method gameStart()'.
I'm sure I'm missing something simple, but can't find it.
Thanks!
You need to create instance of Start class and call gameStart() method on that instance because gameStart() is instance method not static method.
public void main(String args[]) {
new Start().gameStart();
..................
}
Only static methods can be accessed by using class name as perfix.
public int gameStart() <--- Instance method not static method
call it on instance
Start start = new Start();
start.gameStart();
So finally your classes should look like below
public static void main(String args[]) {
Start start = new Start();
start.gameStart();
System.out.println(start.getMenuResult());
}
public class Start {
private int menuResult = 3;
public int gameStart() {
return this.menuResult;//Don't know why there are two methods
}
public int getMenuResult() {
return this.menuResult;
}
}
first of all the main method should be
public static void main(String args[]) {
}
I assume you can have multiple games, and hence you should be able to start multiple instances so you should create a non static class that can be created and then actions performed against.
to answer your original question, you need to have a static variable that have static getters and setters..
public class Start {
private static int menuResult = 3;
public static int gameStart()
{
return menuResult;
}
public static int getMenuResult()
{
return Start.menuResult;
}
If you need the method to be static, just add the keyword static in the function definition. That would get rid of the error. But if you want to keep the class Start the way it is, then you should create an instance of Start in the main function and then call the method. Hope that helps!
you are trying to invoke a method on its class name. you should be creating a new object and invoke its method
public void main(String args[]) {
new Start().gameStart();
System.out.println(menuResult);
}
Start.gameStart() refers to a method which would be public static int gameStart() because Start is the class and not an instance of the object.
If you declare a method on an object, you need to apply it to instance of the object and not its class.
When to use static or instanciated methods ?
instanciated : whenever you need to apply the method to the object you're in. example : mycake.cook();
static : when the actions you do inside your method have nothing to do with an object in particular. example : Cake.throwThemAll();
mycake is an instance of a Cake, declared this way : Cake mycake = new Cake();
Cake is the class representing the object.
You should, i guess, have a read at some object oriented programmation course if you still have a doubt about objects, classes and instances.
While Other answers are Correct , that remains the Question that Why you Can't access Instance
method Directly from Class name , In Java all static (methods , fields) bind with Class Name and when Class Is Loading to the Memory (Stack) all static members are Loading to the Stack , and this time Instance Method is not visible to Class. instance Method will Load into Heap portion in the memory and can only be access by Object references .

java linked list problem

I have written some Java code with 3 simple classes where the first, Controller, has the main method and creates the instances of the other classes. Floaters is a classes that creates a linked list of Floater instances, each with a particular length and boolean value to say if they are vertical or not. My problem, as it says in the commented lines of the first class, is that both "humans" and "otters" Floaters instances are getting assigned the same values and thus have the same size....
Any suggestions on how to fix this?
Thanks in advance!
public class Controller{
private static Floaters humans;
private static Floaters otters;
public static void main(String[] args)
{
otters = new Floaters();
humans = new Floaters();
otters.addFloater(2, true);
otters.addFloater(3, true);
//this should read "2" and it does
System.out.println(otters.size());
//this should read "0" but reads "2". Why?
//How can I get it to read "0"?
System.out.println(humans.size());
}
}
import java.util.LinkedList;
public class Floaters {
private static LinkedList<Floater> llf;
Floaters()
{
llf = new LinkedList<Floater>();
}
public void addFloater(int length, boolean is_vertical)
{
Floater floater = new Floater(is_vertical, (byte)length);
llf.add(floater);
}
public int size()
{
return llf.size();
}
}
public class Floater {
int length;
boolean is_vertical;
Floater(boolean is_vertical, int length)
{
this.length = length;
this.is_vertical = is_vertical;
}
}
The llf in your Floaters-class is static. When you make variables static, they're linked to the class rather than the instance, and thus both instances of Floaters use the same list.
To correct this, simply remove the static from your declaration of the variable.
in floaters, llf should NOT be static
Because of static:
private static LinkedList<Floater> llf;
In this case static means a class field, shared among all instances of a class.
For example - mathematic functions in Java are declared as static metohods of the class java.lang.Math, matemathematical constants are static atributes of this class. So if you use sin(x), you are using always the same method.

Categories