Change and use variable by different methods - java

I've got a small question because oft a topic I didn't understand. There is one variable in a class. In the first method I want to give her a value. The second method have to change the value of this variable again. The new value of the variable is needed by a third method. I want to change and use this variable on every point of the class. Is this possible? I hope you know what I mean. Thanks for every help!

It is possible.
public class Test{
int counter;
public void initCounter(int initValue){
counter = initValue;
}
public void incCounter(){
counter++;
}
public void decCounter(){
counter--;
}
public void printCounter(){
System.out.println(counter);
}
}

If I understand you correctly, you need to send a variable into the methods so that they can modify it. As I understand, here it could be difficult becuause if you use wrapper types, they can't be modified. In such a case you can create a class that wraps your variable and can change it's values or you can use ready-to-go solutions from third party libraries.
For example, in apache-comons, they have a package:
org.apache.commons.lang3.mutable
That contains mutable wrappers for all primitive types(e.g. MutableInt).
Using your own wrapper or this classes you can modify variable inside methods and keep result saved without returning new values from these methods.

You can do , here an example :
public class PassingV {
private int i;
public int getI() {
return i;
}
public void setI(int i) {
this.i = i;
}
public PassingV firsM(PassingV a){
a.setI(1);
return a;
}
public PassingV secondM(PassingV a){
a.setI(2);
return a;
}
public PassingV thirdM(PassingV a){
a.setI(3);
return a;
}
#Override
public String toString() {
return "PassingV [i=" + i + "]";
}
public static void main(String[] args) {
// TODO Auto-generated method stub
PassingV v = new PassingV();
System.out.println(v.firsM(v).toString());
System.out.println(v.secondM(v).toString());
System.out.println(v.thirdM(v).toString());
}
}
Result:
Becarful to the types of objects you are using and becarful at the methods (accessors for example ) you define ,or not define in the class .
They can totally change the way how your object has seen from the outside .
Lets modifiy our class a bit and lets see what happen .
Now instead of int i will use a String parameter.
public class PassingV {
private String i;
public String getI() {
return i;
}
public void setI(String i) {
this.i = i;
}
public PassingV firsM(PassingV a){
a.setI("HEY ");
//substring but it return the original value :D
System.out.println(a.getI().substring(2));
return a;
}
public PassingV secondM(PassingV a){
a.setI("JOE ");
return a;
}
public PassingV thirdM(PassingV a){
a.setI("LETS GO");
return a;
}
#Override
public String toString() {
return this.getI() ;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
PassingV v = new PassingV();
System.out.println(v.firsM(v).toString());
System.out.println(v.secondM(v).toString());
System.out.println(v.thirdM(v).toString());
}
}
Result:
As you can see with String object something changed , it happen because is
Immutable object
Following this link you can read more about Immutable Objects

Related

How to call a non-void method from a void method?

Is it possible to call an int method which receives an object and returns an int value from a void method by sending a temporary object to it?
When I tried this, I got nothing; the output window appears for a millisecond and vanishes. I used this code:
class test {
int x (test ob) { return 10;}
public static void main (String args[]) { new test().x(new test()) }
}
Yes. If it just expects any object, you can pass new Object() and recieve the int value as a result.
In a word yes. The return type of the calling method has no effect on the return type of the method being called. E.g.:
public class SomeClass() {
public int increment(int i) {
return i + 1;
}
public void printFiveTheHardWay() {
System.out.println(increment(4));
}
}
Yes, you can call any method from Void method irrespective of return type of method , e.g:
Your example from comment should be like below:
class test {
int x(test ob) {
return 10;
}
public static void main(String args[]) {
System.out.println(new test().x(new test()));
}
}
More generic code for your better understanding here:
public class Foo {
private Integer value;
public Integer getValue() {
return value;
}
public void setValue(Integer value) {
this.value = value;
}
}
public class TestVoidMethodCall {
public void voidMethod() {
Foo f = new Foo();
f.setValue(100);
System.out.println(integerReturnMethod(f));
}
private Integer integerReturnMethod(Foo f) {
return f.getValue();
}
}
So, Calling method return type has no relation with called method return type.

Access methods based on constructor provided

In my program, I want to be able to access certain methods based on the constructor I initialize and nothing else. For example:
public class A {
int paramOne;
float paramTwo;
public A(int paramOne) {
// Constructor One
}
public A(float paramTwo) {
// Constructor Two
}
public void ConstructorOneMethodOnly(int paramOne) {
// Only used when Constructor One is initialized
}
public void ConstructorTwoMethodOnly(float paramTwo) {
// Only used when Constructor Two is initialized
}
}
In the code given, is there a way of achieving what I have described in the comments and in my question? If so, can you describe how to do so?
As per Sotirios Delimanolis' comment, you can not restrict the accessibility of a method based on the constructor used.
I think this logic should be divided into two class, that is the more clear implementation I can find out.
public class IntDemo {
int paramOne;
public IntDemo (int paramOne) {
...
}
public void ConstructorOneMethodOnly(int paramOne) {
...
}
}
class FloatDemo {
float paramTwo;
public FloatDemo(float paramTwo) {
...
}
public void ConstructorTwoMethodOnly(float paramTwo) {
...
}
}
public class A {
int paramOne;
float paramTwo;
int constr = 0;
public A(int paramOne) {
// Constructor One
constr = 1;
}
public A(float paramTwo) {
// Constructor Two
constr = 2;
}
}
and check constr variable before invoking methods.
Im not sure if this directly helps you but it may help you and more.
I suggest using a generic class like this.
public class A<T> {
public A(final T t) {
}
public void method(final T t) {
}
}
If you dont know how to use a generic class here is an exmaple
final A<Integer> aInteger = new A<Integer>(1);
final A<Float> aFloat = new A<Float>(5.4f);
Hope this helped!

Java Passing variables around classes

I am new to java and am trying to pass variables like in the following example from one class to another, im wondering is this possible and how i would go about it if it is.
As this code does not work as it is not static.
Main Class
public class testAll
{
public static void main(String[] args)
{
One one = new One();
Two two = new Two();
}
}
The first class:
public class One
{
public int test = 4;
public int getTest()
{
return this.test;
}
}
The second class:
public class Two
{
public void value()
{
System.out.print("Var is: " + One.getTest());
}
}
Thanks,
Naz
Lets consider this, if you want to access a variable in Class A from Class B then Class A needs to know about Class B.
public class A {
public A(B classB){
this.classB = classB;
}
public void printValue(){
System.out.println(this.classB.getTest());
}
}
Now you will need to pass an instance of ClassB to ClassA in the constructor so that Class A has a reference to ClassB when it calls printValue();
ClassB b = new ClassB();
ClassA a = new ClassA(b);
b.getTest();
a.printValue();
You have to create an instance for class One first. Try this
public void value()
{
One one_object = new One();
System.out.print("Var is: " + one_object.getTest());
}
public class Two {
private One one;
public Two(One one) {
this.one = one;
}
public void printValue() {
System.out.print("Var is: " + one.getTest());
}
}
public class Main {
public static void main(String [] args) {
One one = new One();
Two two = new Two(one);
two.printValue();
}
}
There are two way - pass a reference or pass a value:
public class One {
private int value = 0;
public One(final int value) {
this.value = value;
}
public int getValue() { return value; }
}
public class Two {
private One one = null;
public Two(final int value) {
this.one = new One(value);
}
public Two(final One one) {
this.one = one;
}
public int getValue() { return one.getValue(); }
}
When passing a reference to a One instance, the value is read from One and will only change it the value held inside the One instance changes. When passing a primitive (int, boolean ...) the value is copied and "owned" by the Two instance. Read some more about the differences of references and values to grasp the idea. It's quite simple, once you get the idea.

polymorphic call depends on variable

I have the following problem. Am trying to make a polymorphic call and the result would depend on the variable that changes value depending on the underlying class. Tried different things however it doesn't work. Please let me know what should be changed. Problem is that although c.w reads both the local variable w, which is defaulted to 0 and reads the one from appropriate class it always defaults to 0. Here is the code:
class Cycle{
private int w = 0;
public void move(){
System.out.println("Cycle moving");
}
public int wheels(Cycle c){
switch (c.w){
case 1: return 1;
case 2: return 2;
case 3: return 3;
default: return 0;
}
}
}
class Unicycle extends Cycle{
public int w = 1;
public void go(){
System.out.println("Unicycle go");
}
}
class Bicycle extends Cycle{
public int w = 2;
public void go(){
System.out.println("Bicycle go");
}
}
class Tricycle extends Cycle{
public int w = 3;
public void go(){
System.out.println("Tricycle go");
}
}
public class TestCycle {
public static void ride(Cycle c){
c.move();
int now = c.wheels(c);
System.out.println(now);
}
public static void main(String[] args){
Bicycle b = new Bicycle();
ride(b);
Unicycle u = new Unicycle();
ride(u);
Tricycle t = new Tricycle();
ride(t);
}
}
Your problem (well one of them) is that you are redefining the class variable 'w' in each of your subclasses. Define it one as a member of 'Cycle' and have each subclass set it correctly in their constructors.
class Cycle{
protected int w;
public void move(){
System.out.println("Cycle moving");
}
public int wheels(){
return w;
}
}
class Unicycle extends Cycle{
public Unicycle() {
w = 1;
}
public void go(){
System.out.println("Unicycle go");
}
}
Or you can define an abstract method called 'wheels()' in the superclass and override it in the subclasses. It's a matter of taste.
the wheels method should be more like
public int getWheelCount(){
return this.w;
}
You invoke it on the instance itself, you don't need to pass an argument. If the current instance is a Tricycle, the method will return 3, etc...
Since Cycle.w is private, it's not visible from its inheritors. This means that for example Tricycle.w it's not the "same" variable, and it's not visible in Cycle (that's why you always get 0). You have to make Cycle.w at least protected, then remove w from all subclasses, and set its value in each subclass's constructor to what you want.
It's probably not the answer you are looking for, but the following works. Please give more details on what you are trying to do.
public abstract class Cycle {
protected int nWheels;
protected String goText;
// no constructor.
public void go() {
System.out.println(goText);
}
public int wheels() {
return nWheels;
}
}
...
public class Unicycle extends Cycle {
public Unicycle() {
nWheels = 1;
goText = "Unicycle go";
}
}
Note that I made Cycle abstract because I don't want it to ever be instantiated.
EDIT:
public static int getNumberOfWheels(Cycle cycle) {
return cycle.wheels();
}
which is obviously not very useful since a simple call to cycle.wheels() would do the same as calling this function.
I'm not sure why you want to avoid constructors. Maybe you should write the exact question you are trying to answer.

Inheritance in Java

Consider the following code in Python:
class A(object):
CLASS_ATTRIBUTE = 42
def f(self):
return "CLASS_ATTRIBUTE: %d" % self.CLASS_ATTRIBUTE
class B(A):
CLASS_ATTRIBUTE = 44
Now A().f() and B().f() return "CLASS_ATTRIBUTE: 42" and "CLASS_ATTRIBUTE: 44" respectively.
How can I achieve a similar effect in Java? I want a CLASS_ATTRIBUTE field to be initialized statically and redefined in the inherited class but the f method should be only defined in the base class.
Is there a particular reason you want the attribute to be static? In Java the typical way you'd do this is to have A contain a protected variable that you then set in the constructors of the 2 classes:
public class A
{
protected int CLASS_ATTRIBUTE;
public A()
{
CLASS_ATTRIBUTE = 42;
}
public String f()
{
return "CLASS_ATTRIBUTE: " + CLASS_ATTRIBUTE;
}
}
public class B extends A
{
public B()
{
CLASS_ATTRIBUTE = 44;
}
}
Alternatively (and probably more consistent with Java design patterns) you'd declare a function that you can override to return the value instead of using a member variable.
Short answer: you cant solve it like this in Java. You'll have to solve it in another way.
In Java you can't override or "redeclare" fields in subclasses, and you can't override static methods.
It can be solved using an ugly reflection-hack (should be avoided though):
public class Main {
public static void main(String... args) {
A a = new A();
B b = new B();
System.out.println(a.f()); // Prints 42.
System.out.println(a.fReflection()); // Prints 42.
System.out.println(b.f()); // Prints 42.
System.out.println(b.fReflection()); // Prints 44.
}
}
class A {
static int CLASS_ATTRIBUTE = 42;
public int f() {
return CLASS_ATTRIBUTE;
}
public int fReflection() {
try {
return getClass().getDeclaredField("CLASS_ATTRIBUTE").getInt(null);
} catch (Exception wontHappen) {
return -1;
}
}
}
class B extends A {
// Compiles, but will not "override" A.CLASS_ATTRIBUTE.
static int CLASS_ATTRIBUTE = 44;
}
You can't do this directly with only a variable, because in Java variables cannot override (they only shadow the super classes variables).
You need to use a protected "getter" method, which can then be overridden by the subclass:
class A
{
private int attribute=42;
...
protected int getAttribute() {
return attribute;
}
}
class B
extends A
{
private int attribute=44;
...
protected int getAttribute() {
return attribute;
}
}
But note there's a special consideration to calling methods from an object's constructor, in that it allows object code to run before object construction is complete.
I'm not sure if you meant "statically" literally or not, but here's a brief example of how inheritance at it's most basic form looks in Java. Note that using a getter method to access the variable is a better idea for several reasons -- this is just an example.
public class Dog {
protected String whatISay = "Woof!";
public void speak(){
System.out.println(whatISay);
}
}
public class Poodle extends Dog {
public Poodle(){
whatISay = "Yap!";
}
}
public class Main {
public static void main(String[] args){
Poodle fluffy = new Poodle();
fluffy.speak();
Dog dog = new Dog();
dog.speak();
}
}
Yap!
Woof!
This way of doing it introduces as little intrusion as I could think of. setAttribute() could be named something like setDefaultValue() if that's clearer.
public class A
{
protected int attribute;
public A()
{
setAttribute();
}
public String f()
{
return "CLASS_ATTRIBUTE: " + attribute;
}
protected void setAttribute()
{
attribute = 42;
}
}
public class B extends A
{
#Override
protected void setAttribute()
{
attribute = 44;
}
}
public class Main
{
public static void main(String[] args)
{
A a = new A();
B b = new B();
System.out.println("A: " + a.f());
System.out.println("B: " + b.f());
}
}

Categories

Resources