Classes and Objects in java - Class consist of blocks, constructor, variables, methods, inner classes and inner interfaces


Object in java
  • Objects are real-world entity.
  • Objects may have different state and behavior.
  • Example - In world different animals have different names like Lion, Goat, they eat different food, have different skin colour, height, weight etc.
Lion eat flesh, Goat eat grass.

Class in java

  • Classes are blueprint/ template,
  • objects are created from classes.


A Class basically consists of  >
class MyClass { //class name
   public MyClass() {} //constructor
  
   private String name; //instance variable/ member variable
   public void setName(String name) { //method
          this.name = name;
   }
}


A typical Class can consist of following >
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
class MyClass { //class name
   /* Static initialization block */
   static {
          System.out.println("static block");
   }
   /*Non-Static block (Instance initialization block)*/
   {
          System.out.println("non-static block");
   }
   public MyClass() { //constructor
          super();
   }
  
   private int instanceVar; //instance variable/ member variable
   private static int staticVar; //static variable/ class variable
   public void instanceMethod() { //instance method
          this.instanceVar=2;
          class LocalInnerClass {} //LocalInnerClass
          MyClass obj=new MyClass(){}; //Anonymous inner class
   }
  
   public static void staticMethod() { //static method
   }
   class InnerClass{} //inner class
   static class StaticNestedClass {} //StaticNestedClass
   interface NestedInterface{} //nested interface
   static interface staticNestedInterface{} //static nested interface
}

Blocks>


Variables>
Instance and
Static variables

Methods>
Instance and
Static methods

(Method definition formation) -
Method definition is formed by using following 5 terms -

Note : Return type may be void, in that case method doesn’t return anything.

      public String food(int x) throws Exception {
          // Method body
          return null;
   }


Optionally, we may add static keyword, after or before public.



Inner Classes>

Inner class/ nested class,

static nested class,

local inner class and

anonymous inner class in java



nested interface>

nested interface

static nested interface



Can use Super & this keywords


access modifiers - We may use different access modifiers with all variables, methods, constructor, inner class like private, package-private(Default), protected and public.


Must read related concepts : Method overloading and




Program 1 to create Class and Objects >
We have Animal class (as used in Program), let’s understand this line -
Animals animal1 = new Animals();

We could divide above line into two lines -
Animals animal1; //animal1 is reference variable, currently it is pointing to null.
animal1 = new Animals(); //new animals() creates object and allocates memory.


There are 3 steps for creating objects from classes and initializing them.

STEP1 : Declaration of referencer variable:

Animals animal1;

animal1 is reference variable, currently it is pointing to null, till now no memory has been allocated, till now no real world animal exists.

STEP 2: Instantiation of class - create object using new keyword.

animal1 = new Animals();

new Animals() calls constructor and creates object and allocates memory, and animal1 is reference variable which is pointing to that newly created object.


STEP 3: Initialization of class - assigning values to member variables

animal1.setName("lion");
animal1.setFood("flesh");

Diagram  >


So, what we understand is >
Class >
    • Class Animals is blueprint/ template (it does not hold any memory),
    • object animal1 is created from class Animals. (it holds memory)

Object >
  • Object animal1 is real-world entity.

  • Object animal1 have different state and behaviour- it’s name is lion and eat flesh.
  • Object animal2 have different state and behaviour- it’s name is goat and eat grass.


Let’s code Program 1 to create Animal Class and Objects.
class Animals {
   public Animals() {} //constructor
  
   private String name; //instance variable/ member variable
   private String food;
   public String getName() { //method
          return name;
   }
   public void setName(String name) {
          this.name = name;
   }
  
   public String getFood() {
          return food;
   }
   public void setFood(String food) {
          this.food = food;
   }
}
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class ClassObjectTest{
   public static void main(String[] args) {
          Animals animal1 = new Animals(); //creating object
          animal1.setName("lion");
          animal1.setFood("flesh");
          Animals animal2 = new Animals();
          animal2.setName("goat");
          animal2.setFood("grass");
          System.out.println("--animal1---");
          System.out.println(animal1.getName());
          System.out.println(animal1.getFood());
          System.out.println("\n--animal2---");
          System.out.println(animal2.getName());
          System.out.println(animal2.getFood());
         
   }
}
/*OUTPUT
--animal1---
lion
flesh
--animal2---
goat
grass
*/




Program 2 to create Class and Objects >
We have Employees class (as used in Program), let’s understand this line -
Employees emp1 = new Employees();

We could divide above line into two lines -
Employees emp1; //emp1 is reference variable, currently it is pointing to null.
emp1 = new Employees(); //new Employees() creates object and allocates memory.

Employees emp1;
emp1 is reference variable, currently it is pointing to null, till now no memory has been allocated, till now no real world employee exists.

emp1 = new Employees();
new Employees() calls constructor and creates object and allocates memory, and emp1 is reference variable which is pointing to that newly created object.


So, what we understand is >
Class >
  • Class Employees is blueprint/ template (it does not hold any memory),
  • object emp1 is created from class Employees. (it holds memory)

Object
  • Object emp1 is real-world entity.

  • Object emp1 have different state and behaviour- it’s name is ankit and id is 1.
  • Object emp2 have different state and behaviour- it’s name is sam and id is 2.


Let’s code Program 2 to create Employees Class and Objects.
class Employees {
   public Employees() {} //constructor
  
   private int id;
   private String food;
   public int getId() {
          return id;
   }
   public void setId(int id) {
          this.id = id;
   }
  
   public String getFood() {
          return food;
   }
   public void setFood(String food) {
          this.food = food;
   }
}
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class ClassObjectTest{
   public static void main(String[] args) {
          Employees emp1 = new Employees();
          emp1.setId(1);
          emp1.setFood("ankit");
          Employees emp2 = new Employees();
          emp2.setId(2);
          emp2.setFood("sam");
          System.out.println("--emp1---");
          System.out.println(emp1.getId());
          System.out.println(emp1.getFood());
          System.out.println("\n--emp2---");
          System.out.println(emp2.getId());
          System.out.println(emp2.getFood());
         
   }
}
/*OUTPUT
--emp1---
1
ankit
--emp2---
2
sam
*/



RELATED LINKS>

Interface in java - Multiple inheritance, Marker interfaces, When to use interface practically, 12 features


Abstract class in java - When to use abstract class or interface practically, 10 features


Constructor in java - Constructor chaining, access modifiers with constructors, constructor overloading, exception thrown, constructors are not inherited


Labels: Core Java
eEdit
Must read for you :