Skip to main content

Command Palette

Search for a command to run...

A Beginners Guide - Object-oriented Programming in Java

A beginner-friendly guide on the concepts and core principles of Object-oriented Programming in Java language.

Published
16 min read
A Beginners Guide - Object-oriented Programming in Java
C

I am a Frontend developer

This article will give you a clear and thorough beginner-friendly understanding of the integral principles of object-oriented programming and the basic concepts. With this knowledge, you can solve fundamental problems in your projects using this method in Java.

What is Object-Oriented Programming?

Object-oriented programming (OOP) in Java is a programming concept based on the use of “objects” which contain data and methods.

The main idea behind the object-oriented programming method is to break down complex data structures into smaller objects.

What is Java?

Java is a multi-purpose, class-based, object-oriented programming language designed to have lesser implementation dependencies.

Java can be used to develop applications for laptops, game consoles, and mobile phones due to its fast, secure, and reliable nature.

In Java, every application starts with a class name, and this class must match the file name. When saving a file, save it using the class name and add “.java” to the end of the file name.

Let's write a Java program that prints the message “Hello everyone. My name is ...”.

We are going to start by creating our first Java file called Main.java, which can be done in any text editor. After creating and saving the file, we are going to use the below lines of code to get the expected output.

public class Main 
{
  public static void main(String[] args) 
  {
    System.out.println("Hello everyone. My name is Java.");
  }
}

Don't worry if you don't understand the above code at the moment. We are going to discuss, step by step, each line of code just below.

For now, I want you to start by noting that every line of code that runs in Java must be in a class.

You may also note that Java is case-sensitive. This means that Java can distinguish between upper and lower case letters. For example, the variable “myClass” and the variable “myclass” are two different things.

Alright, let's see what that code's doing:

Let's first look at the main()  method: public static void main(String[] args).

This method is required in every Java program, and it is the most important one because it is the entry point of any Java program.

Its syntax is always public static void main(String[] args). The only thing that can be changed is the name of the string array argument. For example, you can change args to myStringArgs.

What is a Class in Java?

A class is a group of objects with similar properties. It can also be seen as a template or blueprint from which different objects are created.

An example of the syntax to create a class:

class <class_name>{  
    // field;  
    // method;  
}

In the above syntax, we have fields (also called variables) and methods, which represent the state and behaviour of the object, respectively.

Note that in Java, we use fields to store data, while we use methods to perform operations.

Let's take an example:

We are going to create a class named “Anonymous” with a variable “x”. The variable “x” is going to store the value 5.

public class Anonymous { 

int x = 5; 
}

Note that a class should always start with an uppercase first letter, and the Java file should match the class name.

What is an Object in Java?

An object in Java is an instance of a class in Java, which means it’s a copy of a particular class. Objects in Java have three main characteristics: Identity, state, and behaviour.

  • Identity: Every object has a unique identifier. Such as an address in memory, an ID, or even a name.

  • State: The state monitors the behaviour of an object. The state of an object changes when the behaviour happens.

  • Behavior: Behavior describes what the object can do.

Examples of object identity, states, and behaviours in Java:

Let's look at some real-life examples of the states and behaviours that objects can have.

Example 1:

  • Identity: car.

  • State: colour, brand, weight, model.

  • Behaviour: brake, accelerate, turn, change gears.

Example 2:

  • Identity: house.

  • State: address, colour, location.

  • Behaviour: open door, close door, open blinds.

Syntax example of an object in Java:

public class Number {

int y = 10;

public static void main(String[] args) {

Number myObj = new Number();

System.out.println(myObj.y);

}

}

What is the Java Virtual Machine (JVM)?

The Java Virtual Machine (JVM) is an abstract Machine. JVM provides a runtime environment in which Java can be executed.

JVM is platform-dependent.

The JVM has just two main functions:

  • To allow Java programs to run on any device or operating system.

  • To manage and optimize program memory.

How Access Modifiers Work in Java

In Java, an access modifier specifies the accessibility of a method, constructor, class, or any other field.

These modifiers will determine whether a field, or method in a class can be used in another class or sub-class.

There are four types of access modifiers in Java:

  • Default: A default access modifier has its access level only within the package. Its access cannot occur from outside its scope. When an access level is not specified, it becomes a default.

Here is an example of a default access modifier in code:

class SampleClass 
{
    void output() 
       { 
           System.out.println("Hello Everyone! A Beginners Guide - An introduction to OOP…"); 
       } 
} 
class Main
{ 
    public static void main(String args[]) 
       {   
          SampleClass obj = new SampleClass(); 
          obj.output();  
       } 
}

What is this code doing:

void output(): When there is no access modifier, the program automatically takes the default modifier.

SampleClass obj = new SampleClass();: This line of code allows the program to access the class with the default access modifier.

obj.output();: This line of code allows the program to access the class method with the default access modifier.

The output is: Hello Everyone! A Beginners Guide - An Introduction to OOP…

  • Public: A public access modifier can be accessed everywhere. i.e. can be accessed within and outside the class or within and outside the package.

An example of how a public access modifier can be used:

// Car.java file
// public class
public class Car {
    // public variable
    public int tireCount;

    // public method
    public void display() {
        System.out.println("I am a Car.");
        System.out.println("I have " + tireCount + " tires.");
    }
}

// Main.java
public class Main {
    public static void main( String[] args ) {
        // accessing the public class
        Car car = new Car();

        // accessing the public variable
        car.tireCount = 4;
        // accessing the public method
        car.display();
    }
}

Output:

I am a Car.

I have 4 tires.

Let’s see what happens in this code:

  • The public class Car is accessed from the Main class.

  • The public variable tireCount is accessed from the Main class.

  • The public method display() is accessed from the Main class.




  • Private: A private access modifier has its access level only within the class. It cannot be accessed from outside the class.


Below is an example of what will happen when we try to access variables or methods declared private from outside the class:


class SampleClass 
{

    private String activity;
}

public class Main 
{

    public static void main(String[] main)
    {

        SampleClass task = new SampleClass();

        task.activity = "We are learning about the core concepts of OOP.";
    }
}

Okay, what’s going on here?


  • private String activity: The private access modifier makes the variable “activity” a private one.
  • SampleClass task = new SampleClass();: We have created an object of SampleClass.
  • task.activity = "We are learning about the core concepts of OOP."; On this line of code, we are trying to access the private variable and field from another class (which can never be accessible because of the private access modifier).

When we execute this code, the following error will be the output:

Main.java:49: error: activity has private access in SampleClass
        task.activity = "We are learning about the core concepts of OOP.";
            ^
1 error

This error occurred because we were trying to access the private variable and field from another class.

The best way to access these private variables is to use the getter and setter methods.

Getter and setter methods are used to access the values of class fields and also protect data.

Below is an example of how to use getter and setter methods to access private fields and variables:

class SampleClass 
{

    private String task;

    // This is the getter method.
    public String getTask() 
    {

        return this.task;
    }

    // This is the setter method.
    public void setTask(String task) 
    {

        this.task= task;
    }
}

public class Main 
{

    public static void main(String[] main)
    {

        SampleClass task = new SampleClass();

        // We want to access the private variable using the getter and   setter.

        task.setTask("We are learning about the core concepts of OOP.");

        System.out.println(task.getTask());
    }
}

When we execute the code, the output will look as follows:

We are learning about the core concepts of OOP.

As we have a private variable named task in the above example, we have used the methods getTask() and setTask() to access the variable from the outer class. These methods are called getter and setter in Java.

We have used the setter method (setTask()) to assign value to the variable and the getter method (getTask()) to access the variable.

  • Protected: A protected access modifier has its access level within the package and can only be accessed from outside the package with the help of a child class. In the absence of a child class, it cannot be accessed from outside the package.

A protected access modifier is somehow similar to a default access modifier. The only difference is its visibility in subclasses.

Here is an example of how we can use a protected access modifier:

// Multiplication.java

package learners;

public class Multiplication 
{

   protected int multiplyTwoNumbers(int a, int b)
   {

 return a*b;

   }

}

// Test.java

package javalearners;

import learners.*;

class Test extends Multiplication
{

   public static void main(String args[])
   {

 Test obj = new Test();

 System.out.println(obj.multiplyTwoNumbers(2, 4));

   }

} //output: 8

What this code does:

In the example above, the class Test which is present in another package can call the multiplyTwoNumbers() method, which is declared protected.

The method can do so because the Test class extends class Addition and the protected modifier allows the access of protected members in subclasses (in any package).

How Constructors Work in Java.

What are Constructors in Java?

Constructors are used to create the instance of a class. A constructor is a special type of method except for two differences which are: Its name is the same as the class name and it has no return type.

The constructor is called when an object of a class is created.

Syntax example of a Constructor in Java:

public class Main { 

int a;  

public Main() { 

a = 3 * 3; 

} 

public static void main(String[] args) { 

Main myObj = new Main();

System.out.println(myObj.a); 

} 

}

What’s going on in this code above;

  • We have started by creating the Main class.

  • After that, we created a class attribute, which is the variable a.

  • Third, we have created a class constructor for the Main class.

  • After that, we have set the initial value for variable a that we have declared. The variable a will have a value of 9. Our program will just take 3 times 3, which is equal to 9. You are free to assign any value to the variable a. (In programming, the symbol “*” means multiplication).

Every Java program starts its execution in the main() method. So, we have used the public static void main(String[] args), and that is the point from where the program starts its execution. In other words, the main() method is the entry point of every Java program.

How Methods Work in Java.

Methods are blocks of code that perform a specific task. Methods are also known as functions in some other programming languages.

There are two types of methods in Java:

  • User-defined Methods: These are methods created based on user requirements.
  • Standard Library Methods: These methods are built-in in Java and they are available for use immediately.

Below is an example of how to use methods in Java.

class Main {

  // create a method
  public int divideNumbers(int x, int y) {
    int division = x / y;
    // return value
    return division;
  }

  public static void main(String[] args) {

    int firstNumber = 4;
    int secondNumber = 2;

    // create an object of Main
    Main obj = new Main();
    // calling method
    int result = obj.divideNumbers(firstNumber, secondNumber);
    System.out.println("Dividing " + firstNumber + " by " + secondNumber + " is: " + result);
  }
}

The output will be;

Dividing 4 by 2 is: 2

In the above example, we have created a method named divideNumbers(). The method takes two parameters x and y, and we have called the method by passing two arguments firstNumber and secondNumber.

We have looked at the basics of programming in Java, now let’s take a deep dive into the principles of OOP.

Key Principles of OOP.

Four main key principles make a programming language Object-Oriented.

These four main principles are:

  1. Encapsulation

  2. Abstraction

  3. Inheritance

  4. Polymorphism

Encapsulation

Encapsulation in OOP is hiding data implementation by making sure it cannot have access to public methods.

An example of encapsulation is a handbag. Where a lady keeps all her belongings when going out.

Instance variables are made private and are only made public with the help of getter and setter methods.

Encapsulation is important to ensure that “critical” information is hidden from users like; passwords and date of birth etc.

Below is an example of Encapsulation with instance variables private and public accessor methods.

public class Employee {
   private String name;
   private Date dob;
   public String getName() {
       return name;
   }
   public void setName(String name) {
       this.name = name;
   }
   public Date getDob() {
       return dob;
   }
   public void setDob(Date dob) {
       this.dob = dob;
   }
}

In the above example, we are hiding the name and dob attributes in the person class.

Abstraction

Abstraction is a concept of OOP that lets you hide unnecessary data or show only important attributes in a class.

A simple example of abstraction is sending an email. The details about how the server will send the email to the receiver are abstracted from the user.

All the user needs to do is to enter the receiver's email, then the content of the email and the server will take care of making sure the email gets to the receiver.

A class does not require to know the inner details of another class, knowing the interfaces should suffice.

Example of Abstraction in Java:

// Abstract class
abstract class Animal {
  // Abstract method (does not have a body)
  public abstract void animalSound();
  // Regular method
  public void sleep() {
    System.out.println("Zzzz");
  }
}

// Subclass (inherit from Animal)
class Cow extends Animal {
  public void animalSound() {
    // The body of animalSound() is provided here
    System.out.println("The cow says: Moo");
  }
}

class Main {
  public static void main(String[] args) {
    Cow myCow = new Cow(); // Create a Cow object
    myCow.animalSound();
    myCow.sleep();
  }
}

Inheritance

Inheritance in Java creates a hierarchy between classes by inheriting attributes and methods from a superior class, meaning parent classes can extend attributes and methods to sub/child classes. Inheritance enables reusability.

A simple physical example is a child inheriting some DNA traits from the parent like; how to talk, body color, facial looks, how to walk, etc.

Syntax example of Inheritance

public class Parent { 
//methods and constructors 
} 
public class Child extends Parent { 
//inherits methods from Parent class 
}

Example 2

// Parent class 
class Animal { 
     public void sound() { 
      System.out.println("The animal makes a sound"); 
    } 
} 

// Child class inheriting from Animal 
class Dog extends Animal { 
     public void sound() { 
         System.out.println("The dog barks"); 
    } 
} 

// Child class inheriting from Animal 
class Cat extends Animal { 
     public void sound() { 
        System.out.println("The cat meows"); 
    } 
} 

public class Main { 
    public static void main(String[] args) { 
        Animal animal = new Animal(); 
        animal.sound(); 

        Dog dog = new Dog(); 
        dog.sound();

        Cat cat = new Cat(); 
        cat.sound(); 
    } 
}

For a child class to inherit from a parent class, you must use the extends keyword.

The extends keyword tells the program that you are making a child class that inherits its properties from a super or existing class.

Polymorphism

Polymorphism in Java is the ability to perform a single action in multiple ways. Like calling a single method in different classes. Polymorphism can also be referred to as when an object takes “many forms”.

Polymorphism can be a bit similar to inheritance.

Note: There are two types of polymorphism in Java: compile-time and runtime polymorphism. We will discuss that in a more advanced topic. For now, let’s focus on the basics.

Here is an example of polymorphism

// Parent class
class Animal {
    public void animalSound() { 
        System.out.println("The animal makes a sound"); 
    } 
}


// Child class 
class Dog extends Animal { 
    public void animalSound() { 
        System.out.println("The dog barks"); 
    } 
} 


// Child class
class Cat extends Animal { 
    public void animalSound() { 
        System.out.println("The cat meows"); 
    } 
} 

public class Main { 
    public static void main(String[] args) { 
        Animal myAnimal = new Animal(); 
        Animal myDog = new Dog(); 
        Animal myCat = new Cat(); 

        myAnimal.animalSound(); 
        myDog.animalSound(); 
        myCat.animalSound(); 
    } 
}

Polymorphism, like inheritance, is perfect for syntax or code reusability.

Interfaces in Java.

An interface in Java is a way of achieving abstraction.

Interfaces in Java can also be known as class blueprints that contain static constants and abstract methods.

Example of an interface:

// create an interface
interface Language {
  void getName(String name);
}

// class implements interface
class ProgrammingLanguage implements Language {

  // implementation of the abstract method
  public void getName(String name) {
    System.out.println("One of my favorite programming languages is: " + name);
  }
}

class Main {
  public static void main(String[] args) {
    ProgrammingLanguage language = new ProgrammingLanguage();
    language.getName("Java");
  }
}

Program output:

One of my favourite programming languages is: Java

Conclusion

We have come to the end of this wonderful article. Here we covered the basics of object-oriented programming concepts in Java programming language. It is important to have a rooted understanding of these core concepts to enable you to solve problems and build great projects.

Feel free to join any Java community to be able to ask questions and also gain deeper knowledge about Java and its implementations.

I do hope you find this article insightful and helpful. Happy learning!!!