Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a method inside another method in same class

Tags:

java

In page 428 (the chapter about Type Information) of his "Thinking In Java, 4th Ed.", Bruce Eckel has the following example:

public class Staff extends ArrayList<Position> {     public void add(String title, Person person) {         add(new Position(title, person));     } /* rest of code snipped */ 

Maybe I'm a bit tired, but I can't see how the call to add() inside the add() method works. I keep thinking that it should have a reference, or be a static method (and I can't find a static add() in ArrayList or List). What am I missing?

I just tested for myself, and found that this works:

// Test2.java public class Test2 {     public void testMethod() {         testMethod2();     }      public void testMethod2() {         System.out.println("Here");     }      public static void main(String[] args) {         Test2 t = new Test2();         t.testMethod();     } } 
like image 331
Adriano Varoli Piazza Avatar asked Sep 06 '11 20:09

Adriano Varoli Piazza


People also ask

Can you use a method inside another method?

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.

Can we call one method from another method in Java?

We can call a method from another class by just creating an object of that class inside another class. After creating an object, call methods using the object reference variable.

How do you call a method inside a class in Java?

To call a method in Java, write the method name followed by a set of parentheses (), followed by a semicolon ( ; ). A class must have a matching filename ( Main and Main. java).

How do you call a method inside another class?

To class a method of another class, we need to have the object of that class. Here, we have a class Student that has a method getName() . We access this method from the second class SimpleTesting by using the object of the Student class.


1 Answers

Java implicitly assumes a reference to the current object for methods called like this. So

// Test2.java public class Test2 {     public void testMethod() {         testMethod2();     }      // ... } 

Is exactly the same as

// Test2.java public class Test2 {     public void testMethod() {         this.testMethod2();     }      // ... } 

I prefer the second version to make more clear what you want to do.

like image 50
Daff Avatar answered Sep 17 '22 19:09

Daff