Advertisement
bzhang22

Untitled

Mar 22nd, 2019
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.28 KB | None | 0 0
  1. public class Test {
  2.  
  3.     public static void main(String[] args){
  4.  
  5.         A a = new A();
  6.         a.printMe();
  7.         //a.doSomethingElse();
  8.         // Prints "A"
  9.  
  10.         B b = new B();
  11.         b.printMe();
  12.         // Prints "B"
  13.         b.doSomethingElse();
  14.  
  15.         A a2 = new B();
  16.         a2.printMe();
  17.         // Prints...? "B"
  18.         //a2.doSomethingElse(); // Doesn't work
  19.         ((B) a2).doSomethingElse(); // Works with casting
  20.         // Equivalent to...
  21.         B b2 = (B) a2;
  22.         b2.doSomethingElse();
  23.         // The above could throw ClassCastException if a2 is not type "B"
  24.  
  25.         a2 = new C();
  26.         a2.printMe();
  27.         // Prints... "C"
  28.  
  29.     }
  30.  
  31.     static class A extends Object /* implied */ {
  32.         public void printMe() {
  33.             System.out.println("A");
  34.         }
  35.         @Override
  36.         public String toString() {
  37.             return "A";
  38.         }
  39.     }
  40.     static class B extends A {
  41.         @Override // Override's A's printMe() method
  42.         public void printMe() {
  43.             System.out.println("B");
  44.         }
  45.  
  46.         public void doSomethingElse() {
  47.  
  48.         }
  49.     }
  50.     static class C extends A {
  51.         @Override
  52.         public void printMe() {
  53.             System.out.println("C");
  54.         }
  55.     }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement