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

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.

Related

How can I add customer methods to ENUM to get string value of the value I am using (if needed) [duplicate]

I have a enum defined like this and I would like to be able to obtain the strings for the individual statuses. How should I write such a method?
I can get the int values of the statuses but would like the option of getting the string values from the ints as well.
public enum Status {
PAUSE(0),
START(1),
STOP(2);
private final int value;
private Status(int value) {
this.value = value
}
public int getValue() {
return value;
}
}
if status is of type Status enum, status.name() will give you its defined name.
You can use values() method:
For instance Status.values()[0] will return PAUSE in your case, if you print it, toString() will be called and "PAUSE" will be printed.
Use default method name() as given bellows
public enum Category {
ONE("one"),
TWO ("two"),
THREE("three");
private final String name;
Category(String s) {
name = s;
}
}
public class Main {
public static void main(String[] args) throws Exception {
System.out.println(Category.ONE.name());
}
}
You can add this method to your Status enum:
public static String getStringValueFromInt(int i) {
for (Status status : Status.values()) {
if (status.getValue() == i) {
return status.toString();
}
}
// throw an IllegalArgumentException or return null
throw new IllegalArgumentException("the given number doesn't match any Status.");
}
public static void main(String[] args) {
System.out.println(Status.getStringValueFromInt(1)); // OUTPUT: START
}
I believe enum have a .name() in its API, pretty simple to use like this example:
private int security;
public String security(){ return Security.values()[security].name(); }
public void setSecurity(int security){ this.security = security; }
private enum Security {
low,
high
}
With this you can simply call
yourObject.security()
and it returns high/low as String, in this example
You can use custom values() method:
public enum SortType
{
Scored, Lasted;
public int value(){
return this == Lasted ? 1:0;
}
}

How to write a shared code between two classes

In the below code, in class_1 and class_2 both extends from AbstractClass. I am trying when I call:
c1.setValid(5)
The following two lines, returns 5 as well:
System.out.println(c1.getValid());
System.out.println(c2.getValid());
pleas let me know how can I modify the Super class to achieve that.
main:
public class Main {
public static void main (String[] args) {
Class_1 c1 = new Class_1();
Class_2 c2 = new Class_2();
System.out.println(c1.getValid());
System.out.println(c2.getValid());
c1.setValid(5);
System.out.println(c1.getValid());
System.out.println(c2.getValid());
}
}
class_1
public class Class_1 extends AbstractClass {
public Class_1() {
// TODO Auto-generated constructor stub
}
public void setValid(int v) {
SetValid(v);
}
public int getValid() {
return GetValid();
}
}
class_2.:
public class Class_2 extends AbstractClass {
public Class_2() {
// TODO Auto-generated constructor stub
}
public void setValid(int v) {
SetValid(v);
}
public int getValid() {
return GetValid();
}
}
code:
public abstract class AbstractClass {
public int isValid = -1;
public void SetValid(int value) {
this.isValid = value;
}
public int GetValid() {
return this.isValid;
}
You can delete setValid and getValid from Class 1 and 2
and use the parent's function SetValid and GetValid
If that is your question.
If your goal is to have all instances of your class to always have the same value, then you can simply use the static keyword.
public abstract class AbstractClass {
public static int isValid = -1;
...
}
When static is used for a global variable, you're essentially declaring that this global variable will be shared by every instance of this class, including it's children.
Therefore, updating isValid with a new value in Class_1 will cause Class_2 to have the same value that Class_1 updated.

Change and use variable by different methods

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

Changing the return value of a method

This code is asserting that a created class' method which returns a certain value returns the right number. I have to insert my own code where [???] is currently.
class A { int m() { return 1; } }
public class Exercise {
public static void main(String [] arg) {
A a = [???];
assert a.m() == 2;
}
}
How do I change the return value of the m method of the class A so it returns 2, not 1?
I suppose you need something like this:
A a = new A() {
#Override
int m() {return 2;}
};

Getting String value from enum in Java

I have a enum defined like this and I would like to be able to obtain the strings for the individual statuses. How should I write such a method?
I can get the int values of the statuses but would like the option of getting the string values from the ints as well.
public enum Status {
PAUSE(0),
START(1),
STOP(2);
private final int value;
private Status(int value) {
this.value = value
}
public int getValue() {
return value;
}
}
if status is of type Status enum, status.name() will give you its defined name.
You can use values() method:
For instance Status.values()[0] will return PAUSE in your case, if you print it, toString() will be called and "PAUSE" will be printed.
Use default method name() as given bellows
public enum Category {
ONE("one"),
TWO ("two"),
THREE("three");
private final String name;
Category(String s) {
name = s;
}
}
public class Main {
public static void main(String[] args) throws Exception {
System.out.println(Category.ONE.name());
}
}
You can add this method to your Status enum:
public static String getStringValueFromInt(int i) {
for (Status status : Status.values()) {
if (status.getValue() == i) {
return status.toString();
}
}
// throw an IllegalArgumentException or return null
throw new IllegalArgumentException("the given number doesn't match any Status.");
}
public static void main(String[] args) {
System.out.println(Status.getStringValueFromInt(1)); // OUTPUT: START
}
I believe enum have a .name() in its API, pretty simple to use like this example:
private int security;
public String security(){ return Security.values()[security].name(); }
public void setSecurity(int security){ this.security = security; }
private enum Security {
low,
high
}
With this you can simply call
yourObject.security()
and it returns high/low as String, in this example
You can use custom values() method:
public enum SortType
{
Scored, Lasted;
public int value(){
return this == Lasted ? 1:0;
}
}

Categories

Resources