Читать книгу OCP Oracle Certified Professional Java SE 17 Developer Study Guide - Jeanne Boyarsky - Страница 64

Fields and Methods

Оглавление

Java classes have two primary elements: methods, often called functions or procedures in other languages, and fields, more generally known as variables. Together these are called the members of the class. Variables hold the state of the program, and methods operate on that state. If the change is important to remember, a variable stores that change. That's all classes really do. It's the programmer's job to create and arrange these elements in such a way that the resulting code is useful and, ideally, easy for other programmers to understand.

The simplest Java class you can write looks like this:

1: public class Animal { 2: }

Java calls a word with special meaning a keyword, which we've marked bold in the previous snippet. Throughout the book, we often bold parts of code snippets to call attention to them. Line 1 includes the public keyword, which allows other classes to use it. The class keyword indicates you're defining a class. Animal gives the name of the class. Granted, this isn't an interesting class, so let's add your first field.

1: public class Animal { 2: String name; 3: }

The line numbers aren't part of the program; they're just there to make the code easier to talk about.

On line 2, we define a variable named name. We also declare the type of that variable to be String. A String is a value that we can put text into, such as "this is a string". String is also a class supplied with Java. Next we can add methods.

1: public class Animal { 2: String name; 3: public String getName() { 4: return name; 5: } 6: public void setName(String newName) { 7: name = newName; 8: } 9: }

On lines 3–5, we define a method. A method is an operation that can be called. Again, public is used to signify that this method may be called from other classes. Next comes the return type—in this case, the method returns a String. On lines 6–8 is another method. This one has a special return type called void. The void keyword means that no value at all is returned. This method requires that information be supplied to it from the calling method; this information is called a parameter. The setName() method has one parameter named newName, and it is of type String. This means the caller should pass in one String parameter and expect nothing to be returned.

The method name and parameter types are called the method signature. In this example, can you identify the method name and parameters?

public int numberVisitors(int month) { return 10; }

The method name is numberVisitors. There's one parameter named month, which is of type int, which is a numeric type. Therefore, the method signature is numberVisitors(int).

OCP Oracle Certified Professional Java SE 17 Developer Study Guide

Подняться наверх