Java Class and Objects
In Java, a class is a blueprint for creating objects. It defines the properties and behavior of an object of that class. An object is an instance of a class. You can think of a class as a template or a cookie cutter, and an object as the cookie that is created from the cookie cutter.
Here's an example of a simple class in Java:
public class Person { // properties private String name; private int age; // constructor public Person(String name, int age) { this.name = name; this.age = age; } // methods public void sayHello() { System.out.println("Hello, my name is " + name + " and I am " + age + " years old."); } }
In this example, the Person
class has two properties: name
and age
. It also has a constructor that takes a name
and an age
and sets the corresponding properties of the object. Finally, it has a method called sayHello
that prints a greeting that includes the name and age of the person.
To create an object of this class, you can use the new
keyword and call the constructor with the appropriate arguments:
Person john = new Person("John", 30);
This creates a new Person
object with the name "John" and age 30 and assigns it to the variable john
. You can then call the sayHello
method on the object to print the greeting:
john.sayHello(); // prints "Hello, my name is John and I am 30 years old."
You can create multiple objects of the same class with different values for their properties. Each object is independent and can have its own values for the properties and behavior defined in the class.