Classes in JAVA

Classes in JAVA

Java is counted in pure object-oriented languages, and that’s why the whole code of Java depends on some class to execute. In programming class is a user defined data type which has some resemblance with structures, but they have some additional functionalities like every class has some attribute functions. The class can be inherited and can also inherit some interface, and there are also different access specifiers for the class to limit its access, its attributes, and functions.


access_specifier  class  class_name {

\ body…



complete class syntax and usage
Complete class syntax and usage

In the above syntax access, specifiers are three possible types in Java

  • Default
  • Public
  • Private
  • Protected

Syntax Rules of a Class:

The class is the keyword that indicates it’s class. class keyword is used to initialize a class. 

The name of the class has some rules, as the name of variables like digits are not allowed as the first letter and instead of _ and $, all other special characters are also not allowed to be the first character of the class name.

Parts of class:

A class in Java has three parts, and all these three parts are not compulsory we skip any one according to our need.

  • Constructor
  • Attributes
  • Functions


The constructor in Java has the same name as a class name. A single class may have many constructors which are overloaded on each others by different numbers of parameters. A constructor is the first method which is called when an object is created.

There are two types of constructors.

  1. Default Constructor (No Argument Constructor)
  2. User Defined (Constructor with Arguments / Overloaded Constructor / Parameterized)

See more about Overloading and overriding

A constructor has no data type, but may have access specifiers.



Attributes are same as variables, but they are bound to some class.


Functions in class are same as simple functions in programs, but they are called using object of the class.

Example of attributes and functions in Java:

In the above example is used to access the id of the internal class, this may be helpful if some other variable with the same name come in class from some other source i.e. Some object or from the parent class.

The default access specifier of attributes and functions in Java is the interdefault, which means it is accessible anywhere in the package, but we have to write every time public, protected or private while declaring the attribute.



Members of the class can only be accessed through its object in required scope. The object is created by the new keyword and calls the constructor of the class.


class_name  object_name  =  new    class_name () ;


As we have a Person class above, so to create its object the code is:

To access attributes and function of class . or -> is used.;