Skip to content
Ryan James
Menu

← Java10 min read

Class Design

As stated previously in other parts of this page, Java is an Object-Oriented Programming language and writing code in Java requires you to be submersed in the concepts of OOP; even writing your first program requires you to write a static method inside of a class for it to run correctly.

Class Design

As stated previously in other parts of this page, Java is an Object-Oriented Programming language and writing code in Java requires you to be submersed in the concepts of OOP; even writing your first program requires you to write a static method inside of a class for it to run correctly. Let’s try to think of classes as a container that can contain as many variables and methods that you want it to keep. With this idea in mind, think of using strings, since in Java they are objects. When creating a string, you store a value into it as a variable - the contents of the string literal (“Hello World”). Then the string has multiple methods that are inside the String class: .equals(), .indexOf, .substring(), etc. When creating a string using the constructor, you are creating an instance of the String class.

Look over the example below. This is a review of how strings work in Java so that we can see how objects and classes work.

public class StringReview
{
    public static void main(String[] args){
        String str = new String("Hello World");       // Calling the String constructor method - a new instance of a String
        boolean equ = str.equals("Hello!");           // Calling the .equals() method from the String class
        String str2 = str.substring(0, 5);            // Calling the .substring() method from the String class 
    }
}

Now that it’s clear that there are classes that can keep variables and methods, it’s time to create a custom class. For example, what if the String class wasn’t good enough for a specific problem and we wanted an enhanced string class? Well you can just create your own class to work how you want it to work - with its own variables and its own methods.

Classes have multiple things that you can use when building a class. Look over the terms below and we’re going to use them in the next few examples. Class Heading - this defines the class name and always has to be the same as the file name PIVs - these are the private instance variables; must be declared outside of methods, generally after the class heading Constructor Method(s) - a constructor method(s) are provided to initialize the PIVs; you can have multiple constructor methods depending on the number of parameters for each; constructor methods are always the same name as the class; not necessary since the Object class includes one and will be present even if one is not typed Mutator Methods - these methods will change the state of the PIVs; always have a void return type Accessor Methods - these methods give access to the PIVs to outside of the class; always have a non-void return type toString Method - this method is inherited from the Object class; this overrides the method inherited; always a string representation of the class

Let’s look at an enhanced String class now.

public class EnhancedString
{
    private String literal;
    private int length;

    public EnhancedString()
    {
      literal = "";
      length = 0;
    }

    public EnhancedString(String input)
    {
      literal = input;
      length = input.length();
    }

    public void setString(String input)
    {
      literal = input;
      length = input.length();
    }

    public String substring(int n)
    {
      if(n > 0)
      {
        return literal.substring(n);
      }
      else if(n < 0)
      {
        return literal.substring(0, (-1)*n);
      }
      return "";
    }

    public String firstHalf()
    {
      return literal.substring(0,length/2);
    }

    public String secondHalf()
    {
      return literal.substring(length/2);
    }

    @Override
    public String toString()
    {
      return literal;
    }
}

Let’s go through this piece by piece. It can be a little overwhelming at first. Notice the class heading at the top. It declares the name of the class as ‘EnhancedString’. Best practice is to always name your class starting with a capital letter.

Then the next thing that shows up are the Private Instance Variables or PIVs for short. There are two PIVs in this class, literal and length. Notice that the variables are just declared. At this point in the class they contain zero data - so they are set to defaults. The literal variable is currently null and the length variable is currently 0.

After the PIVs, you should see the constructor methods. For this class I wrote, there are 2 constructor methods. The method signature is different for them because one contains parameters and one does not. This is an example of overloading. The constructor method for this class has been overloaded. The first constructor method is the ‘default’ constructor since there is no parameter. The second constructor is called when a String parameter is present. If the constructor is called with another type of parameter, it will cause a compile error.

After the constructor methods, there is 1 mutator method named setString(). For this example, this acts like a constructor setting the values of the PIVs. The difference is that this method is called after the object is created and the constructor is called when the object is being created.

Following the mutator method, there are 3 accessor methods. These methods are what causes this to be an ‘enhanced’ String class. These methods get access to the PIVs and then return what they need to return. Notice that one of them allows for a negative number to be called in the substring method similar to Python.

The last method that is shown is the toString() method. Before this method, the decorator @Override is shown. This tells Java that we want to override a method. If we type something wrong like toSting() instead of toString(), it will cause a compile error so we know it’s a problem before we try to run our code.

Now it’s time to see how this class can be used.

public class Client
{
    public static void main(String[] args){
        EnhancedString str1 = new EnhancedString();               // Calls the default constructor - literal = "" and length = 0
        str1.setString("number one");                             // Calls the mutator method - literal = "number one" and length = 10
        EnhancedString str2 = new EnhancedString("second");       // Calls the second constructor - literal = "second" and length = 6
        System.out.println(str1 + " " + str2);                    // Prints both objects by calling their toString() methods
        boolean equal = str1.equals(str2);                        // Runs without compile errors since every class has a .equals() method, but doesn't work as expected
        int index = str1.indexOf(str2);                           // Causes a compile error since only String has an indexOf() method
    }
}

The class shown above would be inside the same project folder as EnhancedString but not in the same file. The class creates a main method and inside this main method, instances of the class EnhancedString are created. There are 2 instances of the String class in this example, but many more can be created. Some of the methods are called: the constructor methods, the mutator method, and the toString() method. When typed this way, it almost looks exactly like a String except that it’s calling all of the methods that were written above. This concept of creating a custom data type can keep going to create as simple or complex data types to hold specific types of data to solve more complex problems going forward.

There are still more concepts with class design that this does not touch on like creating abstract classes, interfaces, and the big ideas of polymorphism. But, with what’s here, there’s enough to get started writing your own classes.

Keep coding!
Ryan