Exploring object-oriented programming concepts with Java

Exploring object-oriented programming concepts with Java


Object-Oriented Programming (OOP)?is a programming paradigm that has been around for decades and is present in popular programming languages such as Java, Python, and C.

This method of structuring a program uses?objects?that have properties and behaviours. Java is a class-based, object-oriented programming language with a “write once, run anywhere” principle.

Today, we’ll learn about OOP concepts in Java. We’ll go over the basics of syntax and the core concepts. By the end, you will be able to create classes and initialize Java objects.

Today, we’ll go over:

  • Overview of OOP in Java
  • Objects in Java
  • Methods in Java
  • Classes in Java
  • Constructors in Java
  • Advanced OOP concepts
  • What to learn next

Overview of OOP in Java

Object-oriented programming, also referred to as OOP, is a programming?paradigm?based on the concept of?classes?and?objects. Objects have their own properties and behavior. A class is like a blueprint for creating objects.


In OOP, an object is defined with its own?properties. For example, say our object is an Employee. These properties could be their name, age, and role. OOP makes it easy to model real-world things and the relationships between them.

In fact, objects in a program frequently represent real-world objects. Many beginners prefer to use OOP languages because they are more intuitive. OOP also helps to solve the problem of complexity by dividing the program into different objects.

The four main principles of OOP are?inheritance,?encapsulation,?abstraction, and?polymorphism. We’ll explore these more later using Java.

Check out our article?What is Object-Oriented Programming??for a refresher on these four principles before continuing here.
No alt text provided for this image


If you are familiar with Java programming, you must have noticed that whenever a program is written it is written inside a?class, like the?public class. Generally speaking, this class is referred to as the?Main class. Even a basic program in Java is using classes, so?Java is an OOP language.

Simple example of Java OOP

We will explore this in more detail, but here’s a simple example to get you started. The following code creates different?Dog?objects and stores them.


public class Dog {};
Dog GermanShephered = new Dog();
Dog Bulldog = new Dog();
Dog Labrador = new Dog();        

Procedural vs. OOP

Procedural programming is another programming paradigm. In procedural programming, a program is divided into smaller parts called methods. These methods are the basic entities used in this technique. The focal point of procedural programming technique is to use methods for code reusability.


Object-Oriented Programming has the following advantages over procedural programming:

  • OOP provides a clear structure for the programs
  • OOP helps to keep the Java code DRY (Don’t Repeat Yourself)
  • OOP makes Java code easier to maintain, modify and debug
  • OOP makes it possible to create full reusable applications with less code and shorter development time

Definition:?DRY is a principle of software development aimed at reducing the repetition of software patterns by replacing them with abstractions or by using data normalization.


Objects in Java

In the real world, we can identify things with certain states and behaviors as an object. For example, a car has a name, color, and brand. We can classify these properties as their attributes or state and “driving” as their behavior.


In Java OOP, objects are similar. We create an object and define its states/behaviors. Objects are?instances of a class?or an entity with specific data. Think of a class as a blueprint for creating an object.

For example, we could have the class?Car?and an instance of that class be?Truck1?with the attributes?ford,?blue, and?used.

Note:?An object and an instance are the same things. The word?instance?indicates the relationship of an object to its class.


An object has three major characteristics:

  • State:?represents the data (or value) of an object.
  • Behavior:?represents the functionality of objects, shown via methods.
  • Identity:?An object identity is implemented via a unique ID. The value is used internally by the Java Virtual Machine (JVM) to identify each object.


How to create an object in Java

The following are the steps followed when you want to create an object:


  1. Declaration:?A variable declaration with a variable name with an object type. You declare a variable by writing:


type objectName;        

  1. Instantiation:?In Java, the?new?keyword is used to create an instance of the object. The?new?keyword allocates memory for the new object and returns a reference to that memory.
  2. Initialization:?The?new?keyword is followed by a call to a constructor. This call initializes the new object. To initialize an object is to store data in the object.


Methods in Java

Methods are used to perform certain?actions. They represent the behavior of an object. They can either be?public?or?private, i.e, cannot be accessed from outside, but must be?declared within a class. Methods can be defined as a group of statements that perform some operations and may or may not return a result.


Continuing with our car analogy, the following code snippet shows an example of a method in Java:

class Car {

  // Public method to print speed
  public void printSpeed(int speed) {
    System.out.println("Speed: " + speed);
    }
}
class Demo {
  public static void main(String args[]) {
    Car car = new Car();
    car.printSpeed(100); // calling public method
  }
}
-->
Speed: 100        

Method?parameters?are used to pass data into a method, and the return type gets a value from the method if any. There are two popular types of method in OOP:

  • The?get?method which obtains the value of a particular data field
  • The?set?method sets its value.


class Demo {

   public static void main(String args[]) {
     Car car = new Car();
     car.setSpeed(100); // calling the setter method
     System.out.println(car.getSpeed()); // calling the getter method
   } 
}        

Two or more methods can have the same name if they differ in number or types of parameters. This allows a method to perform different operations based on the nature of its arguments. This concept is referred to as?method overloading.

Method overloading is an example of Static Polymorphism. Polymorphism is an important OOP concept that we’ll explore later.


Classes in Java

A class is a?group of objects?that have common properties. They are used to create user-defined data types. Think of a?Class?like an object constructor, or a "blueprint" for creating objects. We can use basic data types to create our classes. Classes can contain multiple methods, variables, constructors, and functions.


Some benefits of using classes include:

  • They make it easy to create complex objects and applications in Java
  • They ensure code reusability
  • It allows for easy maintenance of different parts of an application


How to declare a class in Java

In Java, classes are defined like below. Here, the?class?command tells the compiler that we are creating our custom class. All the members of the class will be defined within the class scope.


class ClassName { // Class name

  /* All member variables
  and methods*/
}        

Let’s take a look at the structure of a class. Notice how the?{ }?hold all of the members of the class.

//The Structure of a Java Class
class Car { // Class name
  // Class Data members
  int topSpeed;
  int totalSeats;
  int fuelCapacity;
  String manufacturer;
  // Class Methods
  void refuel(){
    ...
  }
  void park(){
    ...
  }
  void drive(){
    ...
  }
}        

Once we create a class, we need to define objects, or instances of that class. The name of the class,?ClassName, will be used to create an instance of the class in our main program. We can create an object of a class by using the keyword?new:

class ClassName { // Class name
  ...
    // Main method
    public static void main(String args[]) {
    ClassName obj = new ClassName(); // className object
  }
}        

Abstract classes

In programing, abstraction is a process of removing or hiding attributes of an object or a system to buttress attributes of greater importance. In Java, abstraction can be achieved with either abstract classes or interfaces.


An abstract class is a?restricted class?that cannot be used to create objects and can only be accessed through inheritance. These kinds of classes are declared using the?abstract?keyword.

An abstract class can have an abstract method, unlike a regular class. An abstract method has no body or definition and must not be private, its declaration should have:

  • An access identifier
  • The keyword?abstract
  • A return type
  • A name of the method
  • The parameter(s) to be passed
  • A semicolon?;?to end the declaration

An abstract class can have everything else as same as a normal Java class has, i.e. constructor, static variables, and methods.

Constructors in Java

Constructors are used for?initializing new object states. They assign values to the class variable when the object is created. A constructor is declared with the same name as its class name and has no return type. It is a good practice to declare/define it as the first member method.


Like methods, constructors can be overloaded. Constructors differ from methods as they have no return type. Secondly, constructors are only called once when creating an object.

There are 2 major types of constructors:

  • Default Constructor:?This is also known as a no-argument constructor. It is the most basic type of constructor. Here, the default values of for data members of the class are defined, which creates an object with data members initialized with default values.
  • Parameterized Constructor:?In a parameterized constructor, we pass arguments to the constructor and set them as the values of our data members. They are used to set fields of a class with your own values.

If a constructor is not defined within a class, the JVC will insert a default constructor without an argument and set its arguments to null or zero.


The following code snippet will help you to get a better understanding of default and parameterized constructors. Here, we have a?Date?class, with its default constructor, and we’ll create an object out of it in our?main():

class Date {

  private int day;
  private int month;
  private int year;
  // Default constructor
  public Date() {
    // We must define the default values for day, month, and year
    day = 0;
    month = 0;
    year = 0;
  }
  // Parameterized constructor
  public Date(int d, int m, int y){
    // The arguments are used as values
    day = d;
    month = m;
    year = y;
  }
  // A simple print function
  public void printDate(){
    System.out.println("Date: " + day + "/" + month + "/" + year);
  }
}
class Demo {
  public static void main(String args[]) {
    // Call the Date constructor to create its object;
    Date paramDate = new Date(1, 8, 2018); // Object created with specified values!
    Date defaultDate = new Date(); // Object created with default values!
    paramDate.printDate();
    defaultDate.printDate();
  }
}
-->
Date: 1/8/2018
Date: 0/0/0        

Advanced OOP concepts in Java

Encapsulation

Encapsulation is a technique in OOP that is used to achieve data hiding. Think of encapsulation as a protective cover that prevents data from being accessed by any code outside its class.


It can be achieved by declaring variables in the class as private and declaring public methods for getting and setting the values of variables.

Encapsulation allows classes to have total?control?over what is stored in their fields. It also increases?flexibility?as we can decide which variables have read/write privileges.

A good example of encapsulation would be implementing?authorization. The username and password fields would be declared private. To those data, public methods would be implemented.

Simplified:?Fields containing data are private, and public methods provide an interface to access those fields.


Inheritance in Java

Inheritance is an important principle in OOP. In Java, inheritance is a mechanism in which a child class?inherits attributes?from a parent class.


When a child class is defined, it is based on an existing class (parent class), and it extends the common methods or data members of the parent class. The derived class?extends?from the base class in order to inherit its properties.

Inheritance supports?reusability, which is very important in object-oriented programming. It can help us upgrade specific parts of our Java code without changing its core attributes.

The?this?keyword in Java is used to refer to the instance of the current class.
In a similar fashion, the?super?keyword in Java is used to refer to the?SuperClass?members from inside the immediate?Subclass.

Polymorphism in Java

Polymorphism is an OOP feature that allows for differentiation between entities with the same name. It allows us to perform a single action in different ways. Polymorphism is used in Java because it helps us reuse code. A single variable can be used to store multiple data types.


Simplified:?Polymorphism refers to the same object exhibiting different forms and behaviors.


A good example would be having a class?Shape?which has a?getArea()?method for finding the area of different shapes. The Shape class would have only one public method,?getArea().

We could then have classes that extend the?Shape?class, for example,?Rectangle?and?Circle?classes. Each class would implement the?getArea()?method differently. Let’s see what that would look like with the following code:

// A sample class Shape which provides a method to get the Shape's area

class Shape {
  public double getArea() {
    return 0;
  }
}
// A Rectangle is a Shape with a specific width and height
class Rectangle extends Shape {   // extended form the Shape class
  private double width;
  private double height;
  public Rectangle(double width, double heigh) {
    this.width = width;
    this.height = heigh;
  }
  public double getArea() {
    return width * height;
  }
}
// A Circle is a Shape with a specific radius
class Circle extends Shape {
  private double radius;
  public Circle(double radius) {
    this.radius = radius;
  }
  public double getArea() {
    return 3.14 * radius * radius;
  }
}
class driver {
  public static void main(String args[]) {
    Shape[] shape = new Shape[2]; // Creating shape array of size 2
    shape[0] = new Circle(2); // creating circle object at index 0
    shape[1] = new Rectangle(2, 2); // creating rectangle object at index 1
    System.out.println("Area of the Circle: " + shape[0].getArea());
    System.out.println("Area of the Rectangle: " + shape[1].getArea());
  }
}
-->
Area of the Circle: 12.56
Area of the Rectangle: 4.0        

There are two types of Polymorphism in OOP. Polymorphism that is resolved during compile time is known as?Static polymorphism.?Method overloading is a perfect example of static polymorphism.

Dynamic polymorphism?on the other hand is resolved during run time. Method overriding is used in dynamic polymorphism. It involves redefining a parent class’s method in a subclass.

This enables the child class to give its implementation to a method provided by the parent class. The parent class method is then called the overridden method, while the methods in the child classes would be called overriding methods.

(source="internet")

要查看或添加评论,请登录

社区洞察

其他会员也浏览了