Java Classes

Class is a user defined blueprint. In Object oriented programming, Class is like a template which are providing certain rules and regulation to implement a class. This implemented class is capable to generate associate objects. Which are use the properties and method of this implemented class.

In simple word, Class is an user defined data type which are capable to store properties and method, That properties and method are protected by outside of class only access this properties by class objects or inherited class. This accessibility is based on user define class access rules.

Generally class is two type in Java Programming. First is predefined which are provided by system when we are install JDK in our system. Second is user defined which is implemented by programmer. Goal of this post providing complete overview how to create a custom class In Java Programming and how to use their properties.

Defining a custom Java Class

class keyword are used to implement a new class in Java programming. After class keyword mention the custom name of class. And inside a curly braces are define class properties and methods. That is called body of class.

[modifiers] class ClassName{
//define Properties
//define Methods
}

Modifiers is describe the behaviour of class, There are mainly three types (public, private,protected). Properties are normally representing data fields of class. The type of this data can be primitive and user define. Method is function of this class. The name of class should be start of capital letter. See the valid class names.

class Student{}
class StudentRecord{}
class Employee{}
class SalesManage{}
//etc

Lets define a properties and method of Student class.

// Class example in java
public class Student
{
	// Define properties
	public String name;
	public String enrollment;
	public int age;
	// Constructor of student class
	public Student(String name, String enrollment, int age)
	{
		// Assign the value of class properties
		this.name = name;
		this.enrollment = enrollment;
		this.age = age;
	}
	// Display student records
	public void showRecord()
	{
      	// Display value of all instance variables
		System.out.println("Name : " + name);
		System.out.println("Enrollment : " + enrollment);
		System.out.println("Age : " + age);
	}
	public static void main(String[] args)
	{
		// Create  objects of class student
		Student first = new Student("Roy", "198CE12", 17);
		Student second = new Student("Willy", "148ME12", 15);
      
		System.out.println("First Student Records");
		first.showRecord(); // Execute class method showRecord
		System.out.println("\nSecond Student Records");
		second.showRecord(); // Execute class method showRecord
	}
}

Output

First Student Records
Name : Roy
Enrollment : 198CE12
Age : 17

Second Student Records
Name : Willy
Enrollment : 148ME12
Age : 15

Defining Properties of class

In this example include lot of new thing. First top section are include class properties. In this example defined only three.

//Define properties
String name;
String enrollment;
int age;

There are no limitation to define properties fields. Normally include common properties which are use by class objects. After that define class constructors.

Defining constructor

constructors are play important role in object oriented programming. That is like a function there name is similar to class name and they are not return any values.

//Constructor of student class
Student(String name,String enrollment,int age){
    //Assign the value of class properties
    this.name=name;
    this.enrollment=enrollment;
    this.age=age;
}

When constructor parameter argument and class method properties name are same then (this) keyword are indicates class properties. We can create any number of constructor in same class using different paramter list and data values.The main role of class constructor are they are provide initial values of class object. And they are automatically execute when create a associative objects. Learn more About Constructors in Class Constructor post.

Defining class methods

That is similar to defining a normal function. but the speciality of class method are they are execute by class object or will possible to call inside the other method of class. When object is execute its class method, method can use this object properties. In this example defined one Student class method showRecord().

//Display student records
public void showRecord(){
    System.out.println("Name : "+ name);
    System.out.println("Enrollment : "+enrollment);
    System.out.println("Age : "+age);
}

Creating objects of class

This is main part of class because every properties and method are surrounding by class objects. When we create an object of a class Then class is set the properties and method of this create object. In above example are create two objects of student class.

//Create  objects of class student
Student first=new Student("Roy","198CE12",17);
Student second=new Student("Willy","148ME12",15)

When we create two object of Student Class.Then class are provide their properties to this created objects. Look at that, new operator are create memory of class instance in heap area. That are return the reference of newly created instance. We can use of this instance access the properties of class.

Create class objects

Observe that both object are have unique properties of student class, and those properties can be use by class methods or using of objects. We can directly access public properties by object.

Object are consist of identifier, state and behavior.

Identifier : This is an name of object which are declare by class name. Note that there is not possible to declare two or more same name variable within same scopes.

Behavior: That means what kind of operation are perform object by using class methods.

State: That are deal with class properties. When change the properties values, that means change the object state.

Class variables (Objects)

Class name are used to create a reference type of variable(object) that are capable to hold the instance reference of class. Let see an example.

// Create class variables
public class Demo
{
	// Instance variable
	int x, y;
	public Demo(int x, int y)
	{
		this.x = x;
		this.y = y;
	}
	public void display()
	{
		System.out.println("X: " + x + " Y : " + y);
	}
	public static void main(String[] args)
	{
		// Create a class variable
		Demo referenceHolder = null; // Set initial null
		// Assigning reference of class instance
		referenceHolder = new Demo(3, 4);
		// Access the properties of instance
		referenceHolder.display();
		// Assigning reference of class instance
		referenceHolder = new Demo(10, 5);
		// Access the properties of instance
		referenceHolder.display();
	}
}

Output

X: 3 Y : 4
X: 10 Y : 5

In this example created two instance of a Demo class. "referenceHolder" variable are holding the reference of this instance. But here this is an single variable that can hold the reference of single instance at a time. That way when next created instance reference is assigning to this variable. Then previously store reference are change to new reference.

Assign the new instance reference

First create reference are not store by any other class variable. So that reason this allocate memory are removed of heap area. In case class variable are assign the null then this are cannot use class method, until when not assign new instance or other class variable to this.

Similar way there are possible to assign the reference of same instance in two different variable. See this example.

class Demo
{
	int x, y;
	public Demo(int x, int y)
	{
		this.x = x;
		this.y = y;
	}
	public void display()
	{
		System.out.println("X: " + x + " Y : " + y);
	}
	public static void main(String[] args)
	{
		// Create two variable of class
		Demo objOne = null, objTwo = null; // Set initial null
		// Assigning reference of class instance
		objOne = new Demo(10, 20);
		objTwo = objOne; // Assign the reference to an instance
		// Access the properties of instance
		objOne.display();
		objTwo.display();
	}
}
Assign same instance reference to the two variable

Output

X: 10 Y : 20
X: 10 Y : 20

If In case in this example objOne are change the value of instance then that change is reflect to on objTwo variable. because both are share the same memory instance.

Passing a object to a method

Function is capable to accept values and reference of an object. In this section views examples how to pass an object to function.

// Pass object in a method
public class BankAccount
{
	// Class field
  	// Instance variable
	double amount;
	int accountNo;
	public BankAccount(int accountNo, double amount)
	{
		this.accountNo = accountNo;
		this.amount = amount;
	}
	// Display amount of two different Account
	public void checkBalance(BankAccount parent)
	{
		System.out.println("Child Account Balance : " + amount);
		System.out.println("Parent Account Balance : " + parent.amount);
	}
	public static void main(String[] args)
	{
		BankAccount childAccount = new BankAccount(102, 10003.2);
		BankAccount parentAccount = new BankAccount(101, 123312.42);
		// Pass the parentAccount object to checkBalance function
		childAccount.checkBalance(parentAccount);
	}
}
Passing a object to a method

Output

Child Account Balance : 10003.2
Parent Account Balance : 123312.42

In this example checkBalance function are work two object. One is pass by parameter list and one is it self which object are call this function. Here this keyword is represent calling object properties.

Java Inner Class

When define one class inside another class this is called nested class. Java are support two types of nested class. First is static nested class and other is non-static class.

Static Nested class: Static nested class are defined by static keyword. This class are capable to access the static properties of outer class.

//Example of static nested class
public class OuterClass{
    //Static data of Outer Class
    private static int data;
    public OuterClass(int data){
        this.data=data;

    }
    //Define nested static class
    public static class NestedClass{
        //NestedClass class properties
        int x;
        NestedClass(int x){
            this.x=x;
        }
        public void display(){
            System.out.println("Inner X : "+x);
            //Access static data of outside
            System.out.println("Outer data  : "+data);
        }
    }
    public static void main(String[] args){
        //Make OuterClass  object
        OuterClass outer=new OuterClass(90);
        //Make NestedClass class object
        NestedClass inner=new NestedClass(100);
        inner.display();
    }
}
Create instance of nested class

Output

Inner X : 100
Outer data  : 90

In this example static data field of outer class is accessible inside the inner class method. Both class can use the properties of static field. static nested class is member of outer class. Outside of the class, There are possible to use nested class in by help of outer-class name.

//Example of static nested class
class OuterClass{
    //Define nested static class
    public static class NestedClass{
        //NestedClass class properties
        int x;
        NestedClass(int x){
            this.x=x;
        }
        public void display(){
            System.out.println("Inner X : "+x);
        }
    }

}
class Operate{
     public static void main(String[] args){
        
        //Make NestedClass class object
        OuterClass.NestedClass inner=new OuterClass.NestedClass(100);
  
        inner.display();
    }
}

Output

Inner X : 100

Non-Static Class: There are two variants are available of non-static class like local inner class and Anonymous inner classes.

//Example of Local inner class
class OuterClass{
    private int x;
    static int y;
    public OuterClass(int x,int y){
        this.x=x;
        this.y=y;
    }

    //Define nested class
    public class InnerClass{
        public void display(){
            //Access outer class properties
            System.out.println("x = " + x); 
            System.out.println("y = " + y); 
        }
    }
}
public class Operate{
     public static void main(String[] args){

        OuterClass info=new OuterClass(10,20);
        //Make InnerClass class object
        OuterClass.InnerClass inner=info.new InnerClass();
        inner.display();
    }
}

Output

x = 10
y = 20

Anonymous Inner class

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

        Thread runCode = new Thread(){
            public void run(){
                System.out.print("Inner code");
            }
        };
        runCode.start();
        System.out.println("Outer code");
    }
}

Output

Outer code
Inner code

Basic Operation

In this section given few special operation which are used some specific purpose in class.

Get the name of class by object

//get the name of class by object
class Execution{
  public int data;
  public static void main(String[] args) {
    Execution obj=new Execution();
    System.out.println(obj.getClass().getSimpleName());
  }
}

Output

Execution

Invoke execution of method when that is an string from.

Assume that we are create a module which are work in our project. This module goal is to test all exist class functionality by this module. Means this module are access all class functionality. This module are work on some parameter values, That are accept two parameter values. Class name and method name which are providin by dynamically. This module are execute that method when class and method are exist in project.

//invoke execution of method when that is an string from
import java.lang.reflect.*;
class Execution{

   public void message(){
      System.out.println("Message Function Are Work");
   }
   public void moduleTest(String className,String methodName){

        try {
      
            //Find class name
            Class<?> classSet = Class.forName(className);
            //provide two parameters of getDeclaredMethod() 
            //First is name of function
            //Second is optional to overview of parameter data class
            Method method = classSet.getDeclaredMethod(methodName); //no second parameter

            //Make object
            Object obj = classSet.newInstance();

            method.invoke(obj);


        }catch (Exception  e) { 
            System.out.println(e);
        }

   }
   public static void main(String[] args){
    
        Execution operates = new Execution();
        operates.moduleTest("Execution","message");
   }
}

Output

Message Function Are Work

In this example object class methods are used to find the class and execute class method. When in case we are need to execute parameterized function then we can do this way.

//invoke execution of method when that is an string from
import java.lang.reflect.*;
class Execution{
   public void testTwo(int age,String name){
        System.out.println("Age :"+age);
        System.out.println("Name :"+name);
   }  
    public static void main(String[] args){
    
        try {
      
                //Find class name
                Class<?> classSet = Class.forName("Execution");
                //provide two parameters of getDeclaredMethod() 
                //First is name of function
                //Second is optional to overview of parameter data class
                Method method = classSet.getDeclaredMethod("testTwo", int.class,String.class);
                //make object
                Object obj = classSet.newInstance();
                method.invoke(obj,21,"Foo");
            }catch (Exception  e){ 
                System.out.println(e);
            }
    }
}

Output

Age :21
Name :Foo
Create instance of class by class name

See this example view that there are three type of instance are created in this program to execute unknown class method.



Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved