waltermilner

Untitled

Sep 7th, 2018
248
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.05 KB | None | 0 0
  1. // Testing inheriting and hiding static and non-static
  2. // fields and methods
  3.  
  4. // fields are inherited (static or not). If re-defined, they hide the base fields
  5. // methods are inherited. If re-defined, they over-ride the base method
  6.  
  7. public class Test {
  8.   public static void main(String[] args) {
  9.  
  10.     System.out.println(Sub1.x); // 4 - static field inherited
  11.     Sub1.method(); // base method - static method inherited
  12.    
  13.     Sub1 s1=new Sub1();
  14.     System.out.println(s1.y);// 2  non-static field inherited
  15.    
  16.    
  17.     System.out.println(Sub2.x); // 5 - hides Base.x
  18.     Sub2.method(); // Sub2 method - over-ridden
  19.     Sub2 s2 = new Sub2();
  20.     System.out.println(s2.y); // 3 - s2.y hides Base.y
  21.   }
  22. }
  23.  
  24. class Base {
  25.   static int x = 4;
  26.   static void method() { System.out.println("Base method"); }
  27.   int y=2;
  28. }
  29.  
  30. class Sub1 extends Base { // inherit x,y and method
  31. }
  32.  
  33. class Sub2 extends Base
  34. {
  35.   static int x = 5; // hides Base.x
  36.   int y=3; // hides non-static field y
  37.   static void method() { System.out.println("Sub2 method"); }
  38. }
Advertisement
Add Comment
Please, Sign In to add comment