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
}
}
Related
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.
How can I call same class constructor from same class method?
I can use this() but it raise the error.
class MyConstructor {
public MyConstructor() {
System.out.println("My Constructor") ;
}
public void MyCall () {
// Call MyConstructor
}
}
public class Constructor {
public static void main(String[] args) {
MyConstructor mycon = new MyConstructor() ;
}
}
You can just call the constructor when instantiating a new Object with the new()-Keyword.It is not possible to call the constructor from within the class otherwise. But you can write another function whit all the logic from the constructor-MEthod. In the constructor you just call this method.
class MyConstructor {
public MyConstructor() {
helperMethod();
}
public void helperMethod(){
System.out.println("My Constructor") ;
}
public void MyCall () {
// Call MyConstructor
helperMethod();
}
i'm trying to write anonymous inner class
interface Face{
void seeThis(String what);
}
class Eyes {
public void show(Face f){}
}
public class Seen {
public void test() {
Eyes e = new Eyes();
e.show(new Face() {
#Override
public void seeThis(String what){
System.out.print(what);
}
});
public static void main(String[] args) {
Seen s = new Seen();
s.test();
}
}
How to call seeThis() and how to pass parameter to it?
Method seeThis() belongs to Face class, which instance is anonymous and thus cannot be reached without storing reference to it. If you want to store a reference, you can do this in the following way:
public class Seen {
public Face face;
....
this.face = new Face() { ... };
e.show(this.face);
And then,
Seen s = new Seen();
s.face.seeThis();
Now, regarding passing the parameter. You have two options - declare parameter outside of anonymous class and make it final in order to be reachable by this anonymous class, or replace anonymous class with normal one and pass the parameter to its constructor:
Approach one:
final int parameter = 5;
...(new Face() {
#Override
public void seeThis() {
System.out.println(parameter);
}
});
Approach two:
public class MyFace implements Face() {
private final int parameter;
public MyFace(int parameter) {
this.parameter = parameter;
}
#Override
public void seeThis() {
System.out.println(parameter);
}
}
Then,
...
e.show(new MyFace(10));
Suppose I have two classes A and B where A is a superclass of B. Now, I write a function (override), say funct() in both the classes. Then, if I want to call the funct() in A from an object of B, is it possible?
class A {
public void f() {...}
}
class B extends A {
#Override public void f() { super.f(); }
}
Is that what you want?
If instead you want to call A#f() directly on an instance of type B, you must provide a placeholder function for that:
class B extends A {
#Override public void f() { ... }
public void superF() { super.f(); }
}
new B().f(); // calls B#f();
new B().superF(); // calls A#f();
I have trick such as this situation to operate it in an illogical manner using Flag argument in funct() method :D, like this:
class A {
public void funct(boolean callSuper) {
// avoid using callSuper arg here
}
}
class B extends A {
#Override
public void funct(boolean callSuper) {
if (callSuper) {
super.funct(callSuper);
return;//if return type is void
} else {
//do here the functionality if the flag is false
}
}
}
or
class A {
public void funct() {
}
}
class B extends A {
private boolean callSuper = false;
#Override
public void funct() {
if (callSuper) {
super.funct(); // call A.funct() functionality
setCallSuper(false);
} else {
//do here the functionality of B.funct() if the flag is false
}
}
public void setCallSuper(boolean callSuper){
this.callSuper = callSuper;
}
}
Given classes like
class A {
public void funct() {...}
}
class B extends A {
#Override
public void funct() {...}
}
You ask
Then, if I want to call the funct() in A from an object of B, is it
possible?
So let's take
B b = new B();
b.funct();
A a = b;
a.funct();
((A)b).funct();
The above all do the same thing because of polymorphism and late-binding.
The only way to call the superclass' implementation is to get a reference to that member through the super keyword.
class A {
public void funct() {...}
}
class B extends A {
#Override
public void funct() {
super.funct();
}
}
I've got something along the lines of the following:
public class A {
public void theMethod(Object arg1) {
// do some stuff with a single argument
}
}
public class B {
public void reflectingMethod(Object arg) {
Method method = A.class.getMethod("theMethod", Object.class);
method.invoke(new A(), arg);
}
}
How do I modify that so that I can do the following instead?
public class A {
public void theMethod(Object... args) {
// do some stuff with a list of arguments
}
}
public class B {
public void reflectingMethod(Object... args) {
Method method = A.class.getMethod("theMethod", /* what goes here ? */);
method.invoke(new A(), args);
}
}
A.class.getMethod("theMethod", Object[].class);
Darthenius's suggestion in the comments for the original question worked, once I wrapped my head around how to do it.
public class A {
public void theMethod(ArrayList<Object> args) { // do stuff
}
}
public class B {
public void reflectingMethod(ArrayList<Object> args) {
Method method;
try {
method = A.class.getMethod("theMethod", args.getClass());
method.invoke(new A(), args);
} catch (Exception e) {}
}
}