Solved

Inheritance Issue

Posted on 2003-12-09
7
248 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 125 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
The Eight Noble Truths of Backup and Recovery

How can IT departments tackle the challenges of a Big Data world? This white paper provides a roadmap to success and helps companies ensure that all their data is safe and secure, no matter if it resides on-premise with physical or virtual machines or in the cloud.

 

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

VMware Disaster Recovery and Data Protection

In this expert guide, you’ll learn about the components of a Modern Data Center. You will use cases for the value-added capabilities of Veeam®, including combining backup and replication for VMware disaster recovery and using replication for data center migration.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
groupSum6 challenge 6 86
split string containing \r\n in Java 46 44
javap not working 8 46
tomcat not starting 6 45
This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.

810 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