Classes and methods in Java are the basic concepts for creating programs: 1) Classes are templates that define object data and behavior. 2) A method is a block of code that performs a specific operation or calculation. 3) Methods belong to classes, and objects use data in the class by calling methods.
Classes and Methods in Java
Classes and methods are two basic concepts in the Java programming language. A class is a template that defines the data and behavior of an object. Methods are blocks of code that perform specific operations or calculations.
Class
Methods
The relationship between classes and methods
Example
<code class="java">class Student { private String name; private int age; public void setName(String name) { this.name = name; } public String getName() { return name; } public void setAge(int age) { this.age = age; } public int getAge() { return age; } } public class Main { public static void main(String[] args) { Student student = new Student(); student.setName("John"); student.setAge(20); System.out.println("Name: " + student.getName()); System.out.println("Age: " + student.getAge()); } }</code>
In this example, the Student
class defines a field named name
and a field named age
. It also defines four methods: setName
, getName
, setAge
, and getAge
. The
Main
class creates a Student
object student
. It then sets the object's field values using the setName
and setAge
methods. Finally, it obtains the object's field values using the getName
and getAge
methods.
The above is the detailed content of What are classes and methods in java. For more information, please follow other related articles on the PHP Chinese website!