Inheritance Issue

Consider the example
class C
{
  method xyz()
}

class D extends C
{

}

d = new D
if we call d.xyz(), then Java uses the function xyz()
of superclass as it is not present in classs D.

If xyz() method is not present in class D, then I want
to temporarily coerce d to class C. is it possible, if
possible what are its advantages.

Hoping for a quick reply....
Gaurav_MehraAsked:
Who is Participating?
 
JakobACommented:
class C
{
    method xyz() {
         system.out.println( "this is C speaking" ):
    }
}

class D extends C
{
    method xyz() {
         system.out.println( "this is D speaking" ):
    }
}
class D2 extends C
{
// no  method xyz()
}

C dx = new D2();
dx.xyz();
dx = new D();
dx.xyz();

regards JakobA

if xyz is not defined in the current D object you get the xyz of the C object
0
 
objectsCommented:
C c = d;

no advantage
0
 
JakobACommented:
I usually put an error-message in the 'C method', then if I ever get that message i know i have forgotten to define that function in one of the dependant classes.

like here: (a bit long for an example, byt you can see the utility:

class Sorter {
    int i,j,k, lgt, hand;
   
    void swap( int[] arr, int idx1, int idx2 ) {
        hand      = arr[idx1];
        arr[idx1] = arr[idx2];
        arr[idx2] = hand;
    }
   
    void sort( int[] arr ) {
        System.out.println( "Extension failed to define method sort." );
    };     // sort the array given as parameter
                            // implemented in the sorting classes
}// endinterface Sorter

class BubbleSort extends Sorter {
    void sort( int[] arr ) {
        lgt = arr.length;
        for ( i=lgt-1; i>0; i-- ) {
            for ( j=0; j<i; j++ ) {
                if ( arr[j] > arr[j+1] ) {
                    swap( arr, j, j+1 );
                }
            }
        }
    }// endmethod sort
}// endclass BubbleSort

class InsertionSort extends Sorter {
    void sort( int[] arr ) {
        lgt = arr.length;
        for (i=1; i<lgt; i++) {
            hand = arr[i];
            for (j=i; j>0 && arr[j-1]>hand; j--) {
                arr[j]   = arr[j-1];
                arr[j-1] = hand;
            }
        }            
    }// endmethod sort
}// endclass InsertionSort

class SelectionSort extends Sorter {
    void sort( int[] arr ) {
        int smallest;
        lgt = arr.length;
        for (i=0; i<lgt-1; i++) {
            k = i;
            for (j=i+1; j<lgt; j++) {
                if ( arr[j] < arr[k] ) {
                    k = j;
                }
            }
            swap( arr, k, i );
        }            
    }// endmethod sort
}// endclass SelectionSort

class HeapSort extends Sorter {
    void sort( int[] arr ) {
        int k;
        lgt = arr.length;
        for (i=lgt/2; i>=0; i--) {   // build heap
            k = i;
            while ( (j = k*2+1) < lgt ) {
                if ( j < lgt-1 && arr[j+1] >= arr[j] ) j = j+1;
                if ( arr[k] <  arr[j] ) {
                    swap( arr, k, j );
                }
                k = j;
            }
        }
        for (i=lgt-1; i>0; i--) {    // sort from heap
            hand = arr[i];
            arr[i] = arr[0];
            arr[0] = hand;
            k = 0;
            while ( (j = k*2+1) < i ) {
                if ( j < i-1 && arr[j+1] >= arr[j] ) j = j+1;
                if ( arr[k] < arr[j] ) {
                    swap( arr, k, j );
                }
                k = j;
            }
        }
       
    }// endmethod sort
}// endclass HeapSort

class QuickSort {
     // no sort method defined here, byt the test still runs.
}

public class SortTest {
   
    static int[] myArr = new int[10];
    static boolean debugOn = false;
   
    static void printArr( int[] arr ) {
        for ( int i=0; i<arr.length; i++) System.out.print( " " +arr[i] );
        System.out.println("");
    }//endmethod printArr
   
    static int[] makeRandom( int lgt ) {  // create a randomly filled integer array
        int[] res = new int[lgt];
        for (int i=0; i<lgt; i++) {
            res[i] = (int)Math.floor(Math.random()*lgt);
        }
        if ( debugOn ) {
            System.out.println("");
            printArr( res );
        }
        return res;
    }//endmethod makeRandom
   
    static long timeSorting( Sorter s, int N ) {
        int[] localArr = new int[2];
        if ( N > 0 ) {
            long time = System.currentTimeMillis();
            for (int i=0; i<N; i++) {
                localArr = (int[])myArr.clone();
                s.sort( localArr );
            }
            time = (System.currentTimeMillis() -time);  // total sort-time in milliseconds
            System.out.println( s.getClass().getName() +" took "
                               +((double)time/N) +" milliseconds to sort "
                               +myArr.length +" numbers." );
            if ( debugOn ) printArr( localArr );
            return time/N;
        }
        return 0;
    }//endmethod timeSorting
   
    public static void main ( String argv[] ) {
        for (int i=20; i<=200; i+=20) {
            int N = 20000/i;
            myArr = makeRandom( i );
            timeSorting( new BubbleSort(), N );
            timeSorting( new InsertionSort(), N );
            timeSorting( new SelectionSort(), N );
            timeSorting( new HeapSort(), N );
            timeSorting( new QuickSort(), N );
        }
    }//end main
   
}// endclass SortTest

0
Cloud Class® Course: Amazon Web Services - Basic

Are you thinking about creating an Amazon Web Services account for your business? Not sure where to start? In this course you’ll get an overview of the history of AWS and take a tour of their user interface.

 
Gaurav_MehraAuthor Commented:
class C { ........}
class D extends C { .................... }

d = new D. (means d is instance of D)

I know how the inheritance works in Java, ie first the method is searched in subclass D. if present, it invokes it and if method not present in the subclass then it searches the method in superclass  C and invokes it.

My question is, if the method is not present in the subclass D,  before searching the method in superclass C, can I temporarily change the owner field of object d to C (ie d should be temporarily instance of C and not D. after the method is executed, it rechanges the owner back to D).

I would like to know the advantage/differences between 2 kinds  of inheritance.

0
 
objectsCommented:
> I usually put an error-message in the 'C method'

defining it as abstract will ensure those errors are picked up at compile time.

> d should be temporarily instance of C and not D

d already is an instance of C, to test try:

if (d instanceof C)
{
   System.out.println(""d is an instance of C");
}
0
 
JakobACommented:
It sounds a bit sacriledeous to me.
Each class has an associated offset-table telling where variables can be found in the data-block allocated for the instances of that class. If you succed in changing the owner to another classname you would get the wrong offset table and any attempt to adress a variable in that instance would be potentially fatal.
0
 
ahosangFinance Systems DeveloperCommented:
Gaurav_Mehra, the book 'Thinking in Java' by Bruce Eckels is mightily impressive(to me anyway) in explaining a lot of these sort of things.

http://www.codeguru.com/java/tij/tij_c.shtml
Look at chapter 6 especially.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.