Object and Class in Java

  1. Object in Java
  2. Class in Java
  3. Instance Variable in Java
  4. Method in Java
  5. Example of Object and class that maintains the records of student
  6. Anonymous Object
JAVA


In this page, we will learn about java objects and classes. In object-oriented programming technique, we design a program using objects and classes.
Object is the physical as well as logical entity whereas class is the logical entity only.
Object in Java
An entity that has state and behavior is known as an object e.g. chair, bike, marker, pen, table, car etc. It can be physical or logical (tengible and intengible). The example of integible object is banking system.
An object has three characteristics:
  • state: represents data (value) of an object.
  • behavior: represents the behavior (functionality) of an object such as deposit, withdraw etc.
  • identity: Object identity is typically implemented via a unique ID. The value of the ID is not visible to the external user. But,it is used internally by the JVM to identify each object uniquely.
For Example: Pen is an object. Its name is Reynolds, color is white etc. known as its state. It is used to write, so writing is its behavior.

Object is an instance of a class. Class is a template or blueprint from which objects are created. So object is the instance(result) of a class.


Class in Java
A class is a group of objects that has common properties. It is a template or blueprint from which objects are created.
A class in java can contain:
  • data member
  • method
  • constructor
  • block
  • class and interface
Syntax to declare a class:
  1. class <class_name>{  
  2.     data member;  
  3.     method;  
  4. }  
Simple Example of Object and Class
In this example, we have created a Student class that have two data members id and name. We are creating the object of the Student class by new keyword and printing the objects value.
  1. class Student1{  
  2.  int id;//data member (also instance variable)  
  3.  String name;//data member(also instance variable)  
  4.   
  5.  public static void main(String args[]){  
  6.   Student1 s1=new Student1();//creating an object of Student  
  7.   System.out.println(s1.id);  
  8.   System.out.println(s1.name);  
  9.  }  
  10. }  
Output:0 null
    


Instance variable in Java
A variable that is created inside the class but outside the method, is known as instance variable.Instance variable doesn't get memory at compile time.It gets memory at runtime when object(instance) is created.That is why, it is known as instance variable.
Method in Java
In java, a method is like function i.e. used to expose behaviour of an object.
Advantage of Method
  • Code Reusability
  • Code Optimization
new keyword
The new keyword is used to allocate memory at runtime.


Example of Object and class that maintains the records of students
In this example, we are creating the two objects of Student class and initializing the value to these objects by invoking the insertRecord method on it. Here, we are displaying the state (data) of the objects by invoking the displayInformation method.
  1. class Student2{  
  2.  int rollno;  
  3.  String name;  
  4.   
  5.  void insertRecord(int r, String n){  //method  
  6.   rollno=r;  
  7.   name=n;  
  8.  }  
  9.   
  10.  void displayInformation(){System.out.println(rollno+" "+name);}//method  
  11.   
  12.  public static void main(String args[]){  
  13.   Student2 s1=new Student2();  
  14.   Student2 s2=new Student2();  
  15.   
  16.   s1.insertRecord(111,"Karan");  
  17.   s2.insertRecord(222,"Aryan");  
  18.   
  19.   s1.displayInformation();  
  20.   s2.displayInformation();  
  21.   
  22.  }  
  23. }  
Output:111 Karan
       222 Aryan
    
As you see in the above figure, object gets the memory in Heap area and reference variable refers to the object allocated in the Heap memory area. Here, s1 and s2 both are reference variables that refer to the objects allocated in memory.


Another Example of Object and Class
There is given another example that maintains the records of Rectangle class. Its exaplanation is same as in the above Student class example.
  1. class Rectangle{  
  2.  int length;  
  3.  int width;  
  4.   
  5.  void insert(int l,int w){  
  6.   length=l;  
  7.   width=w;  
  8.  }  
  9.   
  10.  void calculateArea(){System.out.println(length*width);}  
  11.   
  12.  public static void main(String args[]){  
  13.   Rectangle r1=new Rectangle();  
  14.   Rectangle r2=new Rectangle();  
  15.   
  16.   r1.insert(11,5);  
  17.   r2.insert(3,15);  
  18.   
  19.   r1.calculateArea();  
  20.   r2.calculateArea();  
  21. }  
  22. }  
Output:55
       45    


What are the different ways to create an object in Java?
There are many ways to create an object in java. They are:
  • By new keyword
  • By newInstance() method
  • By clone() method
  • By factory method etc.
We will learn, these ways to create the object later.


Annonymous object
Annonymous simply means nameless.An object that have no reference is known as annonymous object.
If you have to use an object only once, annonymous object is a good approach.
  1. class Calculation{  
  2.   
  3.  void fact(int  n){  
  4.   int fact=1;  
  5.   for(int i=1;i<=n;i++){  
  6.    fact=fact*i;  
  7.   }  
  8.  System.out.println("factorial is "+fact);  
  9. }  
  10.   
  11. public static void main(String args[]){  
  12.  new Calculation().fact(5);//calling method with annonymous object  
  13. }  
  14. }  
Output:Factorial is 120


Creating multiple objects by one type only
We can create multiple objects by one type only as we do in case of primitives.
  1. Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two objects  
Let's see the example:
  1. class Rectangle{  
  2.  int length;  
  3.  int width;  
  4.   
  5.  void insert(int l,int w){  
  6.   length=l;  
  7.   width=w;  
  8.  }  
  9.   


  10.  void calculateArea(){System.out.println(length*width);}  
  
Object class in Java
The Object class is the parent class of all the classes in java bydefault. In other words, it is the topmost class of java.
The Object class is beneficial if you want to refer any object whose type you don't know. Notice that parent class reference variable can refer the child class object, know as upcasting.
Let's take an example, there is getObject() method that returns an object but it can be of any type like Employee,Student etc, we can use Object class reference to refer that object. For example:
  1. Object obj=getObject();//we don't what object would be returned from this method  
The Object class provides some common behaviours to all the objects such as object can be compared, object can be cloned, object can be notified etc.
Methods of Object class
The Object class provides many methods. They are as follows:

Method
Description
public final ClassgetClass()
returns the Class class object of this object. The Class class can further be used to get the metadata of this class.
public int hashCode()
returns the hashcode number for this object.
public boolean equals(Object obj)
compares the given object to this object.
protected Object clone() throws CloneNotSupportedException
creates and returns the exact copy (clone) of this object.
public String toString()
returns the string representation of this object.
public final void notify()
wakes up single thread, waiting on this object's monitor.
public final void notifyAll()
wakes up all the threads, waiting on this object's monitor.
public final void wait(long timeout)throws InterruptedException
causes the current thread to wait for the specified milliseconds, until another thread notifies (invokes notify() or notifyAll() method).
public final void wait(long timeout,int nanos)throws InterruptedException
causes the current thread to wait for the specified miliseconds and nanoseconds, until another thread notifies (invokes notify() or notifyAll() method).
public final void wait()throws InterruptedException
causes the current thread to wait, until another thread notifies (invokes notify() or notifyAll() method).
protected void finalize()throws Throwable
is invoked by the garbage collector before object is being garbage collected.
We will have the detailed learning of these methods in next chapters.


Encapsulation in Java
Encapsulation in java is a process of wrapping code and data together into a single unit, for example capsule i.e. mixed of several medicines.
We can create a fully encapsulated class in java by making all the data members of the class private. Now we can use setter and getter methods to set and get the data in it.
The Java Bean class is the example of fully encapsulated class.
Advantage of Encapsulation in java
By providing only setter or getter method, you can make the class read-only or write-only.
It provides you the control over the data. Suppose you want to set the value of id i.e. greater than 100 only, you can write the logic inside the setter method.
Simple example of encapsulation in java
Let's see the simple example of encapsulation that has only one field with its setter and getter methods.
  1. //save as Student.java  
  2. package com.javatpoint;  
  3. public class Student{  
  4. private String name;  
  5.    
  6. public String getName(){  
  7. return name;  
  8. }  
  9. public void setName(String name){  
  10. this.name=name  
  11. }  
  12. }  
  1. //save as Test.java  
  2. package com.javatpoint;  
  3. class Test{  
  4. public static void main(String[] args){  
  5. Student s=new Student();  
  6. s.setname("vijay");  
  7. System.out.println(s.getName());  
  8. }  
  9. }  
Compile By: javac -d . Test.java
Run By: java com.javatpoint.Test
Output: vijay

Polymorphism in Java

Polymorphism in java is a concept by which we can perform a single action by different ways. Polymorphism is derived from 2 greek words: poly and morphs. The word "poly" means many and "morphs" means forms. So polymorphism means many forms.
There are two types of polymorphism in java: compile time polymorphism and runtime polymorphism. We can perform polymorphism in java by method overloading and method overriding.
If you overload static method in java, it is the example of compile time polymorphism. Here, we will focus on runtime polymorphism in java.

Runtime Polymorphism in Java

Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an overridden method is resolved at runtime rather than compile-time.
In this process, an overridden method is called through the reference variable of a superclass. The determination of the method to be called is based on the object being referred to by the reference variable.
Let's first understand the upcasting before Runtime Polymorphism.

Upcasting

When reference variable of Parent class refers to the object of Child class, it is known as upcasting. For example:
  1. class A{}  
  2. class B extends A{}  
  1. A a=new B();//upcasting  

Example of Java Runtime Polymorphism

In this example, we are creating two classes Bike and Splendar. Splendar class extends Bike class and overrides its run() method. We are calling the run method by the reference variable of Parent class. Since it refers to the subclass object and subclass method overrides the Parent class method, subclass method is invoked at runtime.
Since method invocation is determined by the JVM not compiler, it is known as runtime polymorphism.
  1. class Bike{  
  2.   void run(){System.out.println("running");}  
  3. }  
  4. class Splender extends Bike{  
  5.   void run(){System.out.println("running safely with 60km");}  
  6.   
  7.   public static void main(String args[]){  
  8.     Bike b = new Splender();//upcasting  
  9.     b.run();  
  10.   }  
  11. }  
Output:running safely with 60km.

Real example of Java Runtime Polymorphism

Consider a scenario, Bank is a class that provides method to get the rate of interest. But, rate of interest may differ according to banks. For example, SBI, ICICI and AXIS banks could provide 8%, 7% and 9% rate of interest.
Note: It is also given in method overriding but there was no upcasting.
  1. class Bank{  
  2. int getRateOfInterest(){return 0;}  
  3. }  
  4.   
  5. class SBI extends Bank{  
  6. int getRateOfInterest(){return 8;}  
  7. }  
  8.   
  9. class ICICI extends Bank{  
  10. int getRateOfInterest(){return 7;}  
  11. }  
  12. class AXIS extends Bank{  
  13. int getRateOfInterest(){return 9;}  
  14. }  
  15.   
  16. class Test3{  
  17. public static void main(String args[]){  
  18. Bank b1=new SBI();  
  19. Bank b2=new ICICI();  
  20. Bank b3=new AXIS();  
  21. System.out.println("SBI Rate of Interest: "+b1.getRateOfInterest());  
  22. System.out.println("ICICI Rate of Interest: "+b2.getRateOfInterest());  
  23. System.out.println("AXIS Rate of Interest: "+b3.getRateOfInterest());  
  24. }  
  25. }  
Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9

Java Runtime Polymorphism with data member

Method is overridden not the datamembers, so runtime polymorphism can't be achieved by data members.
In the example given below, both the classes have a datamember speedlimit, we are accessing the datamember by the reference variable of Parent class which refers to the subclass object. Since we are accessing the datamember which is not overridden, hence it will access the datamember of Parent class always.

Rule: Runtime polymorphism can't be achieved by data members.

  1. class Bike{  
  2.  int speedlimit=90;  
  3. }  
  4. class Honda3 extends Bike{  
  5.  int speedlimit=150;  
  6.   
  7.  public static void main(String args[]){  
  8.   Bike obj=new Honda3();  
  9.   System.out.println(obj.speedlimit);//90  
  10. }  
Output:90

Java Runtime Polymorphism with Multilevel Inheritance

Let's see the simple example of Runtime Polymorphism with multilevel inheritance.
  1. class Animal{  
  2. void eat(){System.out.println("eating");}  
  3. }  
  4.   
  5. class Dog extends Animal{  
  6. void eat(){System.out.println("eating fruits");}  
  7. }  
  8.   
  9. class BabyDog extends Dog{  
  10. void eat(){System.out.println("drinking milk");}  
  11.   
  12. public static void main(String args[]){  
  13. Animal a1,a2,a3;  
  14. a1=new Animal();  
  15. a2=new Dog();  
  16. a3=new BabyDog();  
  17.   
  18. a1.eat();  
  19. a2.eat();  
  20. a3.eat();  
  21. }  
  22. }  
Output: eating
        eating fruits
        drinking Milk

Try for Output

  1. class Animal{  
  2. void eat(){System.out.println("animal is eating...");}  
  3. }  
  4.   
  5. class Dog extends Animal{  
  6. void eat(){System.out.println("dog is eating...");}  
  7. }  
  8.   
  9. class BabyDog1 extends Dog{  
  10. public static void main(String args[]){  
  11. Animal a=new BabyDog1();  
  12. a.eat();  
  13. }}  
Output: Dog is eating
Since, BabyDog is not overriding the eat() method, so eat() method of Dog class is invoked.

Static Binding and Dynamic Binding

Connecting a method call to the method body is known as binding.
There are two types of binding
  1. static binding (also known as early binding).
  2. dynamic binding (also known as late binding).

Understanding Type

Let's understand the type of instance.

1) variables have a type

Each variable has a type, it may be primitive and non-primitive.
  1. int data=30;  
Here data variable is a type of int.

2) References have a type

  1. class Dog{  
  2.  public static void main(String args[]){  
  3.   Dog d1;//Here d1 is a type of Dog  
  4.  }  
  5. }  

3) Objects have a type

An object is an instance of particular java class,but it is also an instance of its superclass.
  1. class Animal{}  
  2.   
  3. class Dog extends Animal{  
  4.  public static void main(String args[]){  
  5.   Dog d1=new Dog();  
  6.  }  
  7. }  
Here d1 is an instance of Dog class, but it is also an instance of Animal.

static binding

When type of the object is determined at compiled time(by the compiler), it is known as static binding.
If there is any private, final or static method in a class, there is static binding.

Example of static binding

  1. class Dog{  
  2.  private void eat(){System.out.println("dog is eating...");}  
  3.   
  4.  public static void main(String args[]){  
  5.   Dog d1=new Dog();  
  6.   d1.eat();  
  7.  }  
  8. }  

Dynamic binding

When type of the object is determined at run-time, it is known as dynamic binding.

Example of dynamic binding

  1. class Animal{  
  2.  void eat(){System.out.println("animal is eating...");}  
  3. }  
  4.   
  5. class Dog extends Animal{  
  6.  void eat(){System.out.println("dog is eating...");}  
  7.   
  8.  public static void main(String args[]){  
  9.   Animal a=new Dog();  
  10.   a.eat();  
  11.  }  
  12. }  
Output:dog is eating...
In the above example object type cannot be determined by the compiler, because the instance of Dog is also an instance of Animal.So compiler doesn't know its type, only its base type.


Post a Comment

0 Comments