580 likes | 589 Views
Learn how to declare and call methods in Java, including changing variable values and object references. See examples of method signatures and arrays.
E N D
Chapter 4 Using Methods
Calling Method CCE JMU CHINA
Worker Method CCE JMU CHINA
Declaring Methods • Worker and calling methods have the same syntax structure. CCE JMU CHINA
**参见程序运行 CCE JMU CHINA
PassTest.java • public class PassTest { • // changeInt(int)方法用于改变int数据值 • public static void changeInt(int value) { • value = 55; • } CCE JMU CHINA
// changeObjectRef(MyDate)方法用于改变MyDate引用变量 public static void changeObjectRef(MyDate ref) { ref = new MyDate(10, 10, 2008); // changeObjectAttr(MyDate) 方法用于改变引用对象的变量 CCE JMU CHINA
public static void changeObjectAttr(MyDate ref) { • ref.setDay(17); • } • } • public static void main(String args[]) { • MyDate date; • int val; • // 赋int val变量值11 CCE JMU CHINA
val = 11; • // 单向传递val值,调用changeInt(int)方法 • changeInt(val); • // 观测val的当前值 CCE JMU CHINA
System.out.println("Int value is: " + val); • // 为date引用赋值,date引用对象MyDate(7, 7, 2007) • date = new MyDate(7, 7, 2007); • //单向传递date值,调用changeObjectRef(MyDate)方法 • changeObjectRef(date); CCE JMU CHINA
// 观测date引用值 • date.print(); • // 调用changeObjectAttr(MyDate)方法, • //通过date改变所引用对象的变量 • // 观测date引用值 • date.print(); • } • } CCE JMU CHINA
运行结果: ---------- java ---------- • Int value is: 11 • MyDate: 7-7-2007 • MyDate: 17-7-2007 • Normal Termination • Output completed (0 sec consumed). CCE JMU CHINA
**参见程序运行 CCE JMU CHINA
Method Signature • method signature is unique • method name +argument list CCE JMU CHINA
public class Point { private int x; private int y; public String toString() { return ("[" + x + "," + y + "]"); } } CCE JMU CHINA