How to Derive One Variable to Another Class in Java

Java is an object-oriented language, so you can inherit variables and functions from a parent class to the child class. OO programming allows you to create modules for each section of your program, which makes it more convenient to add and subtract code when you need to edit the custom program code.

Instructions

    • 1

      Open the Java programming editor and open the Java project you want to edit. Open the file you want to use to inherit the variables.

    • 2

      Create the inherited class. You use the "extend" keyword to inherit a parent's class functions. The following class inherits "Animal":

      public class Dog extends Animal
      {
      public Dog() {
      animal.Type = "Dog";
      }

      The parent Animal class type is set to "Dog" in this class. The "Type" variable is in the parent Animal class, but it is derived in the child class.

    • 3

      Initialize the variable and display the variable to the user. The following code prints "Dog" in the user's window:

      Dog d = new Dog();
      System.out.println("Animal Type: " + d.Type);

Related Searches:

References

Comments

Related Ads

Featured