Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Test {
- public static void main(String[] args){
- A a = new A();
- a.printMe();
- //a.doSomethingElse();
- // Prints "A"
- B b = new B();
- b.printMe();
- // Prints "B"
- b.doSomethingElse();
- A a2 = new B();
- a2.printMe();
- // Prints...? "B"
- //a2.doSomethingElse(); // Doesn't work
- ((B) a2).doSomethingElse(); // Works with casting
- // Equivalent to...
- B b2 = (B) a2;
- b2.doSomethingElse();
- // The above could throw ClassCastException if a2 is not type "B"
- a2 = new C();
- a2.printMe();
- // Prints... "C"
- }
- static class A extends Object /* implied */ {
- public void printMe() {
- System.out.println("A");
- }
- @Override
- public String toString() {
- return "A";
- }
- }
- static class B extends A {
- @Override // Override's A's printMe() method
- public void printMe() {
- System.out.println("B");
- }
- public void doSomethingElse() {
- }
- }
- static class C extends A {
- @Override
- public void printMe() {
- System.out.println("C");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement