Start networking and exchanging professional insights

Register now or log in to join your professional community.

Follow

How many ways a class can be referenced in JAVA?

user-image
Question added by vishal vishal , Associate Professor , Poornima College of Engineering
Date Posted: 2014/03/11
Mohd shahnawaz khan
by Mohd shahnawaz khan , Associate Project , Cognizant Technology Solution

Object : is an instance of the class.

Instance is a run time entity which allocates memory during execution of a program.

Class can be referenced by4 ways in java

1. Class reference

2. Interface

3. Array

4. enum

 

There are four different ways to create objects in java:

A. Using new keywordThis is the most common way to create an object in java. Almost99% of objects are created in this way.

MyObject object =newMyObject();

B. Using Class.forName()If we know the name of the class & if it has a public default constructor we can create an object in this way.

MyObject object =(MyObject)Class.forName("subin.rnd.MyObject").newInstance();

C. Using clone()The clone() can be used to create a copy of an existing object.

MyObject anotherObject =newMyObject();MyObject object = anotherObject.clone();

D. Using object deserializationObject deserialization is nothing but creating an object from its serialized form.

ObjectInputStream inStream =newObjectInputStream(anInputStream );MyObject object =(MyObject) inStream.readObject();

 

 

To make it a bit a clear for everybody to understadn:

Class: is the blue print of an object

Object: is an instance of the class.

 

For example if we have a class called car we can have an object for BMW car

Car BM=new("BMW");

another object of Toyota Car

Car Toy=new("Toyota");

 

In Java specifically you can't manipulate the objects directly you can access by it the reference which is the identifier E.g. BM or Toy. 

 

This was just clarification but to answer your question properly let me give you an example 

 

String s; String S now doesn't reference anything

 

String s="Hello"; S is a reference for the the word "Hello" but doesn't create new String object so if you have String s2="Hello"; s==s2 is true. so s and s2 is is the same reference.

 

String s3=new String("Hello"); will create a new object referenced by s3

String s4=new String("Hello"); will create a new object referenced by s4 

So they are two different objects with two different references in memory thus s3=s4 is FALSE

 

I hope this help you if anything is unclear let me know

 

 

 

More Questions Like This

Do you need help in adding the right keywords to your CV? Let our CV writing experts help you.