Overriding Methods

Java-Overriding Methods

Overriding Methods

A method in a generic class can be overridden just like any other method. For example, consider the following program in which the method getT( ) is overridden. As the output confirms, the overridden version of getT( ) is called for object of type GenTwo, but you can call the superclass version via GenOne object.

Program

Overriding Methods

Program Source

class GenOne<T> {

    T t1;

    GenOne(T t) {
        t1 = t;
    }

    T getT() {
        System.out.println("GenOne's getT");
        return t1;
    }
}

class GenTwo<T> extends GenOne<T> {

    GenTwo(T t) {
        super(t);
    }

    T getT() {
        System.out.println("GenTwo's getT");
        return t1;
    }
}

public class Javaapp {

    public static void main(String[] args) {
        
        GenTwo<Integer> gtwo = new GenTwo<Integer>(50);
        Integer i = gtwo.getT();
        System.out.println("i -> "+i);
    }
}

Leave a Comment