Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Testing inheriting and hiding static and non-static
- // fields and methods
- // fields are inherited (static or not). If re-defined, they hide the base fields
- // methods are inherited. If re-defined, they over-ride the base method
- public class Test {
- public static void main(String[] args) {
- System.out.println(Sub1.x); // 4 - static field inherited
- Sub1.method(); // base method - static method inherited
- Sub1 s1=new Sub1();
- System.out.println(s1.y);// 2 non-static field inherited
- System.out.println(Sub2.x); // 5 - hides Base.x
- Sub2.method(); // Sub2 method - over-ridden
- Sub2 s2 = new Sub2();
- System.out.println(s2.y); // 3 - s2.y hides Base.y
- }
- }
- class Base {
- static int x = 4;
- static void method() { System.out.println("Base method"); }
- int y=2;
- }
- class Sub1 extends Base { // inherit x,y and method
- }
- class Sub2 extends Base
- {
- static int x = 5; // hides Base.x
- int y=3; // hides non-static field y
- static void method() { System.out.println("Sub2 method"); }
- }
Advertisement
Add Comment
Please, Sign In to add comment