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(); } }
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.
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.
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).
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.
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.
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