In Java, a class is a template or blueprint for creating objects. A class defines the properties and behaviors of the objects it creates, and specifies the data type of those objects.
Here's an example of a simple class in Java:
t refero:lautturi.compublic class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } public void setName(String name) { this.name = name; } public void setAge(int age) { this.age = age; } }
In this example, the Person
class has two private instance variables, name
and age
, and four public methods, getName
, getAge
, setName
, and setAge
, which are used to access and modify the values of the instance variables.
To create an object of the Person
class, you can use the new
operator and the class constructor:
Person person = new Person("John", 30);
You can then use the object to access and modify its properties and behaviors:
System.out.println(person.getName()); // Outputs: "John" person.setAge(31); System.out.println(person.getAge()); // Outputs: 31
Classes in Java can have a variety of members, such as instance variables, methods, constructors, inner classes, and more. You can also use inheritance and polymorphism to create relationships of objects.