473,321 Members | 1,622 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,321 software developers and data experts.

Class Casting.

77
What is the restrictions in castng...
Inthe following prog if i uncomment c = p.
It throws,

Casting.java:28: incompatible types
found : test.Parent
required: test.Child

is it possible to cast both up and down the hierarchy ?

Expand|Select|Wrap|Line Numbers
  1. package test;
  2.  
  3. class Parent {
  4.     public static void print(){
  5.     System.out.println("Parent");
  6.     }
  7. }
  8.  
  9. class Child extends Parent {
  10.     public static void print()
  11.     {
  12.         System.out.print("Child");
  13.     }
  14. }
  15.  
  16. class GrandChild extends Child {
  17.     public static void print()
  18.     {
  19.         System.out.print("GrandChild");
  20.     }
  21. }
  22. public class Casting {
  23.     public static void main(String args[]){
  24.         Parent p = new Parent();
  25.         Child c = new Child();
  26.         GrandChild g = new GrandChild();
  27.         p = c;
  28. //        c = p;
  29.         System.out.println("Compiles Good");        
  30.     }
  31. }
  32.  
Thanks,
P.Jerald
Nov 2 '07 #1
7 2923
r035198x
13,262 8TB
What is the restrictions in castng...
Inthe following prog if i uncomment c = p.
It throws,

Casting.java:28: incompatible types
found : test.Parent
required: test.Child

is it possible to cast both up and down the hierarchy ?

Expand|Select|Wrap|Line Numbers
  1. package test;
  2.  
  3. class Parent {
  4.     public static void print(){
  5.     System.out.println("Parent");
  6.     }
  7. }
  8.  
  9. class Child extends Parent {
  10.     public static void print()
  11.     {
  12.         System.out.print("Child");
  13.     }
  14. }
  15.  
  16. class GrandChild extends Child {
  17.     public static void print()
  18.     {
  19.         System.out.print("GrandChild");
  20.     }
  21. }
  22. public class Casting {
  23.     public static void main(String args[]){
  24.         Parent p = new Parent();
  25.         Child c = new Child();
  26.         GrandChild g = new GrandChild();
  27.         p = c;
  28. //        c = p;
  29.         System.out.println("Compiles Good");        
  30.     }
  31. }
  32.  
Thanks,
P.Jerald
No you cannot cast both up and down the inheritance hierarchy.

I'm sure you can play around on the compiler to find out which casts are allowed. Also take note of the difference between casts that fail at compile time and those that fail at run time.
Nov 2 '07 #2
JosAH
11,448 Expert 8TB
No you cannot cast both up and down the inheritance hierarchy.
You can always cast upwards, towards the root which is the Object class. You
can only cast downwards if the object at hand actually *is an* instance of the
target class you want to cast to or a subclass thereof. A Parent most certainly
is not a Child in the example, hence the cast failure.

kind regards,

Jos
Nov 2 '07 #3
r035198x
13,262 8TB
You can always cast upwards, towards the root which is the Object class. You
can only cast downwards if the object at hand actually *is an* instance of the
target class you want to cast to or a subclass thereof. A Parent most certainly
is not a Child in the example, hence the cast failure.

kind regards,

Jos
Yep, I suppose my post ended up all wrong. I wanted to convey that it's not correct to say that "it's always possible to cast both ways" and that the OP is best left to discover those that work and those that do not work ...
Nov 2 '07 #4
pjerald
77
A Parent most certainly is not a Child in the example, hence the cast failure.

kind regards,

Jos
Thanks, jos and r035198x.

Regards,
P.Jerald.
Nov 2 '07 #5
pjerald
77
You can always cast upwards, towards the root which is the Object class. You
can only cast downwards if the object at hand actually *is an* instance of the
target class you want to cast to or a subclass thereof. A Parent most certainly
is not a Child in the example, hence the cast failure.


kind regards,

Jos


So, We cannot cast a parent class to its child. Am i wright ?
Nov 5 '07 #6
JosAH
11,448 Expert 8TB
So, We cannot cast a parent class to its child. Am i wright ?
Yep, true; here's an example:

Expand|Select|Wrap|Line Numbers
  1. public class MeansOfTransportation { ... }
  2. public class CompactCar extends MeansOfTransportation { ... }
  3. public class Submarine extends MeansOfTransportation { ... }
  4. ...
  5. Submarine yellow= new Submarine();
  6. MeansOfTransportation mot= (MeansOfTransportation)yellow; // valid up-cast
  7. CompactCar c= (CompactCar)mot; // invalid down-cast
  8.  
As you can see a submarine clearly isn't a compact car.

kind regards,

Jos
Nov 5 '07 #7
heat84
118 100+
You need an explicit cast from parent class to child class but no need for explicit class from child to parent to child so if you do this there will be no error

#
public static void main(String args[]){
#
Parent p = new Parent();
#
Child c = new Child();
#
GrandChild g = new GrandChild();
#
p = c;
#
c = (Child)p;
#
System.out.println("Compiles Good");
#
}
Nov 12 '07 #8

Sign in to post your reply or Sign up for a free account.

Similar topics

1
by: ofer | last post by:
Hi, I am working with the beta version of the new .net framework (Whidbey) and I encountered a problem with serialization that did'nt exist in the .net 2003 the situation is like this : I have...
1
by: Vic | last post by:
Hi, in VB.NET there is the following code: Friend htProvidedProperties As New Hashtable() Private Class TextboxValidatorProvidedProperties Public DataType As DataTypeConstants Public...
7
by: Cybertof | last post by:
Hello, In the code below, is there a shortcut not to use the temp var CurrEmployee ? I would like to use something like "if (Employee)MyArrayList.Name" but don't know the syntax....
2
by: Peter | last post by:
Hello Thank for reviewing this question. I would like to know why I am getting a syntax error. For example public class public class B : public
2
by: ofer | last post by:
Hi, I am working with the beta version of the new .net framework (Whidbey) and I encountered a problem with serialization that did'nt exist in the .net 2003 the situation is like this : I have...
0
by: Michel | last post by:
Hi all! I created a new class, which has the UserControl as a base class. Now I want to create an instance of my new class, by creating a new usercontrol and casting it to my new class using...
8
by: Michael | last post by:
Hi, I think my problem deals with class casting and inheritance. I want to deal with various Audio Formats, reading into memory for modification, working with it (done by different classes),...
9
by: Kris | last post by:
Hi. I have a asp class A with a public function AA() ----------------A.aspx.cs------------------------ public partial class A : System.Web.UI.Page { protected void Page_Load(object sender,...
3
by: Magnus | last post by:
i have a class which inherits from a base class class base1 { } class child1 : base1 { } how can I determine if child1 is of base1? gettype returns type of child1, but I need to know the...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.