DEV Community

loading...

Classes, Inheritance, Packages & Modularization in Java ☕️

Martins Onuoha
Maker.
・6 min read

Header Image

Modular programming is the process of subdividing a computer program into separate sub-programs. A module is a separate software component. It can often be used in a variety of applications and functions with other components of the system. — www.techopedia.com

Although this post emphasizes on Modularization, we will go through a short basic of Classes and Inheritance which is a part of the Object Oriented Methodology Java enforces so as to put the piece together.

Classes ☕️

If we didn’t already know, Everything in Java is in one way or the other associated with a class, why? because Java is an Object Oriented Programming language, and like in every OOP Language, Everything is an object. And for Objects to have a “Grouping” or “Blueprint”, they need to belong to or be classified within a class.

Here’s an example.

classical_illustration

Vehicles include wagons, bicycles, motor vehicles (motorcycles, cars, trucks, buses), railed vehicles (trains, trams), watercraft (ships, boats), amphibious vehicles (screw-propelled vehicle, hovercraft), aircraft (airplanes, helicopters) and spacecraft. — wikipedia

Following Wikipedia’s definition of Vehicles, although we might easily categorize the blue car and the blue bicycle as two distinct objects, but we can equally say they are both “Vehicles” and so belong to the group or class of “Vehicles”. We also see how classes acts as blueprints for several other kinds of objects ( included above ).

Although these objects belong to the same class, they do not necessarily perform the same “functions/actions” in this case we call these functions/actions “methods”.

Methods 🏃🏼‍♀️💨

We can say that a method is any action that an object can perform. Actions including; fly, drive, ride, reverse. However, objects of the same class ( like the car and bicycle in our example ) may not have all methods in common, just the same way a car cannot be pedaled, likewise a bicycle cannot be driven. Think of Methods as Verbs.

methods_illustration

public class Car {
  public void drive() {

  }
  public void reverse() {

  }
  public void park() {

  }
}

Attributes 🎨

Attributes are properties of an object, they are those things that define an object or differentiate one object from the other. “a blue car” — the word “blue” tells you a little more about the car. Think of Attributes as Adjectives.

You could also say that class attributes are variables within a class.

attributes_illustration

public class MyClass {
  int x = 5;
  int y = 6;
}

spooky

Inheritance 👩‍👩‍👧‍👧

It’s nice to have a bunch of objects and their collective methods and attributes, but what would be nicer would be for us to share this methods and attributes across other related objects, and why would we want to do this? Well, mostly for re-usability and maintaining the DRY (Do not Repeat Yourself) principle. This is where Inheritance comes in handy, inheritance allows one class ( subclass/child ) “inherit” the attributes and methods from another class ( super-class/parent ).

We won’t go too deep into the details around inheritance, we’ll just see a practical example in Java. But for notes, we have a number of types of inheritance:

  • Single ( we’d be touching this )
  • Multiple
  • Multilevel
  • Hierarchical
  • Hybrid

To declare a child class of a parent class in Java, you use the keyword extends.

Modularization 🍰

Modularization involves the process of breaking a program into components or sub-programs.

[‘😚’ + ‘❤️’ + ‘😉’] = 😘

Hopefully the emoji above is a good enough illustration. The major advantage of modularizing our programs is that it helps us detect and debug issues faster and more efficiently.

Packages

A package in Java is used to group related classes. A Package is basically a folder of related classes. Packages come in handy when building a more maintainable code and are mostly of two types:

  • Built-in packages ( Packages from the Java API )
  • User-Defined Packages ( Packages you create )

We’ll only be looking at the second one.

Putting it All Together 👩‍👩‍👦‍👦

Let’s run through a very basic example: we’ll build a Calculator class ( parent class ) with class methods and attributes, then extend a MyCalculator subclass (child class) from it, that will inherit the methods and attributes from it. We’ll be using Modularization by default as we would be separating each of the class files and putting them in a single folder ( package ).

Note: You should have only one class per package file

First We’ll have our package folder structure like so:

Note: I’ll be using Visual Studio Code for this lesson, “why??” As much as it’d be great and nice to have an IDE like Netbean or IntelliJ abstract all the details of compilation from you, one problem is, you may not entirely understand the process and adequately debug issues when the need arises.

Calculator.java 👨🏽‍💼👩🏼‍💼

We’ve declared a parent class Calculator, it has one class attribute z and two class methods addition( ) and subtraction( ). The addition method takes two arguments and prints out their sum, while the subtraction method prints out the difference.

MyCalculator.java 👨‍👧

Here we’re declaring a child class MyCalculator which inherits from the parent class Calculator. Notice we used an undeclared variable z, we don’t have to declare the z variable again cause the child class (MyCalculator) inherits all attributes and methods from the parent ( Calculator ). And Since we already declared z in the parent class, we do not need to repeat the declaration in the child class.

We have also created a new method multiplication which also takes two integer variables and return their product.

Note: The new method created in our child class cannot be accessed from our parent class. the inheritance doesn’t work vice-versa.

Note (again ): To Inherit from a parent class, use the “extends” keyword

Main.java ☕️

There’s nothing fancy about this class, it’s basically where we have our main method, if you didn’t already know, the main method is what marks the initialization of our program, Java looks for this guy.

  • Line 3: we declare two integer variables a and b, this will be the arguments we’ll be passing to our methods.
  • Line 4: In order to access the methods that live in our MyCalculator class, we need to create an instance of that class. So we created an instance of MyCalculator called demo.
  • We call the addition, subtraction and multiplication methods passing the a and b variables as arguments.

Run 🚀

Okay, this is the part where we run our program. Because we are not using Netbean or IntelliJ, we will be compiling and running our program manually.

There are two major steps to successfully running a Java Program:

  • Compilation ( javac )
  • Execution ( java )

For the compilation, we use the javac command

For Execution, we use the java command

Note: Usually, when dealing with just a single Java file/class, we would run both commands for just that class. but in this case where we have multiple related classes, it would be nice to compile all the programs once. Thankfully we can.

Open up your Command Line or Terminal, Depending on what Operating System you’re using.

For windows: Press Windows key + R, Then type in “cmd” (without the quotes) and press enter. You should see the command line pop up.

Now we need to go into the directory where we saved our program. I’ll assume it was saved on the Desktop and the folder name is “calculator”. To go into the your program directory, type:

cd Desktop/calculator

You should now be in your project directory.

Compile

To compile all the classes in the directory at once, Type:

javac ./*.java

Note: This command tells the java compiler to look in the current folder, find anything that have the “java” extension ( in this case, Calculator.java, MyCalculator.java & Main.java) and compile them.

Another way to compile the classes would be one at a time: If you would rather go with this method, you need to carry out the compilation in this order:

  • Compile The parent class ( javac Calculator.java )
  • Compile The Child class ( javac MyCalculator.java )
  • Finally, Compile the Main class ( javac Main.java )

This will create a .class file for each of the classes ( MyCalculator.class, Calculator.class, Main.class ).

Execute

To run your program, you’d only need to run the class that contains the main method ( in our case Main.class )

java Main

You should get the following output:

🎉🥂 We’ve come to an end of this short😅 tutorial. Hope this helps someone.

Discussion (1)