Java: Constructing a subclass

This entry is part 42 of 54 in the series Learn Java

We look at this example where we construct an instance from a subclass.  If you run the code, you will find that the parent class constructor is also called.

This parent constructor is called by the compiler.  This is because when constructing a subclass, the member fields in the parent constructor would need to be initialized too.

package javaapplication34;

public class Music {

    public class Rock {

        String r = "Oasis";

        public Rock() {

    public static class Metal extends Rock {

        String m = "Metallica";

        public Metal() {

    public static void main(String[] args) {

        Metal s = new Metal();

When the subclass Metal is constructed, the member field r would be initialized allowing it to be printed out.





Series Navigation<< Java: Accessing member in parent class
Java: Adding a class in a separate file >>