Casting class objects
1.2 Compile and execute the code listed below as it is written. Run it a second time after uncommenting the line obj.speak();.
public class AnimalRunner
{
public static void main(String[] args)
{
Dog d1 = new Dog("Fred");
d1.speak();
Object obj = new Dog("Connie");
// obj.speak();
}
}
The uncommented line causes a compile error because obj is an Object reference variable and class Object doesn’t contain a speak() method. This is the case, in spite of the fact that obj refers to a Dog object and that class Dog has a speak() method. For safety, the Java compiler limits the methods that can be called using a reference variable to only those methods that belong to the class that was used to create the reference variable. So obj can only invoke Object methods.
Use the following method to make Connie speak: Create a second Dog reference variable d2. Cast obj to a Dog and assign the new reference to d2. Now invoke speak on d2. What happens if you create a Cat object and try to cast it to a Dog?
Your answer :
What methods do you need to add to BankAccount to implement Comparable?
2.1. The Comparable interface is a commonly used interface in Java. Look up the Comparable interface in the API documentation.
If you wanted to modify the BankAccount class so that it implements the Comparable interface, what method(s) do you need to implement?
Give the method signature(s), that is, the return type(s), the method name(s), and the method parameter(s) needed.
Your answer :
1.2
SOLUTION:
public class AnimalRunner
{
public static void main(String [ ] args)
{
Dog d1=new Dog ("Fred");
d1.speak();
object obj = new Dog("Connie");
Dog d2 =(Dog) obj;
d2.speak();
}
}
If we cast a cat to a dog, what will happens is that the compiler signals an "inconvertible types" error since the object being cast is not a member of the class which is the target of the cast.
2.1
SOLUTION:
The method i will implement to modify the BankAccount class so that it implements the Comparable interface is
int compareTo(T o)
5
Get Answers For Free
Most questions answered within 1 hours.