Solved

Inheritance Issue

Posted on 2003-12-09
7
245 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
Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

 

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

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Fibonacci challenge 11 84
IT Company 5 69
countAbc challenge 9 50
Which is the latest version of Apache Tomcatl 3 35
For customizing the look of your lightweight component and making it look lucid like it was made of glass. Or: how to make your component more Apple-ish ;) This tip assumes your component to be of rectangular shape and completely opaque. (COD…
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.

746 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

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now