Solved

Inheritance Issue

Posted on 2003-12-09
7
250 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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
MS Dynamics Made Instantly Simpler

Make Your Microsoft Dynamics Investment Count  & Drastically Decrease Training Time by Providing Intuitive Step-By-Step WalkThru Tutorials.

 

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

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
jsp insert to database example 2 66
Selenium docs api java index 3 69
passing enum to a method 4 36
Coding for the first time 9 70
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…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

730 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