Valid XHTML 1.0!

Variables are shadowed and methods are overridden.



Consider the following example.
When a class member variable someNumber is accessed through an object reference base, the variable to be selected depends on the declared class of base.In this case therefore Base.someNumber will retun value 100 even if base holds reference to object of type Derived.
But when a method() is called on through an object reference base, the actual method invoked will be from the class Derived. Therefore base.someMethod() will print "From Derived class." on console as base hold object reference to a Derived object.

The output of execution of class Derived will be "The value of someNumber is 100 from Derived class.".

1
 package com.witscale.scjp.examples;        // Package declaration
2
3
class Base {
4
int someNumber = 100;
5
 String method() {
6
   return "from Base class.";
7
    }
8
 }
9
class Derived extends Base {
10
int someNumber = 500;
11
 String method() {
12
   return "from Derived class.";
13
    }
14
 public static void main(String[] args) {
15
    Base base = new Derived();
16
    System.out.println("The value of someNumber is " + base.someNumber + " " + base.method());
17
 }
18
 }