Java Objects & Classes

Java is an object-oriented programming language and classes are fundamental part of any java program. Individual objects are created from these classes. Below is a java class example.

public class Employee{

int empAge;
String empName;

public void setEmpAge(int age){

}

public int getEmpAge(){

}

}

Java Objects

The java objects are similar to real world objects like human, cat, car etc. Each object has their own states and behaviors. The state of an object in java is stored in fields and behaviors are implemented through methods. The communication between objects are done through methods.

Local Variables

Variables which are defined inside method or constructor body are called local variables. The variable can be accessed inside that method and are destroyed when method completed.

Instance variables

Variables which are defined in class body but outside any method or constructor are instance variables. They are initialized when class is instantiated and can be accessed in method or constructor of that class.

Class Variables

Variables which are defined inside class body but outside any method or constructor with static keyword are called class variables.

Java Constructors

In java each class has a constructor method. If you do not write a constructor method in your class java compiler will automatically bind the default constructor with your class. The constructor method should have same name as of class name. When object of a class is created constructor will be invoked. There can be multiple constructors in same class.

Constructor Example

public class Employee{

public Employee(String name){

// constructor code goes here.

}

}

Creating Objects

Objects are created from classes. ‘new’ keyword is used to create object of a class. See the example below.

public class Employee{

public Employee(String empName){

System.out.println(“Employee Name is :” + empName );

}

public static void main(String []args){

// Creating an object newEmployee
Employee newEmployee = new Employee(“Jhon”);

}

}

Leave a Reply

Your email address will not be published. Required fields are marked *