Object Programming  «Prev  Next»
Lesson 1

Object Oriented Programming in Java

Java is an OOP language, which means that Java programs are developed as groups of interrelated objects. This module introduces you to object-oriented programming (OOP) and the role it plays in Java. OOP concepts such as objects, classes, inheritance, and methods will be discussed. The coverage of each concept is followed up by example Java code. The OOP skills you will learn in this module provide a background that is necessary when it comes to developing effective Java programs.
  • Module Learning Objectives
    After completing the module, you will have the skills and knowledge necessary to:
    1. Understand the relationship between classes and objects
    2. Create simple class definitions
    3. Add behavior to classes using methods


Object-Oriented Programming (OOP) in Java SE 17

Object-Oriented Programming (OOP) in Java SE 17 is a fundamental concept that structures programs around objects, which can encapsulate data and behavior. Here is how OOP principles are used in Java SE 17:
  1. Classes and Objects
    • Classes: Define the blueprint or template for objects. A class in Java contains fields (attributes) and methods (behaviors) that represent an object’s state and behavior.
    • Objects: Instances of classes that hold data (attributes) and have methods to perform actions. Objects interact with each other to solve problems and build functionality.
  2. Encapsulation
    • Encapsulation is the principle of bundling data (fields) and methods (behaviors) that operate on the data into a single unit (class)
    • You use access modifiers (private, public, protected) to restrict or allow access to the data. For example:
      public class Car {
        private String color;  // Field is private
      
        // Getter method to access the field
        public String getColor() {
      	  return color;
        }
      
        // Setter method to modify the field
        public void setColor(String color) {
      	  this.color = color;
        }
      }
      
    • Benefits: Encapsulation provides data protection, improves modularity, and makes it easier to maintain code.
  3. Inheritance
    • Inheritance allows a new class to inherit properties and methods from an existing class. The extends keyword is used to create a child class (subclass) that inherits from a parent class (superclass).
    • Example:
        // Superclass
        public class Animal {
      	  public void eat() {
      		  System.out.println("This animal eats food");
      	  }
        }
      
        // Subclass
        public class Dog extends Animal {
      	  public void bark() {
      		  System.out.println("The dog barks");
      	  }
        }
      
        public class Main {
      	  public static void main(String[] args) {
      		  Dog myDog = new Dog();
      		  myDog.eat(); // Inherited method
      		  myDog.bark(); // Method in Dog class
      	  }
        }
        
    • Benefits: Inheritance promotes code reuse and establishes a parent-child relationship.
  4. Polymorphism
    • Polymorphism allows one interface to be used for a general class of actions. It is implemented in two ways:
    • Compile-time Polymorphism (Method Overloading): Methods in the same class with the same name but different parameter lists.
    • Run-time Polymorphism (Method Overriding): Methods in a subclass with the same name and signature as in the superclass, which are overridden to provide specific functionality.
    • Example:
        // Method Overloading
        public class MathUtils {
      	  public int add(int a, int b) {
      		  return a + b;
      	  }
      
      	  public double add(double a, double b) {
      		  return a + b;
      	  }
        }
      
        // Method Overriding
        public class Animal {
      	  public void sound() {
      		  System.out.println("Some generic animal sound");
      	  }
        }
      
        public class Dog extends Animal {
      	  @Override
      	  public void sound() {
      		  System.out.println("The dog barks");
      	  }
        }
        
  5. Abstraction
    • Abstraction is the concept of hiding complex implementation details and exposing only the necessary features. This is achieved using:
    • Abstract Classes: Classes that cannot be instantiated and may contain abstract (unimplemented) and concrete (implemented) methods.
    • Interfaces: Define a contract that implementing classes must follow, using the interface keyword.
    • Example of an abstract class:
        abstract class Vehicle {
      	  abstract void start(); // Abstract method
      
      	  void stop() {
      		  System.out.println("Vehicle stopped");
      	  }
        }
      
        class Car extends Vehicle {
      
      	  @Override
      	  void start() {
      		  System.out.println("Car started");
      	  }
        }
        
    • Example of an interface:
        interface Animal {
      	  void sound();
        }
      
        class Dog implements Animal {
      	  @Override
      	  public void sound() {
      		  System.out.println("The dog barks");
      	  }
        }
        


  6. Interfaces and Functional Programming
    • Java SE 17 supports functional programming concepts like lambda expressions and functional interfaces. A functional interface is an interface with a single abstract method, making it suitable for lambda expressions.
    • Example of a functional interface:
        @FunctionalInterface
        interface Greeting {
      	  void sayHello();
        }
      
        public class Main {
      	  public static void main(String[] args) {
      		  Greeting greeting = () -> System.out.println("Hello, world!");
      		  greeting.sayHello();
      	  }
        }
        
  7. Modules (Introduced in Java 9)
    • Java SE 17 continues to use the Java Platform Module System to manage modular code. You can organize classes into modules, enhancing encapsulation at a higher level.
    • Example of a module-info.java file:
      module com.example.myapp {
        exports com.example.myapp.service;
      }
      

Summary
  • Encapsulation: Protects data through access control.
  • Inheritance: Facilitates code reuse and a hierarchical relationship.
  • Polymorphism: Provides flexibility in method usage and behavior.
  • Abstraction: Hides complexity and exposes simple interfaces.
These principles work together to make Java SE 17 a robust and versatile OOP language, enabling developers to create modular, maintainable, and scalable applications.


What Is an Object?

Objects are key to understanding object-oriented technology. Look around right now and you'll find many examples of real-world objects: your dog, your desk, your television set, your bicycle. Real-world objects share two characteristics: They all have state and behavior. Dogs have state (name, color, breed, hungry) and behavior (barking, fetching, wagging tail). Bicycles also have state (current gear, current pedal cadence, current speed) and behavior (changing gear, changing pedal cadence, applying brakes). Identifying the state and behavior for real-world objects is a great way to begin thinking in terms of object-oriented programming.
Take a minute right now to observe the real-world objects that are in your immediate area. For each object that you see, ask yourself two questions:
  1. "What possible states can this object be in?" and
  2. "What possible behavior can this object perform?".

Make sure to write down your observations. As you do, you will notice that real-world objects vary in complexity; your desktop lamp may have only two possible states (on and off) and two possible behaviors (turn on, turn off), but your desktop radio might have additional states (on, off, current volume, current station) and behavior (turn on, turn off, increase volume, decrease volume, seek, scan, and tune). You may also notice that some objects, in turn, will also contain other objects. These real-world observations all translate into the world of object-oriented programming.

SEMrush Software