How to pass variable from one parameterized method to another? - java

How do I send the variable from main method to the Method A, and what Parameter should I pass within A(), in method B.
Code:
public class MethodCall {
public void A(String c) {
System.out.println(c);
}
public void B() {
A(); // What parameter do I pass here. method B is dependent on A
}
#Test
public void D() {
B();
MethodCall mc = new MethodCall();
mc.A("Hello");
}
}

In method A you expect one parameter of type String therefore you have to provide a parameter for String can be just an empty String "" or null.
Another option depending on your use case; you could use varargs:
public void a(String... varargs) {...}
In this case it's possible to give zero or multiple parameters of type String.
So this works:
a("Hello World");
this:
a();
But also this:
a("Hello", "World");
Or you could just pass all parameters necessary for A through B:
public class MethodCall {
public void A(String c) {
System.out.println(c);
}
public void B(String c) {
A(c);
}
#Test
public void D() {
MethodCall mc = new MethodCall();
mc.B("Hello World");
mc.A("Hello");
}
}

You should pass the String parameter for within A(), in method B.
public class MethodCall {
public void A(String c) {
System.out.println(c);
}
public void B() {
A("Pass the String parameter");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
MethodCall mc = new MethodCall();
mc.A("Hello");
mc.B();
}
}

when you passing the String type as a parameter its mean you should use to same data type when you giving the value to the parameter. you cant use any other types like Integer, float etc. you just need to pass the String value to the given parameter.
When you are using non-static method it cannot call directly. so use
static keyword to call the method in directly.
ANSWER-
public class MethodCall {
public static void A(String c) {
System.out.println(c);
}
public static void B() {
A("HI "); //you can put `null` or `empty`
}
public static void main(String[] args) {
B();
MethodCall mc = new MethodCall();
mc.A("Hello");
}
}

I am not so sure about your question but here is my take:
public class MethodCall {
public void A(String c) {
System.out.println(c);
}
public void B(String s) {
A(s); //If you want to call A() here, then you would have to pass a variable in the parameters of A(), as A() is a parameterized method by definition.
}
public static void main(String[] args) {
// TODO Auto-generated method stub
MethodCall mc = new MethodCall();
mc.A("Hello"); //This part is right, that is how you pass value of a non static function through main method.
}

Related

super not working as I expected? (calling derived method instead of base method)

Let's say we have the following code:
public class A {
void someMethod() {
System.out.println("Some method from A");
}
void someOtherMethod() {
System.out.println("Some other method from A");
this.someMethod();
}
}
public class B extends A {
void someMethod() {
System.out.println("Some method from B");
}
void test() {
System.out.println("Test method from B");
super.someOtherMethod();
}
}
public class Main {
public static void main(String[] args) {
B b = new B();
b.test();
}
}
The output is:
Test method from B
Some other method from A
Some method from B
Why in 'someOtherMethod()' from A, when we call 'this.someMethod()' the program calls the method from B. I was expecting it to call 'someMethod()' from A and print 'Some method from A' on the third line instead of 'Some method from B'. Why is this happening and how can I make it so it works as I intended?

Java chained reflection

I have this chained method call
Integer.parseInt(A.get().getC().getD().toString());
I need to make this with reflection. I know that I can use Class.forName(String class) and then invoke methods, but how do I save method results so I can call that chain.
Classes:
public class A
{
public static B get() { return new B(); }
}
public class B
{
public C getC() { return new C();}
}
public class C
{
public C getD() { return new D();}
}
Suppose we have this classes:
public class A {
public B getB() { return new B(); }
public static B getBStatic() { return new B(); }
}
public class B { public C getC() { return new C();}}
public class C { public String getD() { return "done"}}
Example 1:
public static void main(String[] args) throws Exception {
Class<A> clazz = A.class;
Constructor<A> constructor = clazz.getConstructor();
A instance = constructor.newInstance();
Method getMethod = clazz.getDeclaredMethod("getB");
Object b = getMethod.invoke(instance);
Method getCMethod = b.getClass().getDeclaredMethod("getC");
Object c = getCMethod.invoke(b);
Method getDMethod = c.getClass().getDeclaredMethod("getD");
String d = (String) getDMethod.invoke(c);
System.out.println(d); // done
}
Example 2:
public static void main(String[] args) throws Exception {
reflection(new A(), "getB", "getC", "getD"); // invoke non static methods
reflection(new A(), "getBStatic", "getC", "getD"); // invoke static and nonstatic methods
reflection(A.getBStatic(), "getC", "getD"); // provide object from static method
reflection(invokeStaticMethod(A.class, "getBStatic"), "getC", "getD"); // invoke static method without instance
}
public static Object invokeStaticMethod(Class<?> clazz, String methodName) throws Exception {
return clazz.getMethod(methodName).invoke(clazz);
}
public static void reflection(Object instance, String... methods) throws Exception {
Object item = instance;
for (String methodName : methods) {
item = item.getClass().getDeclaredMethod(methodName).invoke(item);
}
System.out.println(item); // done
}

What does makes those methods calls returns those values?

I need to write what is the output of those methods calls.
My answer was:
I i = new A();
i.m(b);
My answer: m_IB because I doesn't have any method with a B type so I went down to class A which implements I. A doesn't also have any methods with parameter B but it extends I.IImpl which has a method with m(B b) that prints m_IB.
I j = new B();
j.m(b);
My answer: m_BB becuase again I doesn't have any method with a B type so I went down to class B because I j = new B() and it has a m(B b) which print m_BB.
interface I {
public void m(A a);
class IImpl {
public static void m(B b) { System.out.println("m_IB"); }
}
}
class A extends I.IImpl implements I {
public void m(A a) { System.out.println("m_AA"); }
}
class B extends A {
public void m(A a) {
super.m(a);
System.out.println("m_BA");
}
public static void m(B b) { System.out.println("m_BB"); }
}
public class Interfac {
public static void main(String[] args) {
A a = new A();
B b = new B();
a.m(b); System.out.println(); // m_IB
I i = new A();
i.m(b); System.out.println(); // m_AA
I j = new B();j.m(b); // m_AA m_BA
}
}
Both of my answers are wrong and the correct output is m_AA for i and m_AA m_BA for j.
I can't understand why I get this output even if I'm calling a method with a type B.
Both of the correct answer are calling a m(A a) methods.
Your interface provides this method:
public void m(A a);
And your j is declared like this:
I j = new B();
So, yes, it's an instance of B, but it is declared as an I, meaning, when you call that method, it calls the method provided by the interface, not the overloaded one.
So, in class B it takes the method that is provided by the interface:
public void m(A a) { // this one
super.m(a);
System.out.println("m_BA");
}
// not this overloaded one
public static void m(B b) { System.out.println("m_BB"); }
The first line of that method is:
super.m(a);
Which calls the m(a) method in the A class, which then prints: "m_AA".
Then, it prints "m_BA"

Simulate constructor overriding in Java?

Several times I thought it will be good to have overridable constructor in Java.
"Overridable" means the logic of construction can be overriden and/or extended in descending classes in the same way it is possible to override normal methods, i.e. with ability to call parent method AFTER the child.
This task can be formulated as to have a method, say, called init() which is called at construction time, but only in the last constructor of the stack.
Like:
public class InitializationOverride {
public static class A {
A() {
System.out.println("Constructor of A");
}
void init() {
System.out.println("Init of A");
}
}
public static class B extends A {
B() {
System.out.println("Constructor of B");
}
#Override
void init() {
System.out.println("Init of B");
}
}
public static class C extends B {
C() {
System.out.println("Constructor of C");
}
#Override
void init() {
System.out.println("Init of C");
}
}
public static void main(String[] args) {
new A(); // should print "Constructor of A, Init of A"
new B(); // should print "Constructor of A, Constructor of B, Init of B"
new C(); // should print "Constructor of A, Constructor of B, Constructor of C, Init of C"
}
}
The obvious way is to write
public static void main(String[] args) {
new A().init();
new B().init();
new C().init();
}
but this doesn't guarantee init() is not forgotten to call.
Is it possible to do somehow?
UPDATE
It is not known at design time, which class will be "last". It is expected, that class tree will be developed in future.
UPDATE 2
Here is the solution with reflection and constructor code requirement to call currentStage() at the end:
public class InitializationOverride {
public static class A {
A() {
System.out.println("Constructor of A");
currentStage(A.class);
}
void currentStage(Class<?> cls) {
if( cls == getClass() ) {
init();
}
}
void init() {
System.out.println("Init of A");
}
}
public static class B extends A {
B() {
System.out.println("Constructor of B");
currentStage(B.class);
}
#Override
void init() {
System.out.println("Init of B");
}
}
public static class C extends B {
C() {
System.out.println("Constructor of C");
currentStage(C.class);
}
#Override
void init() {
System.out.println("Init of C");
}
}
public static void main(String[] args) {
new A(); // should print "Constructor of A, Init of A"
new B(); // should print "Constructor of A, Constructor of B, Init of B"
new C(); // should print "Constructor of A, Constructor of B, Constructor of C, Init of C"
}
Is it possible to write simpler?
Constructors shouldn't call overridable methods. If invoking of such method is necessary the better solution is makes constructors protected and provide static factory methods:
public class InitializationOverride {
public static class A {
protected A() {
System.out.println("Constructor of A");
}
public static A newInstance(){
A a = new A();
a.init();
return a;
}
protected void init() {
System.out.println("Init of A");
}
}
public static class B extends A {
protected B() {
System.out.println("Constructor of B");
}
public static B newInstance(){
B b = new B();
b.init();
return b;
}
#Override
protected void init() {
System.out.println("Init of B");
}
}
public static class C extends B {
protected C() {
System.out.println("Constructor of C");
}
public static C newInstance(){
C c = new C();
c.init();
return c;
}
#Override
protected void init() {
System.out.println("Init of C");
}
}
public static void main(String[] args) {
A.newInstance(); // should print "Constructor of A, Init of A"
B.newInstance(); // should print "Constructor of A, Constructor of B, Init of B"
C.newInstance(); // should print "Constructor of A, Constructor of B, Constructor of C, Init of C"
}
}
Edit
More explanation: Such solution provide benefits but also drawbacks. You should to provide a contract for classes (i.e. in Javadoc) that sub-classes that extends your class should follow this standard of objects creation. Also it creates more code. The profit is that objects created in that way:
C obj = C.newInstance()
...are always fully initialized and there is no need to remember for call init() method explicite.
Remember that it also will be the only method for create object outside the class' package (constructor won't be available), but inside same package constructor will be still available (protected methods are available inside same package)
In Java, when child class is instantiated, default constructor of parent class is always invoked (unless any other constructor is specified). Now, if you need to have a common code that needs to be executed for all the classes, it's recommended to put it in constructor. However, if you want something to be executed only in the last class in the hierarchy then (a) you can write it into the last constructor itself or (b) write an initialisation block, below example demonstrates this:
public class Test extends Test2{
public Test(){
System.out.println("In test");
System.out.println("Init last");
}
{
System.out.println("Init");
}
public static void main(String[] args) {
new Test();
}
}
class Test2{
public Test2(){
System.out.println("In test 2");
}
}
Just change your a class constructor like this, each object init method will call by calling this.init(), you required to change just most upper class constructor.Because at time of object creation parent class constructor will definitely call
public class Test {
public static class A {
public A() {
this.init();
}
void init() {
System.out.println("Called in A");
}
}
public static class B extends A {
#Override
void init() {
System.out.println("Called in B");
}
}
public static class C extends B {
#Override
void init() {
System.out.println("Called in C");
}
}
public static void main(String[] args) {
new A(); // should "Called in A" printed
new B(); // should "Called in B" printed
new C(); // should "Called in C" printed
}
}
Use super.init() for this to call root parent class init() .

Dynamically invoke a method from a varying class

I have a requirement where in i need to invoke method from class in a particular pattern which is obtained as input argument.
public RandomMethod(String ClassName){
//Eg For Class Name Abc , there is a method AbcProcessor which i need to invoke
ClassName.ClassNameProcessor
}
Since i am getting the argument as String , i am not able to figure out how to cast String into a form where i can call something like Abc.AbcProcessor()
I believe there is some way to do this using reflections. But i am not sure how to proceed.
By reflection you can do that, try following sample:
Class A:
public class A {
public void print(){
System.out.println("A");
}
}
Class B:
public class B {
public void print(){
System.out.println("B");
}
}
Invoking print() from A and B:
public class Test {
public static void callPrint(String className){
try {
Class clazz = Class.forName(className);
Object obj = clazz.newInstance();
clazz.getDeclaredMethod("print").invoke(obj);
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
callPrint("test.A");
callPrint("test.B");
}
}
You need to use reflecton, indeed:
public void randomMethod(String fullyQualifiedClassName, String methodName) throws ReflectiveOperationException {
Class<?> clazz = Class.forName(fullyQualifiedClassName);
clazz.getMethod(methodName).invoke(null);
}
which would work assuming you are calling public static method with no arguments

Categories

Resources