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.
Related
Are both the below approaches for lazy-initializing thread-safe singleton in java correct? Is there any performance difference? If not then why do we use the Holder pattern(Singleton2) instead of keeping it simple as in Singleton1 ?
Thanks in advance.
class Singleton1 {
private Singleton1() {
System.out.println("Singleton1-Constructor");
}
private static final Singleton1 inst1 = new Singleton1();
public static Singleton1 getInst1() {
return inst1;
}
}
class Singleton2 {
private Singleton2() {
System.out.println("Singleton2-Constructor");
}
public static class Holder {
private static final Singleton2 holderInst = new Singleton2();
}
public static Singleton2 getInst2() {
return Holder.holderInst;
}
}
public class App {
public static void main(String[] args) {
Singleton1.getInst1(); // without this statement the Singleton1 constructor doesnt get called.
Singleton2.getInst2(); // without this statement the Singleton2 constructor doesnt get called.
}
}
Singleton1 is not truly lazy, since if you add any other method to Singleton1 and call it from the main class, then the static inst1 will be initialized.
Try this:
public class Singleton1 {
private Singleton1() {
System.out.println("Singleton1-Constructor");
}
private static final Singleton1 inst1 = new Singleton1();
public static Singleton1 getInst1() {
return inst1;
}
public static void foo() {
}
}
public class Singleton2 {
private Singleton2() {
System.out.println("Singleton2-Constructor");
}
public static class Holder {
private static final Singleton2 holderInst = new Singleton2();
}
public static Singleton2 getInst2() {
return Singleton2.Holder.holderInst;
}
public static void bar() {
}
}
public class LazyInitializationApp {
public static void main(String[] args) {
Singleton1.foo();
Singleton2.bar();
}
}
Now running the app will print:
Singleton1-Constructor
But it will not print Singleton2-Constructor, because it is truly lazy.
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);
}
}
I have two nested classes inside a class with the outer class extending another class. The structure is something like this.
public class EXTENSION_CLASS
{
public int Get_Value()
{
return(100);
}
}
public class OUTER extends EXTENSION_CLASS
{
public static class NESTED1
{
public void Method1()
{
int value=0;
value=Get_Value();
System.out.println("Method1: "+value);
}
}
public static class NESTED2
{
NESTED1 Nested1_Instance=new NESTED1();
public void Method2()
{
Nested1_Instance.Method1();
}
}
public void run()
{
NESTED2 Nested2_Instance=new NESTED2();
Nested2_Instance.Method2();
}
public static void main (String[] args)
{
OUTER New_Class=new OUTER();
New_Class.run();
}
}
I'm expecting the output: "Method1: 100". But, am getting the output: "OUTER.java:16: error: non-static method Get_Value() cannot be referenced from a static context value=Get_Value();". How can i make this working?
Cheers !
Rajesh.
One approach would be to have an instance of NESTED1 in NESTED2. For example:
private static class NESTED2
{
private NESTED1 nested1;
public NESTED2 (NESTED1 nested1) {
this.nested1 = nested1;
}
public void Method2()
{
nested1.Method1();
}
}
private static class NESTED2
{
public void Method2(NESTED1 nested1Instance)
{
nested1Instance.Method1();
}
}
That should do it with your class structure. Instead, with a modification like so....
private static class NESTED1
{
public *statc* void Method1()
{
...
}
}
private static class NESTED2
{
public *static* void Method2()
{
NESTED1.Method1();
}
}
... you could get away with no creation of objects.
If you make the methods static, you don't need to instantiate(create) a class object to call them first.
I need to call a method after the constructor has ended, and I have no idea what is the better approach.
I have this class:
class A {
public A() {
// ...
}
public void init() {
// call after the constructor
}
}
How do I call init() after the class A has been created?
You either have to do this on the client side, as so:
A a = new A();
a.init();
or you would have to do it in the end of the constructor:
class A {
public A() {
// ...
init();
}
public final void init() {
// ...
}
}
The second way is not recommended however, unless you make the method private or final.
Another alternative may be to use a factory method:
class A {
private A() { // private to make sure one has to go through factory method
// ...
}
public final void init() {
// ...
}
public static A create() {
A a = new A();
a.init();
return a;
}
}
Related questions:
What's wrong with overridable method calls in constructors?
Java call base method from base constructor
You will need a static factory method to construct the object, call the init method, and finally return the object:
class A {
private A() {
//...
}
private void init() {
//Call after the constructor
}
public static A create() {
A a = new A();
a.init();
return a;
}
}
Notice I have made the constructor and the init() method private, so that they can only be accessed by the factory method. Client code would make objects by calling A.create() instead of calling the constructor.
What did you so far? Are you looking something like this?
Class A {
public A() {
//...
}
public void init() {
//Call after the constructor
}
}
public static void main(String[] args)
{
A a = new A();
a.init();
}
I pick up some ideas and provide an abstractable solution:
class A {
protected A() {
// ...
}
protected void init() {
// ...
}
public static <T extends A> T create(Class<T> type) {
try {
T obj = type.newInstance();
obj.init();
return obj;
} catch (ReflectiveOperationException ex) {
System.err.println("No default constructor available.");
assert false;
return null;
}
}
}
If you want to call method BEFORE constructor you can use initializer block. https://www.geeksforgeeks.org/g-fact-26-the-initializer-block-in-java/
class A {
{
init()
}
public A() {
//todo
}
private final void init() {
//todo
}
}
Why not this :
Class A {
public A() {
//... Do you thing
this.init();
}
public void init() {
//Call after the constructor
}
}
I have a sample code to solve which is based on inner classes:
package inner;
class A {
void m() {
System.out.println("Outer");
}
}
public class TestInner {
public static void main(String[] args) {
new TestInner().go();
}
private void go() {
new A().m();
class A{
void m(){
System.out.println("Inner");
}
}
new A().m();
}
class A{
void m(){
System.out.println("Middle");
}
}
}
The output given by above sample code is:
Middle
Inner
And my question is, given that I dont want to use the package name to create an object, how can I print the output as:
Outer
Inner
Since using a package is so obviously the answer, I assume you are looking for something obtuse.
You can add an outer class and call that.
class B extends A { }
// in TestInner.go()
new B().m();
class A{
void m(){
System.out.println("Inner");
}
}
new A().m();
public class TestInner {
public static void main(String[] args) {
new TestInner().go();
}
private void go() {
new inner.A().m(); //will produce output "Outer"
class A{
void m(){
System.out.println("Inner");
}
}
new A().m(); //will produce output "Inner"
}
class A{
void m(){
System.out.println("Middle");
}
}