I took this example from a tutorial. Given below class was created to restrict multiple objects creation in same class.
package interview;
public class Test1 {
private static Test1 tstObj = null;
private Test1() {
}
public static Test1 createObject() {
if (tstObj == null) {
tstObj = new Test1();
}
return tstObj;
}
public void display() {
System.out.println("Singleton class Example");
}
}
But when I tried to create multiple objects from the same class in another class in same package I got succeeded.
package interview;
public class Test {
public static void main(String[] args) {
Test1 myobject = Test1.createObject();
myobject.display();
Test1 myobject1 = Test1.createObject();
myobject1.display();
Test1 myobject2 = Test1.createObject();
myobject2.display();
}
}
How come this happened or am I not understanding the consepnt of multiple object creation ???
Please help.
Your second and third calls to Test1#createObject() are not actually creating another instance of the singleton class, q.v. the code for the constructor:
public static Test1 createObject() {
// create a single instance the first time around
if (tstObj == null) {
tstObj = new Test1();
}
// otherwise return the instance which already exists
return tstObj;
}
Note carefully that the if statement only instantiates the singleton if the reference be null, which ideally should only happen the very first time your app calls createObject().
Related
I'm trying to view the elements of an ArrayList in a different class but it shows that there is nothing. In the other class, you can see the element in the ArrayList though.
Here are the codes.
First class
import java.util.ArrayList;
public class Test {
ArrayList<String> inventory = new ArrayList<String>();
public void test() {
inventory.add("item");
}
public void check() {
System.out.println(inventory);
}
}
Second class
import java.util.ArrayList;
public class Test2 {
Test testObj = new Test();
public void test2() {
System.out.println(testObj.inventory);
}
}
Main class
public class Main {
public static void main(String[] args) {
Test testObj = new Test();
Test2 test2Obj = new Test2();
testObj.test();
testObj.check();
test2Obj.test2();
}
}
Output
[item]
[]
In java Class level variables are Object associated until unless they are not declared static.
By means of Object associated is that when a object is initialized with new keyword in Java all Object will be having it's own memory and own class variables.
In your case inside main method when you create a Object of Test class and when you create a another test class object inside Test2 class, both will be totally independent of each other. And both will be having their own memory and own variables.
If you want that to get the updates of inventory variables from first object to be available in another object you need to declare it as static and should be initialized inside static block. Static variables are shared across all objects of class. As below:
static ArrayList<String> inventory;
static {
inventory = new ArrayList<String>();
}
In your main method, you call the method that handles adding operation yet you do not call any add methods in the second class and in your main method.
testObj.test();
testObj.check();
This one shows that you add an item into the arraylist and show it. But in the second class you do not add anything but calling it. Therefore there is no way to show any element from that method. What has should be done is that you just need to call the adding method inside of the second class and then try to use the display method.
You didn't call test() method in Test2 class.
To make it work change the Test2 class as follows.
import java.util.ArrayList;
public class Test2 {
Test testObj = new Test();
public void test2() {
testObj.test();
System.out.println(testObj.inventory);
}
}
I've been flustered over trying to figure out how to call a method from an instance of a class from a different class. For example:
public class Test1
{
public static void makeSomeInst()
{
Test1 inst = new Test1();
inst.fireTest();
}
public void fireTest()
{
System.out.println("fireTest");
}
public Test1()
{
}
}
no problem with understanding the above, but what If I want to do something to inst from a class called Test2, how would I do that? The below example doesn't work:
public class Test2
{
public static void main(String[] args)
{
Test1.makeSomeInst();
inst.fireTest();
}
}
And just to be extra clear, I get that I can call static references without instantiating, but I just want to know, in this specific case
What is the syntax to reference the test1 object called inst from the Test2 class?
what If I want to do something to inst from a class called Test2, how would I do that?
First of all you have to teach the Test2 class what Test1 is.
public class Test2
{
public doSomething()
{
inst.fireTest();
}
public Test2(Test1 inst)
{
this.inst = inst;
}
private Test1 inst;
}
Then teach the inst2 object what inst is.
public class Test1
{
public static void main(String[] args)
{
Test1 inst = new Test1();
Test2 inst2 = new Test2(inst); // <- new code
inst2.doSomething(); // <- new code
}
public void fireTest()
{
System.out.println("fireTest");
}
public Test1()
{
}
}
You only need one main to start the show. Flow of control can still pass through other objects. But at this point I wouldn't call these independent tests. I only used that name to match your code.
What you're looking at is something called reference passing. The fancy term for it is Pure Dependency Injection*. The basic pattern is to build an object graph in main. Once that's built call one method on one object to start the whole thing ticking.
In main you build every object that will live as long as your program does. What you wont find built here are objects that are born later, such as timestamps. A good rule of thumb is to build each of these long lived objects before doing any real work. Since they know about each other they can pass flow of control back and forth between them. There's a lot of power there and if not used well it can get confusing. Look into Architectural Patterns to help keep that simple.
The principle followed here is to separate use from construction. Following that allows you to easily change your mind about what talks to what in one place. It's nice when a design change doesn't force you to rewrite everything.
You have to save your instance somewhere.
If Test1 should be a singleton, you can do:
public class Test1
{
private static Test1 instance;
public static Test1 getInstance()
{
return instance == null ? instance = new Test1() : instance;
}
public static void main(String[] args)
{
Test1 inst = getInstance();
inst.fireTest();
}
public void fireTest()
{
System.out.println("fireTest");
}
}
and in Test2:
public class Test2
{
public static void main(String[] args)
{
Test1.getInstance().fireTest();
}
}
//Edit
As I just learned from #Thomas S. comment, singletons are not a good solution.
See #candied_orange's answer for a better implementation.
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");
}
}
First of all, I am new in Java and I don't know yet a lot about it I just came up with this new idea.
Let's say I have a method methodCondition(String,String,String) where I want to be put in any class.
The scenario of code is below:
Where everything is started
public class MainClass{
public static void main(String... args)
{
//Whe everything started, call StartFunction from proccesshelper class to Start a Thread.
ProccessHelper phelper = new ProccessHelper();
phelper.StartFunction();
}
public void methodCondition(String data1, String data2, String data3){
//Do something about the data when this method is fire from Thread
}
}
A class where functions can call
public class ProccessHelper{
//Some function here
public void StartFunction(){
MyThread mythread = new MyThread();
Thread t = new Thread(mythread);
t.start();
}
//Some function here
}
A thread where methodCondition(String,String,String) is able to fire
public class MyThread implements Runnable {
volatile boolean StopThread = false;
public MyThread(){}
public void Stop(boolean stopThread){
this.StopThread = stopThread;
}
public void run(){
if(dontLoop){
while(true){
if(condition = true){
/*
* if the condition here is true then call "eventMethod" from any unkown class.
*/
methodCondition(String data1, String data2, String data3);
}
}
}
}
}
So my question is, it is possible that the MyThread can call methodCondition(String,String,String) in any class where it is register just like listening and waiting to be call?
Just like what I said, I don't know yet a lot in Java, I don't know what kind of function is this or if this is possible I just came up with this Idea.
So if anyone can tell,explain or give a link for any reference about what I am trying to achieve that will be very appreciated. I am also open for any clarification. Thank you!
If you want to call methodCondition from any class you must declare like static method. The statics methods can be called without instantiate the container class.
public static void methodCondition(String data1, String data2, String data3){
//Do something about the data when this method is fire from Thread
}
After declare like static you can call it directly:
MainClass.methodCondition(...);
All classes must be in the same package, or import MainClass where you want to use methodCondition.
If you don't know the class name, better put it in an interface and accept that interface as an input to your thread and call it from interface reference. This method could be inner to thread or can be a normal interface. Below is the example with inner interface.
Thread Code:
class MyThread implements Runnable {
interface interfaceName {
void methodName(String data1, String data2, String data3);
}
interfaceName interfaceReference = null;
// Other members declaration
private MyThread(interfaceName obj) {
interfaceReference = obj;
}
public static MyThread getInstance(interfaceName obj) {
if (obj == null) {
throw new NullPointerException();
}
return new MyThread(obj);
}
public void run() {
// Do your stuff
interfaceReference.methodName("", "", "");
// Do your stuff
}
}
Other Classes Example:
public class Temp implements MyThread.interfaceName {
public static void main(String[] args) {
Temp t = new Temp();
MyThread mt = MyThread.getInstance(t);
}
public void methodName(String data1, String data2, String data3) {
// Do your stuff
}
}
I am happy to found it and it is called Invoking Methods. And to be clear, what I really want is to find for specific name of method from unknown class and if it is exist then call it to fire specific task.
in Addition, the code I've done is below and it's work:
Class c=Class.forName("MainActivity");
Method m=c.getMethod("methodCondition", String.class, String.class, String.class); //The method has 3 String paramaters so I have to intialize it otherwise it will produce an error that the method was not found.
Object t = c.newInstance();
m.invoke(t,"Hello Word!", "this is", "to Invoke Method"); //Now invoke the method with the value or paramaters.
I am starting in java, so please bear with me if this sounds stupid.
I am trying the below code:
First.java
class First {
public static void main( String[] args ) {
First f = new First();
f.print();
}
private void print() {
System.out.println( "Hello, World!" );
}
}
Within the main function, i re-instantiate the same class as i need to call a non-static method from within the static main method.
While this works, i am wondering is this a good way to do it? And how many instances of f are created.
How can i make sure f would be a singleton.
Thanks
About the first question: Only one instance of the class First is created.
About the second question:
The singleton pattern involves using a private constructor and a factory method. You cannot create a new instance of First without using the getInstance factory method, and all calls to getInstance will return the same instance.
class First {
private static First instance = null;
private First() {}
public static First getInstance() {
if (instance == null) {
instance = new First();
}
return instance;
}
}
class Second {
public static void main(String[] args) {
First f = First.getInstance(); //Always the same instance of First.
}
}