1. Exam Points
- How to
declare class methods(static) andinstance methods.- How to
call class methods (static) and instance methods.Pay attention to the return type and argumentspassed into a method.- Example:
declare: public boolean check(int a, String b, double c) {}call: boolean result =check(10, ”anna”, 5.3);- Pay attention:
call methods from the same class or a different class.
- an instance method can call another method in the same class directly.
- an method needs to call another instance method in a different class by using an object name.
2. Knowledge Points
(1) Class Methods and Instance Methods
- A
class methodis declared using thestatickeyword, andis called using the class name.- Example:
public class A{ public static void test1(){} } public class B{ public static void main(String[] args){ A.test1(); } } - An instance method is declared without using the static keyword, and
is called using an object/instance name.- Example:
public class A{ public void test2(){} } public class B{ public static void main(String[] args){ A a = new A(); a.test2(); } }
(2) Calling Instance Methods
Instance methodsare called onobjectsof the class, are non-static methods.A method call on a null reference will result in a NullPointerException.- Example:
Dog d = null; d.bark(); // d is null, leading to NullPointerException