Everything about Classes & Objects in Java

Views: 125   

Class

Class is a blueprint/ template/ prototype that defines a new data type. From this class you can create Objects of that type.
Following is the sample code that defines a class with some data & behaviour.

public class Person {
    String name;
    int age;

    public void sayHello() {
        System.out.println("Hello");
    }
}

Object

Object is an instance of Class, you can create Objects using new operator. new operator allocates memory for the Object you are creating and returns the reference to it.
Following code shows you how to create Objects for a Class

public class CreatingObjects {
    public static void main(String[] args) {

        Person person1 = new Person();
        Person person2 = new Person();

        person1.name = "p1";
        person2.name = "p2";

        person1.sayHello();
        person2.sayHello();
    }
}
On By