Now let’s take a look at the concept of shadowing in Java. Shadowing allows for the overlapping scopes of members with the same name and type to exist in both a nested class and the enclosing class simultaneously. Depending on which object we use to call the same variable in a main method will result in different outputs.

Take a look at the example below:

class Outer { String name = "Outer"; // Nested inner class class Inner { String name = "Inner"; public void printTypeMethod() { System.out.println(name); System.out.println(Outer.this.name); } } } class Main { // Main driver method public static void main(String[] args) { Outer outerObj = new Outer(); Outer.Inner innerObj = outerObj.new Inner(); innerObj.printTypeMethod(); } }

The code above will output the following:

Inner Outer

If we take a closer look at the method printTypeMethod(), there is the use of the keyword this in the second print statement. Using the keyword this along with the class name Outer allows us to overlap the variable name with the contents of the outer class.



For this exercise, we will be practicing the use of shadowing by modifying a program about books. To start off the outer class Book and inner class Biography have been created for you.

  1. Create a String variable in both classes named type.
  2. In the class Book, set the variable type to “Nonfiction”.
  3. In the class Biography, set the variable type to “Biography”.

In the inner class Biography create a method called print() that will use two System.out.println() statements.

  1. For the first println() statement use the variable type to print “Nonfiction”.
  2. For the second println() statement use the variable type to print “Biography”.

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?