class

Static fields inheritance

This is an example of static fields inheritance between two classes. The steps of the example are described below:

  • We have created a class Aclass that has a static int val, and a static method fun() that returns an int value.
  • We have also created a subclass of Aclass, that is InheritanceStaticFields and extends the Aclass.
  • We create a new instance of InheritanceStaticFields and call its start() method, that prints the results of the values inherited to this class by Aclass.

Let’s take a look at the code snippet that follows:  

package com.javacodegeeks.snippets.core;

class Aclass {
    
    static int val = 24;

    Aclass() {


  System.out.println("In Aclass::<init>");
    }

    static int fun() {

  return 12;
    }
}

/**
 * This is the subclass
 */

public class InheritStaticFields extends Aclass {

    public static void main(String[] c) {

  new InheritStaticFields().start();
    }

    public void start() {

  System.out.println("In InheritStaticFields::start");

  System.out.println("Val is " + val);

  System.out.println("fun is " + fun());
    }
}

Output:

In Aclass::<init>
In InheritStaticFields::start
Val is 24
fun is 12

  
This was an example of static fields inheritance between two classes in Java.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button