How to Declare a Constructor in Java

How to Declare a Constructor in Java thumbnail
Constructors reduce the code necessary to define objects.

Classes within Java programs are templates for objects. Constructors are methods within classes that set up the new objects. Classes don't need constructors. But if a class contains a constructor, the program, when it creates a new instance of that class, will parse the constructor for parameters to apply to the new object. Declaring a constructor means writing the relevant method and setting the parameters that the constructor defines.

Instructions

    • 1

      Open your Java file, and navigate to the class in which you want to declare the constructor. For example, the class may look like this:

      public class Room {
      int length;
      int width;
      int height;

      public int area () {
      return (length * width)
      }
      }

    • 2

      Add a line to declare the class's constructor, assigning the constructor the same name as the class itself. By convention, capitalize the constructor name, though you do not normally capitalize method names.

      public class Room {
      int length;
      int width;
      int height;

      public int area () {
      return (length * width)
      }

      Room () {
      }
      }

    • 3

      Add parameters within the constructor's parentheses:

      public class Room {
      int length;
      int width;
      int height;

      public int area () {
      return (length * width)
      }

      Room (int l, int w) {
      }
      }

    • 4

      Add code within the constructor, associating its parameters with the class's properties:

      public class Room {
      int length;
      int width;
      int height;

      public int area () {
      return (length * width)
      }

      Room (int l, int w) {
      length = l;
      width = w
      }
      }

Related Searches:

References

Resources

  • Photo Credit Stockbyte/Stockbyte/Getty Images

Comments

Related Ads

Featured