ابدأ بالتواصل مع الأشخاص وتبادل معارفك المهنية

أنشئ حسابًا أو سجّل الدخول للانضمام إلى مجتمعك المهني.

متابعة

How many ways a class can be referenced in JAVA?

user-image
تم إضافة السؤال من قبل vishal vishal , Associate Professor , Poornima College of Engineering
تاريخ النشر: 2014/03/11
Mohd shahnawaz khan
من قبل 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

 

 

 

المزيد من الأسئلة المماثلة