Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Upcasting and Downcasting

807600Oct 2 2007 — edited Oct 3 2007
Hi all,

Ive got three classes, forming a hierarchy of a super class and 2 sub classes as in the code below
public class Animal {
	public void sound(){
		System.out.println("Animal");
	}
}


public class Dog extends Animal {
	public void sound(){
		System.out.println("Dog");
	}
}

public class Cat extends Animal {

	public void sound(){
		System.out.println("Cat");
	}
}
now in the launch file
Animal animal = new Animal();
animal.sound(); //Animal

Dog dog = new Dog();
dog.sound(); //Dog

Cat cat = new Cat();
cat.sound(); //Cat
these would print the methods shown in the comments, however how would it be possible for a dog to invoke the animal's sound method to display "Animal" instead (typically if i understood right using upcast), and how would it be possible to do the opposite downcast from type animal to invoke sound of dog..

Also would it be possible to convert dog to cat by converting dog to animal then animal to cat ?

Sorry if this post is abit confusing however these class cast (upcast/downcast) are abit confusing me :P

Thanks, i appreciate the help :)
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Oct 31 2007
Added on Oct 2 2007
5 comments
716 views