006 The Fuctions in JAVA, 006 fuctions
In JAVA, all functions (or methods) must be defined in the class.
Let's not talk about it. Let's look at the example first:
Class Point {int x; int y; Point () {// This is the default class. If we do not have any constructor, the compiler adds this} Point (int x, int y) {this. x = x; this. y = y;}/*** print my coordinates */void displayMyCoordinate () {System. out. println ("coordinate (x, y) = (" + this. x + "," + this. y + "). ");}/*** returns the midpoint of This vertex and another vertex * @ param other: Another vertex */Point midpoint (Point other) {// note, here, the return value type is a Point object return new Point (this. x + other. x)/2, (this. y + other. y)/2 );}/*** Return the midpoint * @ param A: vertex A * @ param B: vertex B */Point midpoint (Point A, Point B) {// note, here, the return value type is a Point object, and JAVA polymorphism is also used here. polymorphism is simply a method of multiple forms.
// For example, this method has the same name as the aforementioned Point midpoint (Point other) method. Although the name is the same as the number of single parameters, This Is A polymorphism.
// Polymorphism is used to provide methods that cannot be used by callers.
Return new Point (. x + B. x)/2, (. y + B. y)/2);} public static void main (String [] args) {Point p = new Point (2, 3 ); // We can use the constructor we defined to construct the Point instance p as follows. System. out. println ("the value of member variable x in object p is:" + p. x); // we can use p. x Access Object p member variable x System. out. println ("the value of member variable y in object p is:" + p. y); // we can use p. y: The member variable of Access Object p y p. displayMyCoordinate (); Point A = new Point (5, 6); Point B = new Point (10, 20); Point C = p. midpoint (A); // obtain the Point C Point D = p. midpoint (A, B); // obtain the point D of A and B.
// No, the aforementioned polymorphism is used here
System. out. print ("p:"); p. displayMyCoordinate (); System. out. print ("A:");. displayMyCoordinate (); System. out. print ("B:"); B. displayMyCoordinate (); System. out. print ("p, A's midpoint C:"); C. displayMyCoordinate (); System. out. print ("midpoint D of A and B:"); D. displayMyCoordinate ();}}