• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Method inheritance

 
Karu Raj
Ranch Hand
Posts: 481
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Given the following object hierarchy and code for the upgrade method:
java.lang.Object
|
+---- mypkg.BaseWidget
|
+---- TypeAWidget
// the following is a method in BaseWidget
1. public TypeAWidget upgrade( ){
2. TypeAWidget A = (TypeAWidget) this ;
3. return A ;
4. }
What will be the result of trying to compile and run a program containing the following statements?
5. BaseWidget B = new BaseWidget() ;
6. TypeAWidget A = B.upgrade() ;

A. The compiler will object to line 2.
B. A runtime ClassCastException will be generated in line 2.
C. After line 6 executes, the object referred to as A will in fact be a TypeAWidget.

Why is the answer B?
Explain me more clear .
 
Michael Ernest
High Plains Drifter
Sheriff
Posts: 7292
Netbeans IDE VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The code attempts to 'downcast' the current type to a subtype. This is inherently dangerous, as it can work out in some cases, but guaranteed for all cases.

If the subtype adds methods to its supertype interface, for example, how can the supertype claim to support it? It has no understanding of extensions to itself.
 
Karu Raj
Ranch Hand
Posts: 481
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I didnot understand it .
please explain me with example clearly .
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
From the diagram(?) class TypeAWidget is a subclass of class BaseWidget. So every TypeAWidget object is a BaseWidget object. It is not so that every BaseWidget object is a TypeAWidget object. Some might be, but not all.

Java lets you express "this object might be one of these objects" with a so-called downcast, and the compiler will accept the cast as a promise that ,at runtime, you will provide a TypeAWidget object. The compiler will only accept the promise if it looks feasible that the classes have such a relationship to each other - it could reject the cast if obviously no such relationship exists.

TypeAWidget A = (TypeAWidget)this is making exactly that promise in the upgrade method. But at runtime the this in method upgrade() is definitely only of type BaseWidget (see line //5), not of type TypeAWidget. The Java Virtual Machine detects your broken promise to provide a TypeAWidget object at runtime and complains very loudly with a ClassCastException.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic