I wrote a method (that works fine) for a()
in a class. I want to write another method in that class that calls the first method so:
void A::a() { do_stuff; } void A::b() { a(); do_stuff; }
I suppose I could just rewrite b()
so b(A obj)
but I don't want to. In java can you do something like this.a()
.
I want to do obj.b()
where obj.a()
would be called as a result of obj.b()
.
Similarly another method which is Method2() is being defined with 'public' access specifier and 'void' as return type and inside that Method2() the Method1() is called. Hence, this program shows that a method can be called within another method as both of them belong to the same class.
In order to call Method in another Method that is contained in the same Class is pretty simple. Just call it by its name!
You can also use the instance of the class to call the public methods of other classes from another class. For example, the method FindMax belongs to the NumberManipulator class, and you can call it from another class Test.
Java does not support “directly” nested methods. Many functional programming languages support method within method. But you can achieve nested method functionality in Java 7 or older version by define local classes, class within method so this does compile.
What you have should work fine. You can use "this" if you want to:
void A::b() { this->a(); do_stuff; }
or
void A::b() { this->A::a(); do_stuff; }
or
void A::b() { A::a(); do_stuff; }
but what you have should also work:
void A::b() { a(); do_stuff; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With