Communication between 2 Classes - java

I'm a newbie java programer and I'm trying to make my first project.
I need to pass a variable between 2 classes, which is going fine. The problem is that the variable has a changing value and i cannot pass the actual value. Here is an example:
public class A{
private int counter = 0;
public int getCounter(){
return counter;
}
//here some code which will increase or decrease the value of the counter variable
//lets say for the sake of the example that at this point the value of the variable is 1.
//counter = 1;
}
public class B{
public static void main(String[] args) {
A a = new A();
System.out.println(a.getCounter());// here I need the actual counter variable value which is currently: 1
}
}
My problem is that i always receive 0. How can i pass the actual value of the variable.
Any help or advice is greatly appreciated.

A a = new A();
After instantiation (above statement) you need to call the method which will increment the counter here.
Example:
a.incrementCounter();
Then below statement will get counter value.
System.out.println(a.getCounter());

lets say for the sake of the example that at this point the value of the variable is 1.
No, by the time that code is read, the value did not change. All you do inside a class-block is to define a class, the “template” for an object. At that time, no values are set though.
The a.getCounter() you use already does the correct job: It returns the current value of a’s counter variable. If it does not return 1, then obviously the value hasn’t changed yet.
public class A {
private int counter = 0;
public int getCounter() {
return counter;
}
public void increaseCounter() {
counter++;
}
}
public class B {
public static void main() {
A a = new A();
System.out.println(a.getCounter());
a.increaseCounter();
System.out.println(a.getCounter());
}
}

Make variable static so that it will be associated with class.
public class A{
private static int counter = 0;
public int getCounter(){
counter++;
return counter;
}

public static void main(String[] args) {
A a = new A();
a.setCounter(5);
System.out.println(a.getCounter());
}
public class A{
private int counter = 0;
public int getCounter(){
return counter;
}
public void setCounter(int count ){
this.counter=count;
}
}

Use constructors/setter...
public class A{
private int counter = 0;
public A(int c){
counter = c
}
public int getCounter(){
return counter;
}
public void setCounter(int c){
counter = c;
}
public void incCounter(){
counter++;
}
}
public class B{
public static void main(String[] args) {
A a = new A(123);
System.out.println(a.getCounter());
a.setCounter(456);
System.out.println(a.getCounter());
a.incCounter();
System.out.println(a.getCounter());
}
}

class A {
private int counter = 0;
public int getCounter() {
return counter;
}
public int increment() {//////////create increment Method which will increase the counter , or do any function you want
return counter++;
}
public void setCounter(int c) {///////////this method will allow you to set the counter
counter=c;
}
}
class B {
public static void main(String[] args) {
A a = new A();
a.increment();///////if you call this function will change your counter , if not , you will get it = 0
System.out.println(a.getCounter());
}
}
A a = new A();
System.out.println(a.getCounter());
The Output = 0
A a = new A();
a.increment();
System.out.println(a.getCounter());
The Output =1
a = new A();
a.setCounter(10);//////////here you set the `counter` by 10
System.out.println(a.getCounter());
The Output =10;

You have one class (Counter) which manages the counter int variable.
You would like for one or more other classes to be able to increment and/or get the counter value.
In that case, each instance of those classes should have a reference to the same instance of Counter (stored as member variable, passed to their constructor or a setter method).
class Counter {
private int counter = 0;
public int getValue() { return counter; }
public void increment() { counter++; }
public String toString() { return Integer.toString(counter); }
}
class CounterUser {
private final Counter counter;
public CounterUser(Counter counter) { this.counter = counter; }
public String toString() { return Integer.toString(counter.getValue()); }
}
class Test {
public static void main(String[] args) throws Exception {
Counter counter = new Counter();
CounterUser a = new CounterUser(counter);
CounterUser b = new CounterUser(counter);
System.out.printf("%s %s %s\n", counter, a, b);
counter.increment();
System.out.printf("%s %s %s\n", counter, a, b);
b.increment();
System.out.printf("%s %s %s\n", counter, a, b); }
}
Output:
0 0 0
1 1 1
2 2 2

You can do it from the constructor and/or create method that changes the value.
public class A
{
private int counter = 0;
public A()
{
// value is set first time you create an instance of A. (e.g when you do A a = new A();
counter = 1;
}
public int getCounter()
{
return counter;
}
public void incrementCounter()
{
counter++;
}
}
public class B
{
public static void main(String[] args)
{
A a = new A();
System.out.println(a.getCounter());// Output : 1
a.incrementCounter();
System.out.println(a.getCounter());// Output : 2
a.incrementCounter();
a.incrementCounter();
a.incrementCounter();
System.out.println(a.getCounter());// Output : 5
}
}

Related

Which overridden methods are invoked?

I am having hard time to understand the solution of the given question. I can't understand at each step which of the class' methods are invoked.
I tried to make a list for what are a,b,c declared types and actual types then try to chose overridden or overloaded methods but it is complex.
class Upper {
private int i;
private String name;
public Upper(int i) {
name = "Upper";
this.i = i;
}
public void set(Upper n) {
i = n.show();
}
public int show() {
return i;
}
}
class Middle extends Upper {
private int j;
private String name;
public Middle(int i) {
super(i + 1);
name = "Middle";
this.j = i;
}
public void set(Upper n) {
j = n.show();
}
public int show() {
return j;
}
}
class Lower extends Middle {
private int i;
private String name;
public Lower(int i) {
super(i + 1);
name = "Lower";
this.i = i;
}
public void set(Lower n) {
i = n.show();
}
public int show() {
return i;
}
}
class Tester {
public static void main(String[] args) {
Lower a = new Lower(1);
Middle b = a;
Upper c = new Middle(5);
a.set(c);
b.set(a);
c.set(b);
System.out.println(a.show());
System.out.println(b.show());
System.out.println(c.show());
}
}
What is printed as a result of System.out.println(a.show()); after the set commands? Answer is 1
What is printed as a result of System.out.println(b.show()); after the set commands? Answer is 1
What is printed as a result of System.out.println(c.show()); after the set commands? Answer is 1
I don't get why the answers of all these are 1. Also I can't tell which class' overridden or overloaded methods that "a.set(c); b.set(a); c.set(b);" uses. A detailed explanation would be really helpful.
a.set(c) uses the set-method from Middle, as that overrides the one from Upper and the (overloaded) set from Lower is not applicable because c is not an instance of Lower.
Therfore j is set to c.show() which returns c's attribute j, so it will be set to 5. Consequently the (Lower-)attribute i of a is never touched and remains at 1 when it is shown and printed.
Try to resolve the others yourself.

How can I pass a value from one constructor to another constructor?

I'm working with Java. I have a class with 2 constructors. The first constructor takes an int value as a parameter and sets an int variable as that value. The second constructor takes a string and prints it out. The idea is that when I call the first constructor from my main class, it sets an integer value. And when I call the second constructor in the main class, it takes the string representation of int variable of the first constructor and prints it out.
Here's how I made the constructors:
public class Test
{
int val;
public Test(int x)
{
val = x;
return val; //I know this won't work. So I'm looking for an alternative
}
public Test(String y)
{
System.out.println("The value is " + y);
}
}
And the main method (in a different class) looks like this:
public static void main(String [] args)
{
Test t1 = new Test(6);
Test t2 = new Test(String.valueOf(t1)); //This won't work because the first constructor can't return a value
}
So how exactly can I change the contents of the constructors so that I can pass val into the 2nd constructor?
Override toString() to return value so when you so String.valueOf(t1) it will do the toString() method;
public class Test
{
int val;
public Test(int x)
{
val = x;
}
public Test(String y)
{
System.out.println("The value is " + y);
}
#Override
public String toString()
{
return String.valueOf(val);
}
}
I think what you are probably actually trying to do is to override the toString() method of Test.
public class Test
{
int val;
public Test(int x)
{
val = x;
}
#Override
public String toString() {
return "Test:"+val;
}
}
Then you can do this:
public static void main(String [] args)
{
Test t1 = new Test(6);
String s = t1.toString();
// or this
System.out.println( t1 ); // prints "Test: 6"
}
What you're describing is actually impossible without some changes.
First and foremost, t1 and t2 are two separate instances and the values inside of them have no bearing on one another. So t1 has x=6 and t2 has x=0 (because of default values).
If you want your second constructor to have a value of x that isn't 0, then you'll need to pass that in too.
public Test(int x, String s) {
super(x);
System.out.println(x);
}
I think you don't really want two constructors. It seems like you're wanting to do something like the following:
public class Test
{
int val;
public Test(int x)
{
val = x;
}
public void printVal()
{
System.out.println("The value is " + val);
}
public static void main(String [] args)
{
Test t1 = new Test(6);
t1.printVal();
}
}
Your requirement is kinda weird. But this will work even it is kinda weird
public class Test {
private static int val;
public Test(int x) {
val = x;
}
public Test() {
System.out.println("The value is " + String.valueOf(val));
}
public static void main(String[] args) {
Test t1 = new Test(6);
Test t2 = new Test();
}
}

How to pass the correct value when calling a method?

I'm doing an assignment in which I have created an Appliance class that has a timePasses()method within it. This method re-directs some values that need to be stored within another method that is inside of another class. Here is where I am up to on this:
Appliance
public class ElectricCooker extends Cooker {
public int isOn = -1;
public int isOff = 0;
public int incrementTime;
public int varPass = -1;
#Override
public int currentState() {
if (varPass == 0) {
return isOff;
} else {
return isOn;
}
}
#Override
public void useTime(int defaultTime) {
defaultTime = 15;
incrementTime = 4;
}
#Override
public void timePasses() {
if (varPass == isOff) {
varPass = 0;
} else {
ElectricMeter.getInstance().incrementConsumed(electricityUse);
GasMeter.getInstance().incrementConsumed(gasUse);
WaterMeter.getInstance().incrementConsumed(waterUse);
}
}
ElectricCooker(int electricityUse, int gasUse, int waterUse, int timeOn) {
super(electricityUse, gasUse, waterUse, timeOn);
this.electricityUse = 5 * incrementTime;
this.gasUse = 0 * incrementTime;
this.waterUse = 0 * incrementTime;
this.timeOn = 15 * incrementTime;
}
}
Meter
public class ElectricMeter {
ElectricMeter() {
}
private static ElectricMeter instance = new ElectricMeter();
public static ElectricMeter getInstance() {
return instance;
}
public void incrementConsumed(int value) {
System.out.println(value);
}
public int incrementGenerated() {
}
public boolean canGenerate() {
}
public String getConsumed() {
}
public String getGenerated() {
}
}
Main method
public class MainCoursework {
public static void main(String[] args) {
ElectricMeter a = new ElectricMeter();
a.incrementConsumed(//what goes here?);
}
}
So the value from timePasses()has been redirected into an ElectricMeter instance but now I need to return that value to the increentConsumed() method in the meter class and I'm stuck on how to do this. Since the value of electricityConsumed is 20, the output should be 20. But instead I have to pass a parameter into a.incrementConsumed(//pass parameter here) and what ever is passed gets printed out onto the screen instead of the 20 from electrictyUse. Any help on how to do this is appreciated, thanks.
Actually, the incrementConsumed method is indeed implemented as you described:
public void incrementConsumed(int value)
{
System.out.println(value);
}
A method called incrementXXX shouldn't really output anything, should it? It should increment a variable/field:
private int electricityUsed = 0;
public void incrementConsumed(int value)
{
electricityUsed += value;
}
You should declare another method that returns electricityUsed:
public int getElectricityUsed() {
return electricityUsed;
}
Now let's fix your main method.
In your main method, you didn't even create anything that consumes electricity! How can the electric meter incrementConsumed? So remove everything from the main method and create a cooker:
// your constructor looks weird. So I passed in some random arguments..
ElectricCooker cooker = new ElectricCooker(20, 0, 0, 60);
Now call timePasses to simulate that some time passed:
cooker.timePasses();
And print the electricity used:
System.out.println(ElectricMeter.getInstance().getElectricityUsed());
you need to create an instance variable in ElectricMeter and update that value on say incrementConsumed. When you want to print that use accessor of this variable.
public class Electric {
public static void main(String[] args) {
ElectricCooker cooker = new ElectricCooker(1,2,3,4);
//opertion on cooker
//ignoring best way for singleton creation
int electricityUse = ElectricMeter.getInstance().getElectricityUse();
System.out.println(electricityUse);
}
}
class ElectricCooker // extends Cooker
{
public int isOn = -1;
public int isOff = 0;
public int incrementTime;
public int varPass = -1;
public int electricityUse = -1;
public int currentState() {
if (varPass == 0)
return isOff;
else {
return isOn;
}
}
public void useTime(int defaultTime) {
defaultTime = 15;
incrementTime = 4;
}
public void timePasses() {
if (varPass == isOff)
varPass = 0;
else {
ElectricMeter.getInstance().incrementConsumed(electricityUse);
}
}
ElectricCooker(int electricityUse, int gasUse, int waterUse, int timeOn) {
this.electricityUse = 5 * incrementTime;
}
}
class ElectricMeter {
public int electricityUse = -1;
private static ElectricMeter instance = new ElectricMeter();
public static ElectricMeter getInstance() {
return instance;
}
public void incrementConsumed(int value) {
this.electricityUse = value;
}
public int getElectricityUse() {
return electricityUse;
}
}
In ElectricMeter, some operations don't perform what they should.
ElectricMeter.getInstance().incrementConsumed(electricityUse);
should increment something but it writes only in the output:
public void incrementConsumed(int value){
System.out.println(value);
}
You should write it rather :
public void incrementConsumed(int value){
consumed+=value;
}
and add a private int consumed field in ElectricMeter class to store the actual consumed.
And your getConsumed() which has a empty implementation :
public String getConsumed(){
}
should simply return the consumed field and you should return a int value and not a String.
public int getConsumed() {
return consumed;
}
In this way, you can do :
public static void main(String[] args){
ElectricMeter.getInstance().incrementConsumed(20);
int consumed = ElectricMeter.getInstance().getConsumed();
}

How can I invoke a method and print its result?

How can I invoke a method and print its result?
public class Test {
public static int main (String args[]){
System.out.println(total);
}
public int numbers (int a, int b){
int total;
total = a + b;
return = total;
}
}
Try this instead:
public class Test {
public static void main (String args[]){
System.out.println(numbers(1, 2));
}
public static int numbers(int a, int b){
int total;
total = a + b;
return total;
}
}
Variables are scoped to the method or class in which they are defined, therefore the 'total' variable is accessible only in the 'numbers' method
public class Test {
public static void main (String args[]){
System.out.println(numbers(anumber,bnumber));
}
public static int numbers (int a, int b){
int total;
total = a + b;
return total;
}

Java 'this' keyword

I'm just beginning in programming and I'd like to make exercise from a book, but I can't. That's my problem:
public class increment {
int increment() {
return this + 1; // aka this++
}
public static void main(String[] args) {
int a = 0;
System.out.println(a.increment());
}
}
As you for sure guessed already, that it doesn't works, I want to ask you how to get outputed integer a incremented by one, but using keyword 'this'.
Regards and sorry for stupid questions.
It is strange to name a class like a method.
I guess you wanted this:
public class Counter {
int val;
public Counter (int start) {
val = start;
}
public void increment() {
val ++;
}
public String toString () {
return Integer.toString (val);
}
public static void main(String[] args) {
Counter counter = new Counter (0);
counter.increment ();
System.out.println(counter.toString ());
}
}
this is an object (the current object). You cannot "increment" it.
A way to do it is:
public class Increment {
int a = 0;
int increment() {
return a + 1;
// or: return this.a + 1;
// or: a++; return a; if you want a to be incremented from now on
}
public static void main(String[] args) {
Increment inc = new Increment();
System.out.println(inc.increment());
}
}
The this keyword in Java refers to the current scope's object instance. I don't think it's what you're looking for in this case.
In your example, a isn't an object of the class increment, it is a primitive int. In order to use the .increment() function you defined, it would have to be an object of type increment.
One option that may be what you're looking for would be the following.
public class Increment { //Java likes capitalized class names
private int myInt;
public Increment(int a) { //constructor
myInt = a;
}
public int increment() {
return ++myInt;
}
public static void main(String[] args) {
Increment a = new Increment(0);
System.out.println(a.increment());
}
}
In this example, we make a new class of type increment, which internally contains an integer. Its increment method increments that internal integer, and then returns the number.
you are using operator + for your current object (this). Operator overloading is not supported in java.
Something like this will work:
class MyInteger {
private int internal;
public MyInteger( int value ){
this.internal = value;
}
public int incerment(){
return ++this.internal;
}
}
public class Increment {
public static void main(String[] args) {
MyInteger a = new MyInteger(0);
System.out.println(a.increment());
}
}
You see, you can only implement methods for your own classes, not for existing classes, or for primitives like int.
i don't think you can use this to return the value, except if you're making a new class like this:
class Increment1
{
private int a;
public int increment2(int a)
{
this.a=a;
return this.a + 1;
}
}
public class Increment
{
static Increment1 b = new Increment1();
public static void main(String[] args)
{
int a = 0;
System.out.println(b.increment2(a));
}
}
You cannot increment a class like this.
You have to use a member variable that you can increment.
public class Test {
private int var;
public Test(int i) {
this.var = i;
}
int increment() {
this.var++;
}
}
public static void main(String[] args) {
Test t = new Test(0);
System.out.println(t.increment());
}
This refers to the current instance of the class, not a particular member.
You want to increment a property (I'm guessing of type long or int), and not the instance of your increment class (should be Increment, by the way).
Something like this would work:
public class increment {
private int innerValue = 0;
int increment() {
innerValue+=1
return innerValue; // aka this++
}
public static void main(String[] args) {
increment a = new increment()
System.out.println(a.increment());
}
}

Categories

Resources