waltermilner

Untitled

Sep 15th, 2018
275
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.52 KB | None | 0 0
  1. // Illustrate covariant return type
  2. public class Test {
  3.  
  4.   public static void main(String[] args) {
  5.  
  6.     B b = new B();
  7.     System.out.println(b.m()); // I'm a Sub instance
  8.   }
  9. }
  10.  
  11. class Base { // a base class
  12. }
  13.  
  14. class Sub extends Base { // a sub class
  15.  
  16.   public String toString() {
  17.     return "I'm a Sub instance";
  18.   }
  19. }
  20.  
  21. class A {
  22.  
  23.   Base m() {  // covariant return type
  24.     return new Base();
  25.   }
  26. }
  27.  
  28. class B extends A {
  29.  
  30.   Sub m() { // sub is 'narrower' than base
  31.     return new Sub();
  32.   }
  33.  
  34. }
Advertisement
Add Comment
Please, Sign In to add comment