Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Inheritance Issue

Posted on 2003-12-09
7
Medium Priority
?
254 Views
Last Modified: 2010-03-31
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....
0
Comment
Question by:Gaurav_Mehra
7 Comments
 
LVL 92

Expert Comment

by:objects
ID: 9907402
C c = d;

no advantage
0
 
LVL 15

Accepted Solution

by:
JakobA earned 375 total points
ID: 9907478
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
 
LVL 15

Expert Comment

by:JakobA
ID: 9907555
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
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 

Author Comment

by:Gaurav_Mehra
ID: 9907628
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
 
LVL 92

Expert Comment

by:objects
ID: 9907665
> 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
 
LVL 15

Expert Comment

by:JakobA
ID: 9907869
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
 
LVL 12

Expert Comment

by:ahosang
ID: 9913307
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

Featured Post

How to Use the Help Bell

Need to boost the visibility of your question for solutions? Use the Experts Exchange Help Bell to confirm priority levels and contact subject-matter experts for question attention.  Check out this how-to article for more information.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
How to fix incompatible JVM issue while installing Eclipse While installing Eclipse in windows, got one error like above and unable to proceed with the installation. This video describes how to successfully install Eclipse. How to solve incompa…
Suggested Courses

824 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question