Get Inner Class Instance status - java

Use case is something similar to below code. There is a class(Inner_Demo) inside another class(Outer_Demo). Inner_class will be instantiated upon some condition in the outer class private method.
class Outer_Demo {
public Outer_Demo() {
test();
}
// private method of the outer class
private void test() {
Inner_Demo demo;
if(condition)
demo = new Inner_Demo();
}
// inner class
class Inner_Demo {
}
}
main(){
Outer_Demo outer = new Outer_Demo();
// Here I need to check is Inner class got instantiated
// Trying to print the value as below leads to error create
// field/constant Inner_Demo in Outer_Demo
System.out.println(Outer_Demo.Inner_Demo); // outer.Inner_Demo
/* Storing the created instance to Outer_Demo.Inner_Demo
is allowed */
Outer_Demo.Inner_Demo inst = outer.new Inner_Demo();
System.out.println(inst);
}
I need to test, Is inner class is Instantiated or not. I got to know that calling the inner class in above way is incorrect.
Reflection might have used if the field demo in the Outer_Demo class's method test is not local/ have class level access.
Can anybody help me to understand, Is there any way find inner class status. Any links to subject is helpful. Thanks.

You probably want to check if an object of that class has been instantiated.
For this task you should declare an Inner_Demo field in your Outer_Demo class:
class Outer_Demo {
public Outer_Demo() {
test();
}
Inner_Demo innerDemo;
...
Now, each time the object is instantiated, this field must be assigned a value:
innerDemo = new Inner_Demo();
And finally, when you want to check if the object exists, you just do it like:
if (innerDemo == null) {
//object does not exist yet and has to be instantiated
} else {
//object does exist and can be used
}

Related

How can I access local variable in main code block?

I want to access the checkWord variable in the main code block. I don't know how to access it globally. How can I access a local variable in main in Java?
This is example code blocks.
textField.setOnAction(event -> {
try{
ArrayList<String> wordList = wordListReader();
boolean checkWord = false;
for(String word:wordList){
if(word.equals(textField.getText())){
checkWord = true;
}
}
System.out.println(checkWord);
}catch (FileNotFoundException ex){
ex.printStackTrace();
}
});
// Error
System.out.println(checkWord);
Design-wise, global variables (static fields in Java) are usually not a great idea because it causes a tight coupling between classes, making it harder to make changes to the system later on.
That said, to do what you describe you would do this:
public class YourClass {
// class field
public static boolean checkWord;
// instance (object) field
private TextField textField = new TextField("Your text field");
public void yourMethod() {
textField.setOnAction(event -> {
// ...
checkWord = true;
// ...
});
System.out.println(checkWord);
}
public static void iDoNotKnowAboutInstances() {
// OK
System.out.println(checkWord);
// Compile error - cannot refer to instance field in static context
System.out.println(textField);
}
}
Meanwhile, in another class:
public class YourOtherClass {
public void yourOtherMethod() {
System.out.println(YourClass.checkWord);
}
}
A static field exists at class level. It is initialized when the class is loaded by the class loader for the first time, in this case it will be initialized as false (the default for booleans). Then, when yourMethod is executed and an event is handled, the field checkWord is set to true. It can be referred to directly from within the same class. From another class it can be referred to by prefixing the class name, as shown in YourOtherClass.
EDIT: Not that you can refer to static fields from anywhere (as long as their visibility qualifier allows it) but you only refer to instance field via an actual instance. So for example from the static method iDoNotKnowAboutInstances you cannot refer to instance field textField. You often run into this when you create a simple java application with the entry method public static void main(String[] args). If you then add instance fields to the class you will first need to create an instance of the class using YourClass instance = new YourClass() to be able to read and write those fields.

How can I access variables that exist within a class that is encapsulated within another class in Java?

I am currently working on a project which keeps track of items added into a shopping cart. My background is in C++ and I am currently learning Java. How would I access the variables which exist within a class that is encapsulated in another class? I am attempting to make a vector of RunningCart objects when a new item is added.
For example:
'''
public class ShoppingCart{
public class RunningCart{
int variable;
}
}
'''
How would I access the int variable in RunningCart?
You need an instance of the outer class in order to create an object of the inner class as follows:
// Class 1
// Helper classes
class ShoppingCart {
// Class 2
// Simple nested inner class
class RunningCart{
int variable;
// getter
public int getVariable()
{
return this.variable;
}
}
}
// Class 2
// Main class
class Main {
// Main driver method
public static void main(String[] args)
{
// Note how inner class object is created inside main()
ShoppingCart.RunningCart in = new ShoppingCart().new RunningCart();
// Calling getter method above object created
int x = in.getVariable();
}
}
You can then use the object as usual.

How to set a variable in one class and get it in another

Once I have set the "set" method in one class to set my accessor, is it possible to return(get) that variable/string in another class without first having to "set" the variable again?
public class A {
Edits edits = new Edits("hello") }
now I want to access this from class B
public class B {
Edits edits = new Edits();
String hello = edits.getHello(); }
Problem is that there is and error initializing "new Edits()" because it first has to be set.
The answer here is actually quite simple. All you do it declare a static variable and call it with the class from another class.
public class Edits {
public static String edits;
}
Set it in another class
public class A {
Edits.edits = "new value";
}
Then get it from another class
public class B {
doSomething(Edits.edits);
}

jMockit's access to a private class

I have a public class with a private class inside it:
public class Out
{
private class In
{
public String afterLogic;
public In(String parameter)
{
this.afterLogic = parameter+"!";
}
}
}
And wanted to test the In class with jMockit. Something along these lines:
#Test
public void OutInTest()
{
Out outer = new Out();
Object ob = Deencapsulation.newInnerInstance("In", outer); //LINE X
}
The problema is, in LINE X, when trying to cast ob to In, the In class is not recognized.
Any idea how to solve this?
Thanks!
The only constructor in class In takes a String argument. Therefore, you need to pass the argument value:
Object ob = Deencapsulation.newInnerInstance("In", outer, "test");
As suggested in the comment one way is to change the access modifier of the inner class from private to public.
Second way (in case you don't want to make your inner class public), you can test the public method of outer class which is actually calling the inner class methods.
Change the scope of the inner class to default then make sure that the test is in the same package.
There are two approaches, first as mentioned in other posts to change the scope to public. The second which I support is, to avoid testing private class altogether. Since the tests should be written against testable code or methods of the class and not against default behavior.

Can't access public non-static class attribute from secondary class

I have the following two classes:
public class Class1
{
public Class1 randomvariable; // Variable declared
public static void main(String[] args)
{
randomvariable = new Class1(); // Variable initialized
}
}
public class Class2
{
public static void ranMethod()
{
randomvariable.getSomething(); // I can't access the member "randomvariable" here even though it's public and it's in the same project?
}
}
I am very certain that it's a very fundamental thing I'm missing here, but what am I actually missing? The Class1 member "randomvariable" is public and so is the class and both classes are in the same project.
What do I have to do to fix this problem?
There are two problems:
Firstly, you're trying to assign a value to randomvariable from main, without there being an instance of Class1. This would be okay in an instance method, as randomvariable would be implicitly this.randomvariable - but this is a static method.
Secondly, you're trying to read the value from Class2.ranMethod, again without there being an instance of Class1 involved.
It's important that you understand what an instance variable is. It's a value associated with a particular instance of a class. So if you had a class called Person, you might have a variable called name. Now in Class2.ranMethod, you'd effectively be writing:
name.getSomething();
That makes no sense - firstly there's nothing associating this code with Person at all, and secondly it doesn't say which person is involved.
Likewise within the main method - there's no instance, so you haven't got the context.
Here's an alternative program which does work, so you can see the difference:
public class Person {
// In real code you should almost *never* have public variables
// like this. It would normally be private, and you'd expose
// a public getName() method. It might be final, too, with the value
// assigned in the constructor.
public String name;
public static void main(String[] args) {
Person x = new Person();
x.name = "Fred";
PersonPresenter.displayPerson(x);
}
}
class PersonPresenter {
// In a real system this would probably be an instance method
public static void displayPerson(Person person) {
System.out.println("I present to you: " + person.name);
}
}
As you can tell by the comments, this still isn't ideal code - but I wanted to stay fairly close to your original code.
However, this now works: main is trying to set the value of an instance variable for a particular instance, and likewise presentPerson is given a reference to an instance as a parameter, so it can find out the value of the name variable for that instance.
When you try to access randomvariable you have to specify where it lives. Since its a non-static class field, you need an instance of Class1 in order to have a randomvariable. For instance:
Class1 randomclass;
randomclass.randomvariable.getSomething();
If it were a static field instead, meaning that only one exists per class instead of one per instance, you could access it with the class name:
Class1.randomvariable.getSomething();

Categories