• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Object Referencing

 
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Consider the foll eg:-
I] class print{
public static void print(long arr[]){
for (int i =0; i< arr.length; i++)
System.out.println(arr[i]);
}
public static void print(long arr){
System.out.println(arr);
}
public static void main(String args[]){
int i[] = {1,2,2,3,4};
print(i); //line 1
int t = 3;
print(t);
}
}
Why does line marked line 1 not compile..If I want to pass an int array , how do I pass it to the function print??..

II] class a
{
};
class b extends a
{
};
class print{
public static void print(b arr[]){
for (int i =0; i< arr.length; i++)
System.out.println(arr[i]);
}
public static void main(String args[]){
//b arr[] = {new b(), new b()};
// print(arr);
Object arr[] = {new b(), new b()};
print((b[])arr);
}
}

If the variable arr is of any other type other than b (say of type a(superclass) or of type Object), even on casting it to an array of objects of type b , it gives a ClassCastExceptionError? Can anyone please explain why and the solution to the same??
Can anyone tell em of some good eg�s or notes on Object referencing, conversion & casting.I read from rHE , but am confused.

 
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
i[] is an array so the compiler is not going to cast it to an long array type
U can accept in Object type of array B'cze array itself is an object
where as long is a primitive type but not an Object type
Even if u try to accept it an Wrapper type of array then also it throw an compile time exception
This overcome these type of problems Pls go through JLS
if u r preparing for SCJP
For threads reffer Core Java2
For class Reffer JLS
& Remaining Reffer RHS
ravi_g9@yahoo.com
 
Ranch Hand
Posts: 275
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
<HTML>
Pooja,

The rule for assignment of arrays of primitive types is that the contents have to be
of the same type.


<PRE>
class Base { }
class Derived extends Base {}
public class Test{
public static void aMethod(int b[])
{
}
public static void main(String args[])
{
long l[] = {5,5};
int i[] = {5,5};
l = i; // not okay
Base b[] = { new Base() , new Base()};
Derived d[] = { new Derived() , new Derived()};
b = d; // okay
}
}

</PRE>
Most people assume that the same rule for assignment of arrays of objects apply to array of
primitives . It is not so.
Rgds - Sahir
</HTML>
 
Sheriff
Posts: 5782
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
'Pooja K'
PROPER NAMES ARE NOW REQUIRED!!
Read this post for more details.
Javaranch appreciates your cooperation to comply with the official naming policy.
Ajith
 
Ranch Hand
Posts: 101
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Pooja:
You cannot pass an int array as an argument to a method that expects a long array argument. Passing an array Argument is NOT similar to argument passing using primitives. So, for your code to work fine, you must have a print method that takes int array as an argument (in your example a static method).
 
Ranch Hand
Posts: 108
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
lets start from scratch

class A{}
class B extends A{}
class C extends B{}

A temp1=new B(); //line 1
B temp2=(B) temp1; //line2
if temp1 not having object of type b there will be exception thrown.

however if
A temp1=new C();

there will be no exception in line 2 as object of subclass is also object of super class
even if temp1 is null no exception will be thrown.
now come to ur case in case of array always take care of array object not elements
following quote from JLS:
"A variable of array type holds a reference to an object. Declaring a variable of array type does not create an array object or allocate any space for array components. It creates only the variable itself, which can contain a reference to an array."

int sr[];//no memeory
int sr=new int[]//object created

if u write
A arr[]={new ??,new??};
irrespective of type of member the array object will be type A[]
i.e if u write
A arr[]={new B(),new B()};
or
A arr[]={new B(),new A()};

ur array object is type of A[]
now whwn ever u try to cast it to subclass

B ar[]=(B[])arr;
there will be no error at compile time coz what compiler whant is that classes of array should be in class hiearchy.
at runtime there will be exception thrown coz array type of arr is A[] and u r casting to B[].it must be B[] or its subclass
compare this to above to line 2 above if in line1 u have temp1=new A();
u will get Exception at run time reason is as above object must be B or C

now come the real point how to do it???
see
A arr[]=new B[2];
now object of array Type is B[].
but u cannot have now like
arr[0]=new A(); //line 3
There will be ArrayStoreException will be thrown.
coz array is now of type B[] and that cannot hold Superclass object.however it can always have object of
subclass.
i.e
arr[0]=new C();

Following Lines from JLS chapter 10 u can see effect in line 3
"An assignment to an element of an array whose type is T[], where T is a reference type, is checked at run-time to ensure that the value assigned can be assigned to the actual element type of the array, where the actual element type may be any reference type that is assignable to T. "
At compile time, an assignment to an element of A is checked to make sure that the value assigned is a A. But since arr holds a reference to an array of B, the assignment is valid only if the type of the value assigned at run-time is, more specifically, a B.

Following are some points regarding this topic
1) If ur casting array of primitive type they must be same.
2)Array of Refernce type can be converted to both Object and Object[];
A ar[]={new A(),new B()};
Object oops[]=ar
Object oop=ar;
3)Array of Primitive can be converted to only Object not Object[];

int ar[]={4,5};
Object oops[]=ar;//Error compile time
Object oop=ar;

to retrive Whole array
int b[]=(int [])oop;//intialize br to similar to ar
to retrive single element
int b=((int[])oop)[1]; //intialize b to 5
Hope this will Help:-)
 
Let's go to the waterfront with this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic