Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikibooksThe Free Textbook Project
Search

Methods

100% developed
From Wikibooks, open books for an open world
<Java Programming

LiteralsJava Programming
Methods
API/java.lang.String
NavigateLanguage Fundamentals topic:()


Methods are how we communicate with objects. When we invoke or call a method we are asking the object to carry out a task. We can say methods implement the behaviour of objects. For each method we need to give a name, we need to define its input parameters and we need to define its return type. We also need to set itsvisibility (private, protected or public). If the method throws a checked exception, that needs to be declared as well. It is called amethod definition. The syntax of method definition is:

MyClass{...publicReturnTypemethodName(ParamOneTypeparameter1,ParamTwoTypeparameter2){...returnreturnValue;}...}

We can declare that the method does not return anything using thevoid Java keyword. For example:

ExampleCode section 3.67: Method without returned data.
privatevoidmethodName(Stringparameter1,Stringparameter2){...return;}

When the method returns nothing, thereturn keyword at the end of the method is optional. When the execution flow reaches thereturn keyword, the method execution is stopped and the execution flow returns to the caller method. Thereturn keyword can be used anywhere in the method as long as there is a way to execute the instructions below:

WarningCode section 3.68:return keyword location.
privatevoidaMethod(inta,intb){intc=0;if(a>0){c=a;return;}intc=c+b;return;intc=c*2;}

In thecode section 3.68, thereturn keyword at line 5 is well placed because the instructions below can be reached whena is negative or equal to 0. However, thereturn keyword at line 8 is badly placed because the instructions below can't be reached.

Test your knowledge

Question 3.9: Consider the following code:

ExampleQuestion 3.9: Compiler error.
privateintmyMethod(inta,intb,booleanc){b=b+2;if(a>0){a=a+b;returna;}else{a=0;}}

The code above will return a compiler error. Why?

Answer
ExampleAnswer 3.9: Compiler error.
privateintmyMethod(inta,intb,booleanc){b=b+2;if(a>0){a=a+b;returna;}else{a=0;}}

The method is supposed to return aint but whena is negative or equal to 0, it returns nothing.

Parameter passing

[edit |edit source]

We can pass anyprimitive data types or reference data type to a method.

Primitive type parameter

[edit |edit source]

The primitive types arepassed in by value. It means that as soon as the primitive type is passed in, there is no more link between the value inside the method and the source variable:

ExampleCode section 3.69: A method modifying a variable.
privatevoidmodifyValue(intnumber){number+=1;}
ExampleCode section 3.70: Passing primitive value to method.
inti=0;modifyValue(i);System.out.println(i);
Standard input or outputOutput for Code section 3.70
0

As you can see incode section 3.70, themodifyValue() method has not modified the value ofi.

Reference type parameter

[edit |edit source]

The object references are passed by value. It means that:

  • There is no more link between the reference inside the method and the source reference,
  • The source object itself and the object itself inside the method are still the same.

You must understand the difference between the reference of an object and the object itself. Anobject reference is the link between a variable name and an instance of object:

Object objectnew Object()

An object reference is a pointer, an address to the object instance.

The object itself is the value of its attributes inside the object instance:

object.firstName"James"
object.lastName"Gosling"
object.birthDay"May 19"

Take a look at the example above:

ExampleCode section 3.71: A method modifying an object.
privatevoidmodifyObject(FirstClassanObject){anObject.setName("Susan");}
ExampleCode section 3.72: Passing reference value to method.
FirstClassobject=newFirstClass();object.setName("Christin");modifyObject(object);System.out.println(object.getName());
Standard input or outputOutput for Code section 3.72
Susan

The name has changed because the method has changed the object itself and not the reference. Now take a look at the other example:

ExampleCode section 3.73: A method modifying an object reference.
privatevoidmodifyObject(FirstClassanObject){anObject=newFirstClass();anObject.setName("Susan");}
ExampleCode section 3.74: Passing reference value to method.
FirstClassobject=newFirstClass();object.setName("Christin");modifyObject(object);System.out.println(object.getName());
Standard input or outputOutput for Code section 3.74
Christin

The name has not changed because the method has changed the reference and not the object itself. The behavior is the same as if the method was in-lined and the parameters were assigned to new variable names:

ExampleCode section 3.75: In-lined method.
FirstClassobject=newFirstClass();object.setName("Christin");// Start of the methodFirstClassanObject=object;anObject=newFirstClass();anObject.setName("Susan");// End of the methodSystem.out.println(object.getName());
Standard input or outputOutput for Code section 3.75
Christin

Variable argument list

[edit |edit source]

Java SE 5.0 added syntactic support for methods withvariable argument list, which simplifies the typesafe usage of methods requiring a variable number of arguments. Less formally, these parameters are calledvarargs[1]. The type of a variable parameter must be followed with..., and Java will box all the arguments into an array:

ExampleCode section 3.76: A method using vararg parameters.
publicvoiddrawPolygon(Point...points){//…}

When calling the method, a programmer can simply separate the points by commas, without having to explicitly create anarray ofPoint objects. Within the method, the points can be referenced aspoints[0],points[1], etc. If no points are passed, the array has a length of zero.

A method can have both normal parameters and a variable parameter but the variable parameter must always be the last parameter. For instance, if the programmer is required to use a minimum number of parameters, those parameters can be specified before the variable argument:

ExampleCode section 3.77: Variable arguments.
// A polygon needs at least three points.publicvoiddrawPolygon(Pointp1,Pointp2,Pointp3,Point...otherPoints){//…}

Return parameter

[edit |edit source]

A method may return a value (which can be a primitive type or an object reference). If the method does not return a value we use thevoid Java keyword.

However, a method can return only one value so what if you want to return more than one value from a method?You can pass in an object reference to the method, and let the method modify the object properties so the modified values can be considered as an output value from the method.You can also create an Object array inside the method, assign the return values and return the array to the caller. However, this gives a problem if you want to mix primitive data types and object references as the output values from the method.

There is a better approach, define a special return object with the needed return values. Create that object inside the method, assign the values and return the reference to this object. This special object is "bound" to this method and used only for returning values, so do not use a public class. The best way is to use a nested class, see example below:

Computer codeCode listing 3.12: Multiple returned variables.
publicclassMyObject{.../** Nested object is for return values from getPersonInfoById method */privatestaticclassReturnObject{privateintage;privateStringname;publicvoidsetAge(intage){this.age=age;}publicintgetAge(){returnage;}publicvoidsetName(Stringname){name=name;}publicStringgetName(){returnname;}}// End of nested class definition/** Method using the nested class to return values */publicReturnObjectgetPersonInfoById(intid){intage;Stringname;...// Get the name and age based on the ID from the database...ReturnObjectresult=newReturnObject();result.setAge(age);result.setName(name);returnresult;}}

In the above example thegetPersonInfoById method returns an object reference that contains both values of the name and the age. See below how you may use that object:

ExampleCode section 3.78: Retrieving the values.
MyObjectobject=newMyObject();MyObject.ReturnObjectperson=object.getPersonInfoById(102);System.out.println("Person Name="+person.getName());System.out.println("Person Age ="+person.getAge());
Test your knowledge

Question 3.10: Consider the following code:

ExampleQuestion 3.10: Compiler error.
privateintmyMethod(inta,intb,Stringc){if(a>0){c="";returnc;}intb=b+2;returnb;}

The code above will return a compiler error. Why?

Answer
ExampleAnswer 3.10: Compiler error.
privateintmyMethod(inta,intb,Stringc){if(a>0){c="";returnc;}intb=b+2;returnb;}

The method is supposed to return aint but at line 4, it returnsc, which is a String.

Special method, the constructor

[edit |edit source]

The constructor is a special method called automatically when an object is created with thenew keyword. Constructor does not have a return value and its name is the same as the class name. Each class must have a constructor. If we do not define one, the compiler will create a default so calledempty constructor automatically.

Computer codeCode listing 3.13: Automatically created constructor.
publicclassMyClass{/**  * MyClass Empty Constructor  */publicMyClass(){}}

Static methods

[edit |edit source]

Astatic method is a method that can be called without an object instance. It can be called on the class directly. For example, thevalueOf(String) method of theInteger class is a static method:

ExampleCode section 3.79: Static method.
Integeri=Integer.valueOf("10");

The static keyword makes attributes instance-agnostic. This means that you cannot reference a static attribute of a single object (because such a specific object attribute doesn't exist). Instead, only one instance of a static attribute exists, whether there is one object in the JVM or one hundred. Here is an example of using a static attribute in a static method:

ExampleCode section 3.80: Static attribute.
privatestaticintcount=0;publicstaticintgetNewInteger(){returncount++;}

You can notice that when you useSystem.out.println(),out is a static attribute of theSystem class. A static attribute is related to a class, not to any object instance. This is how Java achieves one universal output stream that we can use to print output. Here is a more complex use case:

Computer codeCode listing 3.14: A static attribute.
publicclassMyProgram{publicstaticintcount=0;publicstaticvoidmain(String[]args){MyProgram.count++;MyProgramprogram1=newMyProgram();program1.count++;MyProgramprogram2=newMyProgram();program2.count++;newMyProgram().count++;System.out.println(MyProgram.count);}}
Standard input or outputOutput for Code listing 3.14
4
Test your knowledge

Question 3.11: Visit the OracleJavaDoc of the classjava.lang.Integer.

How many static fields does this class have?

Answer

4.

  • int MAX_VALUE,
  • int MIN_VALUE,
  • int SIZE and
  • Class<Integer> TYPE.
To learn how to overload and override a method, seeOverloading Methods and Constructors.


LiteralsJava Programming
Methods
API/java.lang.String
Retrieved from "https://en.wikibooks.org/w/index.php?title=Java_Programming/Methods&oldid=4342321"
Category:
Hidden category:

[8]ページ先頭

©2009-2025 Movatter.jp