A Complete Java Classes Tutorial

Java class is a basic concept of object-oriented programming. Java is an object-oriented programming language, so Everything in java is associated with java classes. In this article, we will learn about java classes and we use the java classes with example programs.

Introduction

 
Java class is the basic building block of Java programming language. This article will explain Java classes and how Java classes work with code example. Java class is a template that is used to create objects, and to define data types and methods.Java class objects should have the basic class properties.
 

What are Java Classes?

 
Java class is the basic concept of object-oriented programming language. Java class is a user-defined template or blueprint where objects, data members and methods are defined and a set of instructions to build a specific type of object. The variables and methods of the same Java class are common for all the objects of the class.
In Java, the class keyword is used to define a Java class.
  

How is a Java Class defined?

  
Syntax:
  
class <class-name>
{
         [data members];
          
         [method];
}
 
Code Example:
  1. class MyClass   
  2. {  
  3.        int x = 5;         //data member;   
  4.        void fun()  //
  5.        {  
  6.               System.out.println("This is method");  
  7.        }     
  8. }  
 

What are the three major components of the Java class?

 

1) What are the class variables in Java?

 
Variable is a reserved memory location to hold a value. In other words, when we want to store any value and give it a name, that value takes a reserved space in memory and it’s called a variable.
 
Variable has any value, which is located in the memory.
 
Syntax
 
<access specifier > < data type > < variable name > = < value > ;
 

How we can declare the variable?

 
Code Example:
  1. int x ;     (int is a data type and x is a variable name).  
  2. int y;  
  3. int x , y;  
  4. int x = 4 , y = 5;  
  5. byte p = 65;  
  6. double pi = 3.1415;  
  7. char q = ‘s’ ; 

What are the different types of Variables?

 
Local Variable
 
A variable, which is declared inside any methods, constructors, and blocks is known as a local variable. Its scope is limited because it is used locally in the method. It is created after the creation of the method, constructor, block, a local variable is not visible to class and not accessed by the class.
 
For example, first, we create a class and a method. Afterward, declare two local variables, inside the method.
 
Code Example:
  1. public class LocalVariableExm {  
  2.     void message() {     //it is a method.  
  3.         int p;                     // declaration of Local Variable.  
  4.         int x = 10;      // declaration and initialization of Local Variable.  
  5.     }  
Static Variable
 
A static variable is a very important type of variable. We use static keyword with the variable. Hence, it’s called as a static variable. Static Variable is declared inside the class and outside the method, constructor and a block. The static variable belongs to the class, not an Object and it is stored in static memory. Its default value is 0 and we can call the static variable with its class name. Hence, there is no need to create an object in a static variable.
 
For example, first, we create a class and three variables outside the method, where two variables are static variables.
 
Code Example:
  1. public class StaticVariableExm {  
  2.     int p;  
  3.     static int q = 10;     // Static Variable with initialization  
  4.     static int r;              // Static Variable declaration  
  5.     void message() {  
  6.     }  
Instance Variable
 
An instance variable is declared inside the class but outside the method, constructor or block. It has the widest scope because it is globally visible to the whole class. It is created at the time of object creation. When the instance variable is created at that time, it takes space in the heap memory and it is called through the object and the default value is 0.
 
For example, first, we create a class and two instance variables outside the method.
 
Code Example:
  1. public class InstanceVariableExm {  
  2.     int a;      // Declaration of instance variable.  
  3.     int b = 10;  // Declaration and initialization of instance variable.  
  4.     void message() {  
  5.     }  

2) What is Constructor in Java?

 
A constructor is like a special method in Java, which is used to initialize an object of a Java class and Constructor is very important for every Java class and if we don't declare the constructor, the compiler creates a default constructor of a Java class.
 
A constructor must be the same name of a Java class. It does not have a return type.
 

What are the different types of constructors in Java?

 
In Java, Constructors can be divided into 3 types.
 
Default constructor
 
The default constructor has no parameter and if we do not declare a constructor, the compiler automatically creates a default constructor of that Java class.
 
Syntax
 
<class-name>()
{   } 
 
In the following program, we create a default constructor and print a msg as an output. The complete program is listed below.
  1. public class DefaultConstructor{    
  2.     DefaultConstructor() {  
  3.         System.out.println("This is default constructor example");  
  4.     }    
  5.     public static void main(String args[]) {  
  6.         DefaultConstructor d = new DefaultConstructor();  
  7.     }  
  8. }  
The output of the above code generates the following output.
 
 
The default constructor is used to provide the default value to the object like 0, null. The value depends on their type.
 
In the following program, we are not creating a constructor compiler provides it by default and provides default values. The complete program is listed below.
  1. public class DefaultConstructor2 {  
  2.     String name;  
  3.     String number;    
  4.     void display() {  
  5.         System.out.println(name + "," + number);  
  6.     }    
  7.     public static void main(String args[]) {  
  8.         DefaultConstructor2 t = new DefaultConstructor2();  
  9.         t.display();  
  10.     }  
The output of the following code generates the following output.
 
 
 
Parameterized constructor  
 
A constructor that has parameters is called a parameterized constructor in Java. We use the parameterized constructor when we want to provide different values to the distinct objects.
 
In the following program, we create a parameterized constructor with two parameters. The complete program is listed below. 
  1. public class ParameterizedConstructor {   
  2.     String name;  
  3.     int salary;    
  4.     ParameterizedConstructor(String n, int s) {  
  5.         name = n;  
  6.         salary = s;  
  7.     }    
  8.     void display() {  
  9.         System.out.println("Employee name is: " + name + "," + "and salary is : " + salary);  
  10.     }    
  11.     public static void main(String args[]) {  
  12.         ParameterizedConstructor e = new ParameterizedConstructor("Rohan"25000);  
  13.         e.display();  
  14.     }  
The output of the following code generates the following output.
 
 
 
Copy constructor
 
Copy constructor in Java class is a special type of constructor that takes the same class as an argument. A copy constructor is used to provide a copy of the specified object.
 
A copy constructor is used when we want to copy an object that is heavy to initiate. The complete program is listed below.
  1. public class CopyConstructor {    
  2.     int empid;  
  3.     public CopyConstructor(int b) {  
  4.         empid = b;  
  5.     }    
  6.     public void disp() {  
  7.         System.out.println("Employee id is :" + empid);  
  8.     }    
  9.     public static void main(String[] args) {  
  10.         CopyConstructor e = new CopyConstructor(1002);  
  11.         e.disp();  
  12.     }  
The output of the following code generates the following output.
 
 
 

3) What are the methods in the Java class?

 
A method is a block of code which only runs when it is called.  You can pass data, known as parameters, into a method. Methods are used to perform certain actions, and they are also known as functions.
 

Why We use Methods?

 
To reuse code: define the code once, and use it many times.
 

How to create a method in the Java class?

 
A method must be declared within a class. It is defined with the name of the method, followed by parentheses ().
 
Syntax
 
 class <class-name> {
    modifier dataType methodName () {
         //block of code to be executed     } }
//calling the method, from anywhere
className.methodName();
 
The complete program is listed below.
  1. public class MethodExample {    
  2.     static void myMethod() {  
  3.         System.out.println("Hello World!");  
  4.     }    
  5.     public static void main(String[] args) {  
  6.         myMethod();  
  7.     }  
The output of the following code generates the following output.
 
 

Methods with parameters

 
A parameter is a value that you can pass to a method in Java. Then the method can use the parameter as though it were a local variable initialized with the value of the variable passed to it by the calling method.
 

Types of Parameters:

 
Formal Parameter: A variable and its type as they appear in the prototype of the function or method.
 
Syntax:
 
function_name(datatype variable_name)
 
Actual Parameter: The variable or expression corresponding to a formal parameter that appears in the function or method call in the calling environment.
 
Syntax:
 
func_nme(variable name(s));
 
The complete program is listed below.
  1. public class ParameterizedMethodExample {    
  2.     static void myMethod(String name) {  
  3.         System.out.println(name);   
  4.     }    
  5.     public static void main(String[] args) {  
  6.         myMethod("CsharpCorner");  
  7.     }  
The output of the following code generates the following output.
 
 
Note: Java class declaration can contain objects, class members, access modifiers and constructors.
 

What are Objects in Java class?

 
An object is a basic concept of oops like java classes .objects like an entity, which has a state and behavior. Like car, mobile, pencil, cat, etc. As a car has states(it's color, name, and brand) and behavior(running). Objects are an instance of a java class and objects can be tangible and intangible.  Objects represent identity, which uniquely identifies it. Like one car number plate is a different number of other cars. so, it is the car's identity which is unique.
 
Objects represent the value of an object like car name, color, and brand. Objects represent the functionality of an object like a car's functionality is running.
 

How to create an object in Java class?

 
In Java new keyword is used to create an object.
 
Syntax:
 
<class-name> [object-name] = new <class-default-conetructor>
 
Example Code:
  1. class ObjectCreationExample   
  2. {           
  3.     public static void main(String args[]) {    
  4.   
  5.         ObjectCreationExample s = new ObjectCreationExample();   // create an object.    
  6.     }   
  7. }    

What are Data Members in Java class?

 
Data members are those whose memory space is created every time whenever an object is created. Data members are always meant for storing a specific value.
 
Syntax:
 
Data type v1,v2,v3,........vn;
  1. class DataMember  
  2. {  
  3.    int v1,v2,v3;  
  4.    float f1,f2;    
  5. }  
 

What are Access Modifiers in Java class?

 
The access Modifiers gives as the accessibility (scope) of a java class, data member, method, or a constructor. Access Modifiers helps us to set the level of access for our java class, variables, and methods.
  

What are the different types of access modifiers?

 
There are four types of Java access modifiers:
  1. public 
  2. private
  3. protected
  4. default
 
Modifiers Accessability
 
The following table lists access modifiers.
 
 Access Modifier 
 Access Modifiers  Keywords
 Public access modifier   public
 Private   private 
 Protected   protected
 Default  no keyword used
 
1) Public Access Modifier.
 
The public access modifier is accessible in all places. It has the widest scope among all other modifiers. Variables, methods, constructors, declared public within a public class is visible to any class in the java program. Hence, it doesn't matter whether these classes are in the same package or another package.
 
The complete program is listed below.
 
Step 1: First we create a Java class PublicExample in which we declare the method show():
  1. public class PublicExample {      
  2.     public void show() {    
  3.         System.out.println("Public access modifier example");   
  4.     }    
  5. }  
Step 2: Second we create a class PublicAccess in which we call the method of PublicExample class:
  1. public class PublicAccess {    
  2.         public static void main(String args[])    
  3.         {  
  4.             PublicExample obj = new PublicExample();    
  5.             obj.show();    
  6.         }  
  7.     }  
The output of the following code generates the following output: 
 
 
 
2) Private Access Modifier.
 
The private access modifier is accessible only within the class and not outside the class. Data members, methods or constructors declared are strictly controlled. Private access modifier can not be accessed anywhere outside the class.
 
A Java class can not be private except for the nested class.
The complete program is listed below.
 
Step 1: First we create a Java class PrivateExample in which we declare a private method run(): 
  1. public class PrivateExample{    
  2.     private void run() {  
  3.         System.out.println("Scooter is running");  
  4.     }  
  5. }  
Step 2: Second we create a class PrivateAccess in which we call the method of PrivateExample class:
  1. public class PrivateAccess{  
  2.         public static void main(String args[]) {  
  3.             PrivateExample s = new PrivateExample();            
  4.             s.run();  //compile time error
  5.         }  
  6.     }     
The output of the following code generates the following output.
 
 
 
Note: 
In this example, we create two Java classes PrivateExample and PrivateAccess. PrivateExample contains private method run(). If we want to access the private method outside the class, it gives the compile-time error.
  
3) Protected access modifier.
 
The protected access modifier is accessible within the package and outside the package also but through the inheritance only.
 
The protected access modifiers can be applied to the variables, methods, constructors but it can't apply on Java classes. Variables, methods, and constructors are declared protected in a parent class can be accessed bt child class in other packages. 
 
The complete program is listed below.
 
Step 1: First we create a public Java class ProtectedExample in package pack1 in which we declare a protected method display().
  1. package pack1;    
  2. public class ProtectedExample{  
  3.     protected void display() {  
  4.         System.out.println("Protected access modifier example");    
  5.     }  
  6. }  
Step 2: Second we create a public Java class ProtectedAccess in package pack2 in which we call the method of ProtectedClass class.
  1. package pack2;        
  2. import pack1.*;        
  3. public class ProtectedAcces extends ProtectedClass{        
  4.     public static void main(String args[]) {        
  5.         ProtectedAccess p = new ProtectedAccess();        
  6.         p.display();    
  7.     }    
  8. }    
The output of the above code generates the following output.
 
 
  
4) Default access modifier
 
When we don't use any modifier, it is treated as a default access modifier in Java. The default access modifier is only accessible only within the package.
 
Any Java class, variable, method, and constructor which is the default access modifier is accessible only by the classes in the same package. The default access modifier is not used for variables and methods within an interface. 
The complete program is listed below.
 
Step 1: First we create a default Java class named DefaultExample in package pack1 which we declare a method msg():
  1. package pack1;    
  2.  class DefaultExample {   
  3.     void msg() {  
  4.         System.out.println("Default access modifier example");  
  5.     }  
  6. }  
Step 2: Second we create a default Java class DefaultAccess package named pack2 in which we call the method of DefaultClass class:
  1. package pack2;    
  2. import pack1.*;   
  3.  class DefaultAccess{  
  4.         public static void main(String args[]) {  
  5.             DefaultClass d = new DefaultClass();// compile time error  
  6.             r.msg(); // compile time error  
  7.         }    
  8.     }  
The output of the above code generates the following output.
 
 
  
Note:
In this example, we create two Java classes DefaultClass and DefaultAccess. DefaultClass is a default Java class, so that can't be accessed by outside the package. So, it gives the compile-time error.
 

How many types of classes in Java?

 
There are 3 major types of Java classes.
 
1. Abstract Java Classes
2. Nested Java Classes
3. Final Java Classes
4. Singletan Java class 
 

1) What is Abstract class in Java?

 
Before Abstract Java classes we should know about Abstraction in Java. 
 

Abstraction

 
In Java, Abstraction is a procedure to hide the implementation details from the user and provides only functionality to the user. For example, in calculator when we want to calculate some data, we use its keys but we don't know, how it works internally.    
So, when we use abstract keyword with any class, this class is called an abstract Java class. It provides only important things to the user and hides the internal process from the user. 
  1. Abstract Java class can have abstract methods and non-abstract methods.
  2. If a class has an abstract method, this class must be an abstract Java class.
  3. If we want to use an abstract class, it needs to be extended and its methods implemented.
  4. If we extend an abstract Java class, we have to provide the implementation for all abstract methods in it. 
The complete program is listed below.
 
Step 1: First we create an abstract Java class named Employee in which we declare an abstract method named work().
  1. abstract class AbstractClass {  
  2.     abstract void work();  
Step 2: Second we create a public Java class named WomanEmployee in which we access the method work() and its implementation is given by WomanEmployee class.
  1. public class AbstractClass2 extends AbstractClass{    
  2.     void work() {  
  3.             System.out.println("Abstract class Example");  
  4.         }  
  5.         public static void main(String args[]) {  
  6.             AbstractClass p = new AbstractClass2();  
  7.             p.work();  
  8.         }  
  9.     }
The output of the following code generates the following output.
 
 

2) What are the Nested Java classes?

 
The Java programming language allows you to define a class within another class. We use the nested class to logically group of the class and interface in one place It can be more readable maintainable and can access all the members of the outer class(public, private, protected).
 
Syntex 
 
class OuterClass{
...... 
      class InnerClass{ 
 //Nested Java class
}  
 
Advantages of nested class in java
 
1. Nested Java classes show a special type of relationship, it can access all the members of the outer class including private.
2. Nested Java classes mainly used to build up our program more readable and maintainable because it logically groups the classes and interfaces in one place.
3. Nested classes require less code to write.
 

Types of nested classes.

 
1. Non-static Nested Classes
2. Static Nested Classes 
 
Non-static nested classes are also known as inner classes in Java.
 
 

Member inner class

 
Member inner class is created inside the class but outside the method. It is a non-static inner class. Creating a member inner class in Java is simple. We need to write a class inside the class. The inner class can be private and once we declare an inner class as a private, it can not be accessed from an object outside the outer class.
 
Syntax 
 
class Outer{
     class Inner
      {
           // Member inner class 
      } 
 
The complete program is listed below.
  1. public class MemberClassExample {  
  2.     private int data = 30;    
  3.     class MemberClassInner {  
  4.         void msg() {  
  5.             System.out.println("data is " + data);  
  6.         }  
  7.     }    
  8.     public static void main(String args[]) {  
  9.         MemberClassExample obj = new MemberClassExample();  
  10.         MemberClassExample.MemberClassInner in = obj.new MemberClassInner();  
  11.         in.msg();  
  12.     }  
The output of the following code generates the following output.
 
 
 
Note
In the example, we create a display() method in member inner class which access the private data member of the outer class.
 

Anonymous inner class

 
The classes which have no name are called anonymous inner classes in java. It must be used when if we have to override the method of the class and interface.
 
We can declare and initiate them at the same time. The complete program is listed below.
  1. public class AnonoymousClassExample {    
  2.     public static void main(String[] args) {  
  3.         AnonoymousDemo a = new AnonoymousDemo() {  
  4.             public void message() {  
  5.                 System.out.println("Anonymous Inner Class Example");  
  6.             }  
  7.         }; // anonymous class body closes here  
  8.         //a contains an object of anonymous subclass of AnonoymousClassExample.  
  9.         a.message();  
  10.     }  
  11. }    
  12. class AnonoymousDemo {  
  13.     public void message() {  
  14.         System.out.println("Message");  
  15.     }  
  16. }  
The output of the following code generates the following output.
 
 
 

Local inner class

 
A Java class that is created inside the method is called local inner class Java and if we want to call the methods of the local inner class then we must initiate this class inside the method.
 
The complete program is listed below.
  1. public class LocalInnerClassExample {  
  2.     private int data = 30;    
  3.     void display() {  
  4.         class Local {  
  5.             void msg() {  
  6.                 System.out.println(data);  
  7.             }  
  8.         }  
  9.         Local l = new Local();  
  10.         l.msg();  
  11.     }   
  12.     public static void main(String args[]) {  
  13.         LocalInnerClassExample obj = new LocalInnerClassExample();  
  14.         obj.display();  
  15.     }  
 
The output of the following code generates the following code.
 
 
 

Static nested class

 
When a static class is created inside another Java class, it is called a static nested class. A static class can not access non-static data members and methods. It can access static members of the outer class whether it is private, public or protected and it can only be accessed through outer class name.
 
Syntax
 
class Outer{
       static NestedClass {
               // Static Nested class          
 
The complete program is listed below.
  1. public class StaticNestedClassExample {  
  2.     static int age = 30;    
  3.     static class StaticClassAccess {  
  4.         void display() {  
  5.             System.out.println("Employee age is " + age);  
  6.         }  
  7.     }    
  8.     public static void main(String args[]) {  
  9.         StaticNestedClassExample.StaticClassAccess a = new StaticNestedClassExample.StaticClassAccess();  
  10.         a.display();  
  11.     }  
The output of the following code generates the following output.
 
 
  

3) Final Java class 

 
When we use the final with any class, it is called a final Java class. A final class can't be inherited. If any class is declared final then all its methods implicitly get declared as final. 
 
Syntax 
final class <class-name>{
       // code 
 
The complete program is listed below.
  1. final  class FinalClassExample {    
  2. }   
  3. class Manager extends FinalClassExample {  // Compile time error  
  4.     void work() {  
  5.         System.out.println("working hard");  
  6.     }   
  7.     public static void main(String args[]) {  
  8.         Manager m1 = new Manager();  
  9.         m1.work();  
  10.     }  
  11. }  
The output of the following code generates the following output.
 
 
 
Note:
In this example, we create a final Java class named FinalClassExample and another Java class named Manager and we try to inherit the final class but the program gives a compile-time error.
 

4) Singleton Java Class

 
In object-oriented programming, a singleton class is a class that can have only one object at a time. Singletons often control access to resources, such as database connections or sockets. The intention is to create a single instance of an object of classes which are expensive to create during runtime and try to reuse the same object. Such objects are mainly immutable.
 
Some basics rules required to implement a singleton class.
 
1. A constructor should be private.
2. Declare a static variable object of the class.
3. Declare a static method to return the instance.
 
The complete program is listed below.
 
Step 1. First, we create a singleton class named SingletonClassExample.
  1. public class SingletonClassExample {  
  2.     private static SingletonClassExample singleton = new SingletonClassExample();  
  3.   
  4.     public static SingletonClassExample getInstance() {  
  5.         return singleton;  
  6.     }  
  7.   
  8.     protected static void demoMethod() {  
  9.         System.out.println("demoMethod for singleton");  
  10.     }  
  11. }  
Step 2. Second we create a public class named SingleTonDemo for access the singleton class.
  1. public class SingletonDemo {  
  2.     public static void main(String[] args) {  
  3.         SingletonClassExample tmp = SingletonClassExample.getInstance();  
  4.         tmp.demoMethod();  
  5.     }  
  6. }  
The output of the following code generates the following output.
 
 
 

Summary

 
In this tutorial, we learned about various Java classes and how to use them in our java program.