What is a class, in Java?

Basics of Object Oriented Concepts.
A class is basic unit of Object Oriented Languages, and hence in Java.
A class can have or a class encapsulates
1.Data Members or properties or fields
2.Constructors
3.Member Methods or Methods

What are properties, of a class

Data members or Properties is the data required by the member methods, to operate. Data members is one of the way, in which constructors and methods of a class, can share data. A class can have zero or more properties. A property can be of primitive type or user defined type.

What are methods, of a class

Methods is the behavior exposed by this class to external world, using which objects or other classes can interact with this class. A class can have zero or more methods.

What is object, in Java?

An object is an instance of a class. And the process of creating an object, from a class, is called instantiation.

Difference between class and object

To compare, class and object with real world scenarios, a class is just like a bottle moulder, which moulds bottles into a shape. And an object is just like a bottle, which got moulded from moulder.

Just like a moulder can mould any number of bottles, a class can generally have any number of objects, except in special cases, like singleton

What is Constructor, in Java?

A Constructor is a special method, of a class, used to initialize an object.

Below is an example of a class, creating object of a class, and invoking methods of class.

class Test1
{
	int i,j; //data members or member variables

	Test1()//constructor
	{
	i = 20;
	j = 11;

	System.out.println("Test1() Constructor");
	}

	void add() //member methods
	{
	int k; //local variable i..e not a member variable of Test1 class
	//NOTE: k cannot be accessed from object of Test1 class
	k = i+j;
	System.out.println("Add Result is:"+k);
	}

	void sub()
	{
	int l = i-j;
	System.out.println("Sub Result is:"+l);
	}
}

public class ClassDemo {
//execution starts from here
public static void main(String args[])
{
	Test1 obj; //declaring object reference
	obj=new Test1(); //creating object of Test1 class
	obj.add(); //invoking add() method of Test1 class, using object obj

	obj.sub();
}
}

You may also like to read:
invoke constructor from another constructor
what is abstract keyword

3 thoughts on “What is a class, in Java?”

Leave a Reply