The Java object-oriented approach
Methods are part of an object, also known as behavior;
Let's start with a simple example:
1 Packagecom.java1234.chap03.sec03;2 3 Public classPerson {4 5 voidspeak () {6System.out.println ("I am Zhang San");7 }8 9 Public Static voidMain (string[] args) {TenPerson person=NewPerson (); One person.speak (); A } -}
The above is a non-parametric method, we changed, changed to a parameter, the name we call the method when determined. Add a name parameter;
On the code:
1 Packagecom.java1234.chap03.sec03;2 3 Public classPerson {4 5 voidspeak (String name) {6 System.out.println (name);7 }8 9 Public Static voidMain (string[] args) {TenPerson person=NewPerson (); OnePerson.speak ("Zhang San"); A } -}
method, we can also have multiple parameters, separated by commas , we add an age parameter:
On the code:
1 Packagecom.java1234.chap03.sec03;2 3 Public classPerson {4 5 voidSpeak (String name,intAge ) {6System.out.println ("My name is +name+", I'm "+age+" this year.);7 }8 9 Public Static voidMain (string[] args) {TenPerson person=NewPerson (); OnePerson.speak ("Zhang San", 23); A } -}
And if we want to add hobbies, the number of hobbies is not fixed, this time we can use the non-fixed parameters
On the code:
1 Packagecom.java1234.chap03.sec03;2 3 Public classPerson {4 5 voidSpeak (String name,intAge ,String ... hobbies) {6System.out.println ("My name is +name+", I'm "+age+" this year.);7 for (String hobby:hobbies){8System.out.println (hobby+ "");9 }Ten } One A Public Static voidMain (string[] args) { -Person person=NewPerson (); -Person.speak ("Zhang San", 23, "swimming", "singing"); the } -}
Return value of the method: Returns the number of hobbies
On the code:
1 Packagecom.java1234.chap03.sec03;2 3 Public classPerson {4 5 intSpeak (String name,intAge ,String ... hobbies) {6System.out.println ("My name is +name+", I'm "+age+" this year.);7 for(String hobby:hobbies) {8System.out.println (hobby+ "");9 }Ten //get the length of your hobby One inttotalhobbies= hobbies.length; A returntotalhobbies; - } - the Public Static voidMain (string[] args) { -Person person=NewPerson (); - intN=person.speak ("Zhang San", 23, "swimming", "singing"); -System.out.println ("Have" +n+ "a hobby"); + } -}
Of course, the return type is either int or string, float, etc. include object
Java object-oriented-method definition and simple use