Objects and Classes in Java

Objects and Classes in Java

Objects and Classes in Java:

In Java, an object is an instance of a class. A class is a blueprint or template for creating objects. It defines the attributes and methods that the objects of that class will have.

To create a class in Java, you use the class keyword followed by the name of the class. Here’s an example of a simple class:

				
					public class Person {
    // attributes
    String name;
    int age;

    // methods
    public void sayHello() {
System.out.println("Hello, my name is " + name + " and I'm " + age + " years old.");
    }
}

				
			

In this example, we’ve created a Person class with two attributes (name and age) and one method (sayHello()). The sayHello() method prints a greeting message that includes the person’s name and age.

To create an object of the Person class, you use the new keyword followed by the name of the class, like this:

				
					Person john = new Person();
				
			

This creates a new Person object called john. You can then set the values of the name and age attributes using dot notation, like this:

				
					john.name = "John";
john.age = 25;

				
			

Finally, you can call the sayHello() method on the john object to print the greeting message:

				
					john.sayHello();
				
			

This will output the following message:

Hello, my name is John and I’m 25 years old.

In summary, a class is a blueprint for creating objects in Java. Objects are instances of classes and have their own set of attributes and methods. You create objects using the new keyword followed by the name of the class, and you can access the attributes and methods of an object using dot notation.

 

Join To Get Our Newsletter
Spread the love