- Object in Java
- Class in Java
- Instance Variable in Java
- Method in Java
- Example of Object and class that maintains the records
of student
- Anonymous Object
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:
- class <class_name>{
- data member;
- method;
- }
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.
- class Student1{
- int id;//data member (also instance variable)
- String name;//data member(also instance variable)
-
- public static void main(String args[]){
- Student1 s1=new Student1();//creating an object of Student
- System.out.println(s1.id);
- System.out.println(s1.name);
- }
- }
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.
|
- class Student2{
- int rollno;
- String name;
-
- void insertRecord(int r, String n){ //method
- rollno=r;
- name=n;
- }
-
- void displayInformation(){System.out.println(rollno+" "+name);}//method
-
- public static void main(String args[]){
- Student2 s1=new Student2();
- Student2 s2=new Student2();
-
- s1.insertRecord(111,"Karan");
- s2.insertRecord(222,"Aryan");
-
- s1.displayInformation();
- s2.displayInformation();
-
- }
- }
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.
|
- class Rectangle{
- int length;
- int width;
-
- void insert(int l,int w){
- length=l;
- width=w;
- }
-
- void calculateArea(){System.out.println(length*width);}
-
- public static void main(String args[]){
- Rectangle r1=new Rectangle();
- Rectangle r2=new Rectangle();
-
- r1.insert(11,5);
- r2.insert(3,15);
-
- r1.calculateArea();
- r2.calculateArea();
- }
- }
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:
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.
|
- class Calculation{
-
- void fact(int n){
- int fact=1;
- for(int i=1;i<=n;i++){
- fact=fact*i;
- }
- System.out.println("factorial is "+fact);
- }
-
- public static void main(String args[]){
- new Calculation().fact(5);//calling method with annonymous object
- }
- }
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.
|
- Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two objects
Let's see the example:
|
- class Rectangle{
- int length;
- int width;
-
- void insert(int l,int w){
- length=l;
- width=w;
- }
-
- 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:
- 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.
- //save as Student.java
- package com.javatpoint;
- public class Student{
- private String name;
-
- public String getName(){
- return name;
- }
- public void setName(String name){
- this.name=name
- }
- }
- //save as Test.java
- package com.javatpoint;
- class Test{
- public static void main(String[] args){
- Student s=new Student();
- s.setname("vijay");
- System.out.println(s.getName());
- }
- }
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:
- class A{}
- class B extends A{}
- 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.
- class Bike{
- void run(){System.out.println("running");}
- }
- class Splender extends Bike{
- void run(){System.out.println("running safely with 60km");}
-
- public static void main(String args[]){
- Bike b = new Splender();//upcasting
- b.run();
- }
- }
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.
- class Bank{
- int getRateOfInterest(){return 0;}
- }
-
- class SBI extends Bank{
- int getRateOfInterest(){return 8;}
- }
-
- class ICICI extends Bank{
- int getRateOfInterest(){return 7;}
- }
- class AXIS extends Bank{
- int getRateOfInterest(){return 9;}
- }
-
- class Test3{
- public static void main(String args[]){
- Bank b1=new SBI();
- Bank b2=new ICICI();
- Bank b3=new AXIS();
- System.out.println("SBI Rate of Interest: "+b1.getRateOfInterest());
- System.out.println("ICICI Rate of Interest: "+b2.getRateOfInterest());
- System.out.println("AXIS Rate of Interest: "+b3.getRateOfInterest());
- }
- }
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.
- class Bike{
- int speedlimit=90;
- }
- class Honda3 extends Bike{
- int speedlimit=150;
-
- public static void main(String args[]){
- Bike obj=new Honda3();
- System.out.println(obj.speedlimit);//90
- }
Output:90
Java Runtime Polymorphism with Multilevel
Inheritance
Let's see the simple example of Runtime
Polymorphism with multilevel inheritance.
- class Animal{
- void eat(){System.out.println("eating");}
- }
-
- class Dog extends Animal{
- void eat(){System.out.println("eating fruits");}
- }
-
- class BabyDog extends Dog{
- void eat(){System.out.println("drinking milk");}
-
- public static void main(String args[]){
- Animal a1,a2,a3;
- a1=new Animal();
- a2=new Dog();
- a3=new BabyDog();
-
- a1.eat();
- a2.eat();
- a3.eat();
- }
- }
Output: eating
eating fruits
drinking Milk
Try for Output
- class Animal{
- void eat(){System.out.println("animal is eating...");}
- }
-
- class Dog extends Animal{
- void eat(){System.out.println("dog is eating...");}
- }
-
- class BabyDog1 extends Dog{
- public static void main(String args[]){
- Animal a=new BabyDog1();
- a.eat();
- }}
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
- static binding (also known as early binding).
- 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.
- int data=30;
Here data variable is a type of int.
2) References have a type
- class Dog{
- public static void main(String args[]){
- Dog d1;//Here d1 is a type of Dog
- }
- }
3) Objects have a type
An object is an instance of
particular java class,but it is also an instance of its superclass.
|
- class Animal{}
-
- class Dog extends Animal{
- public static void main(String args[]){
- Dog d1=new Dog();
- }
- }
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
- class Dog{
- private void eat(){System.out.println("dog is eating...");}
-
- public static void main(String args[]){
- Dog d1=new Dog();
- d1.eat();
- }
- }
Dynamic binding
When type of the object is determined at run-time,
it is known as dynamic binding.
Example of dynamic binding
- class Animal{
- void eat(){System.out.println("animal is eating...");}
- }
-
- class Dog extends Animal{
- void eat(){System.out.println("dog is eating...");}
-
- public static void main(String args[]){
- Animal a=new Dog();
- a.eat();
- }
- }
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.
|
0 Comments