How to call two methods in same class? - java

How can I call two methods from the same class over one object? I mean I try to write a class and its methods to run above code:
volume = Calculate.do_calc().get_volume(a);
I am creating Calculate class and two methods of it. do_calc() and get_volume(a). How should I write this class to run that code.

Unless do_calc() returns the class in where de function get_volume() is located this should never be done.

Here is a little sample for you.
public class ChainTest {
public static void main(String[] args) {
System.out.println(new ChainTest().do_calc().get_volume(1));
}
public ChainTest do_calc() {
// do something;
return ChainTest.this;
}
public int get_volume(int a) {
return a;
}
}

You don't need to write the code in one line. You can call same object methods in different lines.
Calculator calculator = new Calculator();
calculator.do_calc();
calculator.get_volume(a);
In case, if you want static methods
Calculator.do_calc();
Calculator.get_volume(a);

Case 1 If do_calc is static
public class Calculator {
public static void main(String[] args) {
System.out.println(Calculator.do_calc().get_volume(1));
}
public static Calculator do_calc() {
Calculator calculator = new Calculator();
// do something;
return calculator;
}
public float get_volume(int a) {
return a;
}
}
Case 2 : If do_calc is not static
public class Calculator {
public static void main(String[] args) {
System.out.println(new Calculator().do_calc().get_volume(1));
}
public Calculator do_calc() {
Calculator calculator = new Calculator();
// do something;
return calculator;
}
public float get_volume(int a) {
return a;
}
}
Case 3 : If both have return type float as you mentioned in comment
public class Calculator {
public static void main(String[] args) {
Calculator calculator = new Calculator();
calculator.do_calc();
System.out.println(calculator.get_volume(1));
}
public float do_calc() {
// do something;
return 1f; // return your result
}
public float get_volume(int a) {
// do something;
return a;
}
}

You must return this; at the end of each method of your class if they are not static. If the methods are static, do it like this:
public class Calculation {
public static Calculation do_calc () {
//do your calculation
return null;
}
public static Calculation get_volume(int x) {
//do your calculation
return null;
}
}
Then you can write:
Calculation.do_calc().get_volume(1);
No problem in returning null, as the methods are static and not related to a specific instance of the class. If you don't like it, then return new Calculation();
[Edit]
The first method should return a real object if you need to pass its result to the second method:
public class Calculation {
int result;
public static Calculation do_calc () {
//do your calculation
Calculation c=new Calculation();
c.result = theResultOfTheCalculation;
return c;
}
public void get_volume(int x) {
//do your calculation for example:
System.out.println(result + x);
}
}

Related

How do I execute the function public method declared inside a class which is in turn inside a private method?

So, I want to execute the sum() of the following block of code:
import java.lang.reflect.Method;
public class LocalOuterClass { // start of outer
private int x = 10;
private Object run() { //start of inner
class LocalInnerClass {
private int y = 20;
public void sum() {
System.out.println(x+y);
}
} //end of inner
LocalInnerClass lc = new LocalInnerClass();
//lc.sum();
return lc;
}
public static void main(String[] args) {
LocalOuterClass Loc = new LocalOuterClass();
Object obj = Loc.run();
System.out.println(obj.getClass());
Method[] methods = obj.getClass().getMethods();
for (Method method : methods) {
String MethodName = method.getName();
System.out.println("Name of the method: "+ MethodName);
}
}
} //end of outer
When I do lc.sum(), the sum() is correctly executed. But when I'm returning an object of the inner class to the main() and try to execute sum(), it gives a compiler error. Doing getClass().getMethods() on the object does print sum() as one of the methods. What should I do to execute the sum() inside main()?
You have to change return type to LocalInnerClass and move LocalInnerClass out of the method:
public class LocalOuterClass {
private int x = 10;
private class LocalInnerClass {
private int y = 20;
public void sum() {
System.out.println(x + y);
}
}
private LocalInnerClass run() {
LocalInnerClass lc = new LocalInnerClass();
//lc.sum();
return lc;
}
public static void main(String[] args) {
LocalOuterClass Loc = new LocalOuterClass();
LocalInnerClass obj = Loc.run();
obj.sum(); // it works!
// ...
}
}
The problem is, that the whole LocalInnerClass is not known to your main-method. It does not help, that it has a public method, if the whole type is unknown. You need to refactor your code in order to change that.
Actually your method run currently returns a value of type Object and you'd need to return a value of type LocalInnerClass, however this is not possible due to type visibility.
There are basically two options you have. One is to move the whole LocalInnerClass to a location that is visible to main (like oleg.cherednik suggested):
class LocalOuterClass {
private int x = 10;
private LocalInnerClass run() { // now we can retun `LocalInnerClass`
return new LocalInnerClass();
}
public static void main(String[] args) {
new LocalOuterClass().run().sum(); // works!
}
private class LocalInnerClass {
private int y = 20;
public void sum() {
System.out.println(x+y);
}
}
}
Another option is to implement/extend a different type that has sum, e.g. like this:
class LocalOuterClass {
private int x = 10;
private Summable run() { //start of inner
class LocalInnerClass implements Summable {
private int y = 20;
public void sum() {
System.out.println(x+y);
}
}
return new LocalInnerClass();
}
public static void main(String[] args) {
new LocalOuterClass().run().sum(); // works as well
}
private interface Summable {
void sum();
}
}
With this interface-option the type LocalInnerClass is still not visible to anyone outside your run-method, however the Summable-interface is and since your LocalInnerClass implements Summable you can return a value of that type.

Use an object in other methods of a test class

I have a test class in Android test package. There is a class that I've create an object in it. But other method of this test class can not use this object and can not recognize the result of that method. Why and what should I do? I used static too but can't...
#RunWith(AndroidJUnit4.class)
public class PatientDaoTest {
private static int newRowId;
public static PatientRecordEntity newPatient1;
public void generationRecord(){
newRowId = 0;
PatientRecordEntity newPatient1 = new PatientRecordEntity();
newPatient1.setPatient_db_ID("23456");
newPatient1.setPatient_race("Chines");
newRowId = (int) patientDao.addNewPatient(newPatient1);
newPatient1.setPid(newRowId);
}
#Test
public void addNewPatient() throws Exception {
boolean pin = false;
if (0 != newRowId) {
pin = true;
}
assertTrue("addNewPatient is not true", pin);
}
use the annotation #Before.
like:
public class HTest {
public static Integer i;
#Before
public void before(){
i = 10;
}
#Test
public void print() {
System.out.println(i);
}
}
This before method will be executed before print and i will be Initialized.

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.

How to pass down the new operator in a method

For example, if I wanted to do something like this to call a method:
myLights.addLight(new Fluorescent(lumens));
in order to create a new object in the Fluorescent class and pass down the lumens data. How would I then set up the method to receive this?
Assuming method is not returning anything.
void addlight(Fluorescent a){
// your logic
}
In your Lights class create a method that accepts a Fluorescent object as an argument.
public void addLight(Fluorescent fluorescent){
// do something
}
Here is a basic example:
public class HelloWorld
{
public static void main(String[] args)
{
Light light = new Light();
light.addLight(new Fluorescent("300 lm"));
System.out.print(light.getLumen());
}
}
public class Light {
private String lumen;
public Light() {
}
public void setLumens(String lumen){
this.lumen = lumen;
}
public String getLumen(){
return this.lumen;
}
public void addLight(Fluorescent fluorescent) {
if(fluorescent.getLumen() != null) {
this.lumen = fluorescent.getLumen();
}
}
}
public class Fluorescent {
private String lumen;
public Fluorescent(String lumen){
this.lumen = lumen;
}
public void setLumen(String lumen){
this.lumen = lumen;
}
public String getLumen(){
return this.lumen;
}
}
Seeing that a Fluorescent is a Light, you might want to look in to inheritance.
Look here for some explanation
Java 101: Inheritance in Java, Part 1
public class Fluorescent() {
public Fluorescent(String lumens) {
// do something
}
}
public class Lights() {
public void addLight(Fluorescent fluorescent) {
// do something
}
}

Nesting calls to static methods

I want to do something like below, but it does not work. My objective is to be able to nest function calls to static helper classes to get more brevity.
public class StaticHelper {
public static Class<StaticHelper> doSomthing() {
System.out.println("I just did something !!");
return StaticHelper.class;
}
public static Class<StaticHelper> doSomthingElse() {
System.out.println("I just did something else !!");
return StaticHelper.class;
}
public static void main(String[] args) {
// Does not compiles
StaticHelper.doSomthing().doSomthingElse();
}
}
Is this possible? If so a simple example as above will be very helpful.
I guess you want something like this.
public class StaticHelper {
private final static StaticHelper INSTANCE = new StaticHelper();
public static StaticHelper doSomthing(){
System.out.println("I just did something !!");
return INSTANCE;
}
public static StaticHelper doSomthingElse(){
System.out.println("I just did something else !!");
return INSTANCE;
}
public static void main(String[] args) {
StaticHelper.doSomthing().doSomthingElse();
}
}
or another way
public class StaticHelper {
public static SomeClass doSomthing(){
return new SomeClass().doSomthing();
}
public static SomeClass doSomthingElse(){
return new SomeClass().doSomthingElse();
}
public static void main(String[] args) {
StaticHelper.doSomthing().doSomthingElse();
}
private static class SomeClass {
public SomeClass doSomthing(){
System.out.println("I just did something !!");
return this;
}
public SomeClass doSomthingElse(){
System.out.println("I just did something else !!");
return this;
}
}
}
That is not possible, but using static imports is.
public class StaticHelper {
public static void doSomething() {
System.out.println("I just did something !!");
}
public static void doSomethingElse() {
System.out.println("I just did something else !!");
}
}
in another class:
import static StaticHelper.*;
class Other {
public static void main(String[] args) {
doSomething(); // calls static methods from StaticHelper
doSomethingElse();
}
}
or - if the methods are logically connected - you can have one static factory method and the rest are instance methods:
public class StaticHelper {
public static void beginDoingSomething() {
// static factory method - you can pass parameters to it if needed
System.out.println("I just did something !!");
return new StaticHelper();
// if needed, initialize the instance with the parameters
}
public StaticHelper andDoSomethingElse() {
// instance method
// can use the instance parameters (passed to the constructor in the static factory method)
// or use parameters passed to this method
System.out.println("I just did something else !!");
return this;
// returns this for chaining
}
}
in another class:
import static StaticHelper.*;
class Other {
public static void main(String[] args) {
doSomething().andDoSomethingElse().andDoSomethingElse();
}
}
If you name the methods nicely, you can form a sentence:
validate(object).checkEmail().checkName().checkTelephoneStartsWith("+11");
where validate(object) is a static factory method constructing a new validator instance for the given object.

Categories

Resources