Curriculum
In Java, a class is a blueprint or template for creating objects. It defines the attributes and behaviors that an object of that class will have. An object, on the other hand, is an instance of a class that has specific values for its attributes and can perform actions according to its defined behaviors.
To define a class in Java, you use the keyword “class” followed by the name of the class, like this:
public class MyClass { // class members }
Here, “public” is an access modifier that specifies the class is visible to other classes and packages, and “MyClass” is the name of the class. Within the curly braces, you define the class members, such as fields, constructors, and methods.
Here’s an example of a class that represents a person with a name and age:
public 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; } }
This class has two private fields, name and age, and a constructor that takes two parameters to initialize these fields. It also has four methods to access and modify the name and age fields.
To create an object of this class, you use the “new” keyword and the class name, like this:
Person person1 = new Person("John", 25);
This creates a new Person object with the name “John” and age 25, and assigns it to the variable “person1”. You can then access and modify the object’s attributes using its methods, like this:
System.out.println(person1.getName()); // prints "John" person1.setAge(30); System.out.println(person1.getAge()); // prints 30
Classes and objects are used in Java to organize and encapsulate data and behavior into reusable and modular units of code. They allow you to define complex data structures and models, and create multiple instances of them with different values. They also enable you to implement encapsulation, inheritance, and polymorphism, which are essential concepts in object-oriented programming.