Accessing a particular instance of class inside the same class in java - java

I have a java code with the structure that is shown below:
public class x{
public static void main(string[] args)
{
ysample1 = new y(m)
ysample2 = new y(l)
....
}
}
public class y{
private int m_m
public y(int m)
{
m_m = m
}
public void control()
{
h h1 = new h(ysample2)
}
}
At some point when I want to call method control for ysample1 I may need to access ysample2 object.How can I define instance of class y global, so I can access ysample2 inside the control method in class y?
Does anyone know how can I fix this? Thanks.

You can't do what you want to do the way you wrote it.
I think you need to ridefine "control()" method like this:
public void control(Y ysample)
{
h h1 = new h(ysample)
}
So now you need to have an "ysample" as parameter and you can do from your main
control(ysample2);
and you will have what i understood from you question. If you need something else please comment.

Related

Gauge - run #BeforeSpec in a superclass in Java

I am writing a testing framework using Gauge.
I want some initilization logic performed in one class, and the steps logic to reuse it, like this:
public class A {
protected String property = "";
#BeforeSpec
public void init(){
property = "hello";
}
}
public class B extends A {
#Step("...")
public void verifyProperty() {
assertEquals(property, "hello");
}
}
I can't seem to be able to achieve this. When performing the steps, the "property" is always null.
Placing the #BeforeSpec in class B and calling super.init() works, but I would like to avoid having this call in every test class that extends A.
Has anyone encountered and solved such an issue?
Try to use a static variable:
public class A {
public static String property = "";
#BeforeSpec
public void init(){
property = "hello";
}
}
public class B {
#Step("...")
public void verifyProperty() {
assertEquals(A.property, "hello");
}
}

Cant access methods from another class

Im calling DataComparison()
public class SteganographyGUI {
...
DataComparison dataComp;
dataComp = new DataComparison();
}
public int getLSB(){
String x = fileChooser1.getSelectedFile().getAbsolutePath();
x = x.substring(x.length() - 10, x.length() - 9);
return Integer.parseInt(x);
}
when some criteria are met. My problem is that, when I try to access getLSB by using gui.getLSB()
public class DataComparison {
public static SteganographyGUI gui;
...
public DataComparison(){
lsb = gui.getLSB();
}
public static void main(String[] args) {
gui = new SteganographyGUI();
gui.setVisible(true);
}
Error appears - Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
How can I fix this?
You are trying to call getLSB() in your DataComparison class, but you don't give it the reference of your SteganographyGUI class. So change the following line:
DataComparison dataComp;
dataComp = new DataComparison();
to:
DataComparison dataComp;
dataComp = new DataComparison(this);
And change the constructor as well:
public DataComparison(SteganographyGUI guiRef){
gui = guiRef;
}
You are doing cyclic calls in your code. Try another class just for the main and call its methods in order:
class 1: `public class SteganographyGUI {...}`
class 2: `public class DataComparison {...}
class 3:
`public class XXXX {
public static void main(String[] args) {
gui = new SteganographyGUI();
gui.setVisible(true);
}
}`
I have helped :)
When you try to initiate static "gui" variable
gui = new SteganographyGUI();
you execute SteganographyGUI class constructor which (probably) calls DataComparison class constructor
public DataComparison(){
lsb = gui.getLSB();
}
which uses static "gui" variable which is not set yet. This is the reason you got "java.lang.NullPointerException".
Yes, I know "the exception message is misleading" :)

Making a static duplicate of non-static integer

For my programming class in first year engineering I have to make a D-game in Java, with only very little knowledge of Java.
In one class I am generating a random integer via
public int rbug = (int)(Math.random() * 18);
every so many ticks. I have to use this integer in another class (in the requirements for an if-loop), and apparently it needs to be static. But when I change the variable to public int static, the value doesn't change any more.
Is there an easy way to solve this problem?
Edit: part of code added:
public int rbug = (int)(Math.random() * 18);
which is used in
public void render(Graphics g){
g.drawImage(bugs.get(rbug), (int)x, (int)y, null);
And in another class:
if(Physics.Collision(this, game.eb, i, BadBug.rbug)){
}
As error for BadBug.rbug I get the message
Cannot make a static reference to a non-static field
Using static to make things easier to access is not a very good ideal for design. You would want to make variables have a "getter" to access them from another class' instance, and possibly even a "setter". An example of this:
public class Test {
String sample = 1337;
public Test(int value) {
this.sample = value;
}
public Test(){}
public int getSample() {
return this.sample;
}
public void setSample(int setter) {
this.sample = setter;
}
}
An example of how these are used:
Test example = new Test();
System.out.println(example.getSample()); // Prints: 1337
example = new Test(-1);
System.out.println(example.getSample()); // Prints: -1
example.setSample(12345);
System.out.println(example.getSample()); // Prints: 12345
Now you might be thinking "How do I get a string from the class that made the instance variable within the class?". That's simple as well, when you construct a class, you can pass a value of the class instance itself to the constructor of the class:
public class Project {
private TestTwo example;
public void onEnable() {
this.example = new TestTwo(this);
this.example.printFromProject();
}
public int getSample() {
return 1337;
}
}
public class TestTwo {
private final Project project;
public TestTwo(Project project) {
this.project = project;
}
public void printFromProject() {
System.out.println(this.project.getSample());
}
}
This allows you to keep single instances of classes by passing around your main class instance.
To answer the question about the "static accessor", that can also be done like this:
public class Test {
public static int someGlobal = /* default value */;
}
Which allows setting and getting values through Test.someGlobal. Note however that I would still say that this is a horrible practice.
Do you want to get a new number every time that you want BadBug.rbug? Then convert it from a variable to a method.

Pass an object of another class to a singleton class

I am using this singleton class in Java and in one method, I need an object of a class which gets instantiated in Main. I am not knowing how to pass that object to this method because this code is written in the constructor of the singleton class as I need it to be executed as soon as the program starts.
Should I take out the code from the constructor and make it a standalone method which I call from Main (though I wouldn't prefer this) or is there another way?
Any ideas?
Code:
Main:
public static void main(String[] args) {
X x; // This is the object I need to pass to the singleton class
}
Singleton class:
public SomeSingletonClass {
private Queue<Y> someQueue; // Y is another class I have in my project
private SomeSingletonClass(){
someQueue.add(new Y(<some data>, <some data>, <here I need an object of X as the constructor needs it>);
}
}
I haven't added the entire code. Just a fragment where I am stuck.
You have two main options.
The first will produce howls of derision - and rightly so because it is a dark tunnel of hell.
public class X {
}
public class Y {
public Y(String s, X x) {
}
}
public class Main {
public static X x = new X();
}
public class SomeSingletonClass {
private Queue<Y> someQueue = new LinkedList<>();;
private SomeSingletonClass() {
someQueue.add(new Y("Hello", Main.x));
}
}
Here we make the X created by Main a public static so it is now, essentially, global state in parallel with your singleton.
Most readers will understand how nasty this is but it is the simplest solution and therefore often the one taken.
The second option is lazy construction.
public class BetterSingletonClass {
private BetterSingletonClass me = null;
private Queue<Y> someQueue = new LinkedList<>();
private BetterSingletonClass(X x) {
someQueue.add(new Y("Hello", x));
}
public BetterSingletonClass getInstance (X x) {
if ( me == null ) {
me = new BetterSingletonClass(x);
}
return me;
}
}
Note that I have made no effort to make this a real singleton, n'or is this thread-safe. You can search for thread safe singleton elsewhere for plenty of examples.

How to call a public method WITHIN a private attribute?

I am new to Java. So the question may seem naive... But could you please help?
Say for example, I have a class as follows:
public class Human {
private float height;
private float weight;
private float hairLength;
private HairState hairTooLong = new HairState() {
#Override
public void cut(Human paramHuman) {
Human.this.decreaseHairLength();
}
#Override
public void notCut(Human paramHuman) {
Human.this.increaseHairLength();
}
};
public float increaseHairLength () {
hairLength += 10;
}
public float decreaseHairLength () {
hairLength -= 10;
}
private static abstract interface HairState {
public abstract void cut(Human paramHuman);
public abstract void notCut(Human paramHuman);
}
}
Then I have another class as follow:
public class Demo {
public static void main(String[] args) {
Human human1 = new Huamn();
Human.HairState.cut(human1);
}
}
The statement
Human.HairState.cut(human1);
is invalid...
I intend to call the public cut() function, which belongs to hairTooLong private attribute.
How should I do it?
Since HairState is private to Human, nothing outside the Human class can even know about it.
You can create a method in Human that relays the call to its private mechanism:
public class Human {
. . .
public float cutHair() {
return hairTooLong.cut(this);
}
}
and then call that from main():
System.out.println(human1.cutHair());
Two other solutions to previous comment:
You can implement a getter which returns the hairTooLong attribute.
You can invoke the the cut() method through the reflection API (but you don't want to go there if you are beginner).
Would suggest either the solution in the previous comment, or the first option presented here.
If you are curious, you can have a look to the reflection API and an example here: How do I invoke a Java method when given the method name as a string?
In java there are four access levels, default, private, public and protected. Visibility of private is only limited to a certain one class only (even subclass cannot access). You cannot call private members in any other class. Here is a basic details of java access levels.
Access Levels
Modifier Class Package Subclass World
public Y Y Y Y
protected Y Y Y N
no modifier Y Y N N
private Y N N N
For more details check Oracle docs

Categories

Resources