Sharing same variable across classes - java

I am trying to create a system where one variable can be changed from different classes. The code that I am trying to create is this:
Server:
public class Server(){
public int number = 0;
}
Client:
public class Client extends Server(){
public void run (){
number++;
}
}
Business:
public class Business(){
public void run(){
number++;
}
}
I have another class which instantiates the Client and Business class. The result when I print out the number from a different class is still 0, I am trying to understand the concept of how could the same variable be manipulated from different classes. Do I have to even extend classes, is there some other approach?

This is because in your case the number variable is an instance variable, which means that each instance has its own copy of this primitive.
You will get more understanding by reading about instance and class variables.
So if you will make your number variable as a class variable by adding static keyword - your application should start to work (provided that you fix compilation errors).
I also recommend you to read about AtomicInteger which would be more safety in multithreading.
P.S. After rewriting of your code I get following code:
class Test {
public static void main(String... args) {
Client c = new Client();
c.run();
Business s = new Business();
s.run();
Server ss = new Server();
System.out.println(ss.number);
}
}
class Server {
public static int number = 0;
}
class Client extends Server {
public void run() {
number++;
}
}
class Business extends Server {
public void run() {
number++;
}
}

You have a simple methods to achieve this.
1) Use number as a Static variable and access the method. ( Use Synchronized method to increment the value for multi threaded application)
2) Use AtomicInteger to increment. ( No need Synchronization)
(https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicInteger.html)
If you need more explanation please let me know.

You can use the solution above mentioned by #Mikita Berazouski.
Or you can use Static Method. Like this you do not need to extend Server.
Static methods are the methods in Java that can be called without creating an object of class. They are referenced by the class name itself or reference to the Object of that class.
Your solution will be like this :
public class Test {
public static void main(String... args) {
Client c = new Client();
c.run();
Business s = new Business();
s.run();
System.out.println(Server.number);
}
}
class Server {
public static int number = 0;
public static void run ()
{
number ++;
}
}
class Client {
public void run() {
Server.run();
}
}
class Business {
public void run() {
Server.run();
}
}
try the code above here and you will check the result.
Another possible solution since you declare number as static in class Server is to write code like this, this allow you to do diff thing in the void run of each class :
public class Test {
public static void main(String... args) {
Client c = new Client();
c.run();
Business s = new Business();
s.run();
System.out.println(Server.number);
}
}
class Server {
public static int number = 0;
}
class Client {
public void run() {
Server.number ++;
}
}
class Business {
public void run() {
Server.number ++;
}
}

Related

Getting error referencing an object from a different class in Java

I've been working with Java in the last few days, so I am very new to programming in Java.
I am currently going through a bunch of online tutorials and trying to learn as much as possible. In one tutorial, we are getting to learn how to use objects correctly. The person who made the video uses an online compiler, while i follow along in eclipse.
In my code I have two classes
The first is called objectDesign
public class objectDesign {
public static void main(String[] args) {
System.out.println("We are creating a new PEZ dispenser");
PezDispenser dispenser = new PezDispenser();
System.out.printf("The dispenser is %s", dispenser.characterName);
}
}
The second is called PezDispenser
public class PezDispenser {
public String characterName;
public static void main(String[] args) {
String characterName="Mario";
}
}
The goal is to define the character who the object is supposed to be. I used a string called characterName and set it to Mario which i would like to return when I run the objectDesign class. I made the string public thinking that would enable the objectDesign class to find the information. However the console returns "The dispenser is null" every time I run the code.
What am I doing wrong?
You can use below code
package com.stackoverflow;
public class ObjectDesign {
public static void main(String[] args) {
System.out.println("We are creating a new PEZ dispenser");
PezDispenser dispenser = new PezDispenser("Mario");
System.out.printf("The dispenser is %s", dispenser.characterName);
}
}
package com.stackoverflow;
public class PezDispenser {
public String characterName;
public PezDispenser(String characterName) {
// TODO Auto-generated constructor stub
this.characterName=characterName;
}
}
here are few ways of doing this
Option 1:
public class PezDispenser {
public String characterName = "Mario";
public static void main(String[] args) {
String characterName="Mario"; // This statement is never executed because this class's main was never invoked.
}
}
Option 2:
public class PezDispenser {
public String characterName;
public static void main(String[] args) {
String characterName="Mario";
}
}
public class objectDesign {
public static void main(String[] args) {
System.out.println("We are creating a new PEZ dispenser");
PezDispenser dispenser = new PezDispenser();
dispenser.characterName = "Mario";
System.out.printf("The dispenser is %s", dispenser.characterName);
}
}
These are not the best options, but going by what you are trying to achieve these should serve the purpose.

Passing parameter to anonymous class in Java

i'm trying to write anonymous inner class
interface Face{
void seeThis(String what);
}
class Eyes {
public void show(Face f){}
}
public class Seen {
public void test() {
Eyes e = new Eyes();
e.show(new Face() {
#Override
public void seeThis(String what){
System.out.print(what);
}
});
public static void main(String[] args) {
Seen s = new Seen();
s.test();
}
}
How to call seeThis() and how to pass parameter to it?
Method seeThis() belongs to Face class, which instance is anonymous and thus cannot be reached without storing reference to it. If you want to store a reference, you can do this in the following way:
public class Seen {
public Face face;
....
this.face = new Face() { ... };
e.show(this.face);
And then,
Seen s = new Seen();
s.face.seeThis();
Now, regarding passing the parameter. You have two options - declare parameter outside of anonymous class and make it final in order to be reachable by this anonymous class, or replace anonymous class with normal one and pass the parameter to its constructor:
Approach one:
final int parameter = 5;
...(new Face() {
#Override
public void seeThis() {
System.out.println(parameter);
}
});
Approach two:
public class MyFace implements Face() {
private final int parameter;
public MyFace(int parameter) {
this.parameter = parameter;
}
#Override
public void seeThis() {
System.out.println(parameter);
}
}
Then,
...
e.show(new MyFace(10));

Trouble with constructor in the Processing Java environment

I am new to Java and working in the Processing environment. I want to create a class that has a few objects in it, but I am getting an error when I try to construct those classes' object.
The bzaVertex is supposed to be an object within the bza object, but when I seemingly try to construct it, Processing says "The constructor sketch.BzaVertext(int) is undefined." I don't understand how Bza is getting its constructor called properly, but not the child object -- I seem to be calling them the same way?
I have this code all in the main class. I'm using Processing 2.0b7. What am I doing wrong?
Bza bza;
void setup() {
bza = new Bza();
}
public class BzaVertex {
public void BzaVertex(int d) {
}
}
public class Bza {
BzaVertex v1;
public void Bza() {
v1 = new BzaVertex(4);
}
}
constructors do not have a return type so you need to to remove the void from both of them
class BzaVertex {
public BzaVertex(int d) {
}
}
class Bza {
BzaVertex v1;
public Bza() {
v1 = new BzaVertex(4);
}
}
public class Main
{
public static void main(String[] args)
{
Bza bza;
bza = new Bza();
}
}
that should solve the error

Increasing the scope of object from local scope

I want to create an object using a method but I want it (object+reference) to live even after the method ends. Example of code:
public class start{
public static void main (String [] Args){
public void createObject(){
object1 createdObject = new object1();
}
createObject();
createdObject.doSomething();
}
}
public class object1{
//code for object 1
}
So my main question is: how to create object using method and let it live even after method ends. The problem is that reference createdObject is popped of stack after method ends and therefore I can't use it anymore. Is it even possible to create object for further use this way?
public class start{
public static void main (String [] Args){
//class level scope
object1 createdObject = null;
private void createObject(){
createdObject = new object1();
}
}
public class object1{
//code for object 1
}
NOTE: I have not following naming conventions. But please follow them in actual code
UPDATE: Proper code check it out
public class Main {
public static void main(String[] args) {
new MyClass().doSomething();
}
}
class MyClass{
Object obj ;
public void doSomething(){
createObject();
}
private void createObject(){
obj = new Object();
System.out.println("Created MyClass instance");
}
}
Your method should return object1 instead of void and you have to add the following line at the end of the method:
return createdObject;

what is the best way to test whether java code is running in an applet or not?

I want somewhere down in the java code:
if(inAnApplet()) {
initForApplet();
} else {
initForApp();
}
public class MyApplet extends JApplet {
boolean isapplet = true;
public MyApplet() {
this(true);
}
public MyApplet(boolean isapplet) {
this.isapplet = isapplet;
}
public static final void main(String[] argv) {
// is an app
new MyApplet(false);
}
}
Assuming that somewhere you have a view which extends JApplet and it is accessible from the code where you have the if, you can write:
if(mainView instanceof JApplet) {
initForApplet();
} else {
initForApp();
}
Like jli said, maybe you could create initialise a public (static) boolean isApplet = true somewhere accessible in the class in which you would like to do the check and set that to false in your main method, as public static void main(String[] args) is not called in an Applet.
This way your check would simply start if(isApplet)!
HTH

Categories

Resources