I have a program which requires the use of the same objects accross multiple different methods.. how do I make the scope of the class-type variable (object) so that it fits in all the methods in the primary class?
@ganeshie8
language: Java
I believe what I'm looking for is a 'singleton pattern' to do this.. I'll try that.
There are two ways to this and it depends on the context of what you are doing. 1. Static variables: ``` public MyClass { private static Scanner input; public static void main(String[] args) { input = new Scanner(System.in); method1(); } public static void method1() { if (input.nextLine().equals("1+1=3")) System.out.println(method2()); } private static boolean method2() { return AnotherClass.variable1; } } class AnotherClass { public static boolean variable1 = false; } ``` Input 1+1=3 in StdIn and the program will return false. 2. Instance varables: ``` public MyClass { public static void main(String[] args) { AnotherClass anCl = new AnotherClass(); anCl.evaluateInput(); anCl.count(); anCl.count(); anCl.count(); anCl.count(); System.out.println(anCl.count); } } class AnotherClass { private static Scanner input; public int counter = 0; AnotherClass() { input = new Scanner(System.in); ++counter; } public void evaluateInput() { if (input.nextLine().equals("1+1=3")) System.out.println("false"); } private void count() { ++counter; } } ``` Will print "false 5" if StdIn is "1+1=3" otherwise it'll just print "5". All this might seem confusing at first but I strongly recommend you to read up on instance vs. static variables/metods/context, and also a bit on access modifiers. You'll need to understand this to properly implement what you are looking for. In the meantime for a quick and dirt soulution you can just use the "private static" one in the static example.
* ``` System.out.println(anCl.counter); ```
Thank you a whole lot lyrae! This most certainly is a 'quick fix', I'm looking to finish my first text-based game, which I plan will be thoroughly entertaining :). I look forward to learning about those keywords more in depth. cheers
Join our real-time social learning platform and learn together with your friends!