Principles of Object-Oriented Programming in Java
Principles of Object-Oriented Programming in Java
Contents
Introduction
What is Object Oriented Programming?
Why is OOP Important?
Object-Oriented Languages
OOP Elements in Java
Class
Object
OOP Concepts in Java
Encapsulation in Java
Data Abstraction in Java
Abstract Classes
Interfaces
Inheritance in Java
Polymorphism in Java
Object Association: Composition and Aggregation
Object Association
Object Composition
Object-Oriented Modeling (OOM)
Steps in Object-Oriented Modeling
Summary – OOP Concepts in Java
Want to learn more?
Software deals in data. `To effectively utilize data, you need to parse data to make sense
of it, analyze data, update data, store data, and so on. So, how do you deal with and make
sense of all this data? Object Oriented Programming!
Object Oriented Programming (OOP) allows you to model data – and the
methods/functions that act on that data – in an intuitive way. Once you’ve modeled the
required data classes and objects the application needs, you can interact with that data
in a logical way.
OOP uses classes to define the data model and provide simple, reusable blueprints for
creating objects. By allowing us to model the world around us in an intuitive way, OOP
vastly reduces software complexity, development time, and maintenance.
For instance, if you are building an application that manages a restaurant, you would
have classes such as Restaurant, Menu, MenuItem, Beverage, Employee, and Guest. Once
you have the classes that map out the application, you can quickly associate, compare,
update, collate, and analyze all the data in that model.
You can also map these objects to databases and communicate with other services on
the web using these objects in JSON.
Object-Oriented Languages
Object Oriented Languages are programming languages with OOP features. There are
two main categories of Object Oriented Languages (OOLs):
1. Class-based OOLs: In these, classes are defined first, and objects are instances of
classes. Some examples of these languages are C++, Java, Ruby, Scala, and Eiffel.
2. Classless OOLs: In these, objects are cloned from their prototypes. Every object can
have only one prototype link. Some examples of these languages are Self and
Haskel.
Many languages, however, fall outside of these two categories. An example is Javascript,
which has some properties of each of the two types.
If AI is the future, then Python, Data Science, are Machine Learning are the
path
Learn Jupyter Lab, Numpy, Matplotlib, Seaborn, Pandas, Scikit Learn, and
much more
The average annual salary for a Data Scientist in the U.S. ranges from $125K -
$203K USD
The average annual salary for a Machine Learning Engineer in the U.S. ranges
from $131K - $210K USD
Join CodingNomads' membership program to take your skills to the next level
and land your dream job
Classes, in their purest form, define two major aspects of an object: the data and
methods. The data is stored as instance variables of different types. This data is used to
describe objects of the said class. The methods describe actions that can be performed
on that data.
Instance variables are declared outside of methods and exist as class members. Each
instance of a class – as well as each object – gets its own instance variables.
The best way to understand the class/object relationship is to look at an example. In the
code below, we created a basic class called Vehicle, which can tell us the number of
passengers and fuel capacity:
class Vehicle{
//declaration of instance variable storing num of passengers
private int passengers;
// method that returns the number of passengers
public int getPassengers() {
return passengers;
}
// method “sets” the number of passengers
public void setPassengers(int numPassengers){
This.passengers = numPassengers;
}
}
Now that we have created a class, we can create Objects from this class:
class Example {
public static void main(String[] args){
// create a new object of type Vehicle named "myVehicle"
Vehicle myVehicle = new Vehicle();
// then we can set the instance variables in the myVehicle ob
myVehicle.setPassengers(5);
// then we can also access the methods within the myVehicle o
System.out.println(myVehicle.getPassengers());
}
}
Source: Javatpoint
Object
Objects are used to store data, act on that data, and interact with other objects. Each
time you create an object (aka an instance ) of a class, you create an object that
contains its own copies of each instance variable found in the class. For example, each
instance – or object – of the Vehicle class has its own instance variables, passengers and
fuelCap.
class Example {
public static void main(String[] args){
// create a new object of type Vehicle named "myVehicle1"
Vehicle myVehicle1 = new Vehicle();
// then you can set the instance variables in the myVehicle1
myVehicle1.setPassengers(5)
Vehicle myVehicle2 = new Vehicle();
// then you can set the instance variables in the myVehicle2
myVehicle2.setpassengers(11);
// then you can also access the methods within the myVehicle
System.out.println(myVehicle1.getPassengers()); //prints 5
System.out.println(myVehicle2.getPassengers()); //prints 11
}
}
Now, since each object has its own copies of the instance variables, you can set them to
hold distinct values.
State: An object’s state is defined by the object's instance variables and by the
values these have. Thus, you can alter the state of an object by changing the values
of the instance variables.
Behavior: An object’s behavior is defined by its methods. When an object wants to
act on another object, it uses that object’s methods. For security reasons, not all of
the object’s methods are visible to other objects.
Identity: The identity of an object is independent of its instance variables or
methods. For example, two vehicles with the same number of passengers and fuel
cap are still two different objects.
Source: Javatpoint
Encapsulation in Java
Encapsulation in Java is the process of wrapping up variables (data) and the methods
(code) that act on that data together as a single unit within a class.
For example, suppose you have two classes – Car and Dog. The Dog class and the Car
class are two entirely distinct entities unrelated to each other. Their data (instance
variables), and their methods which act on that data are encapsulated within their
respective classes. This means all data and methods related to a car will be in the Car
class. All data and methods related to a dog will be in the Dog class. You can create as
many objects of these classes as you want.
class Car {
String make;
String model;
public void drive(int distance){
// some action(s) to drive the car
}
}
Another example depicted below is a Box class, in which we create three instances – or
objects – of the Box class.
Data Abstraction in Java
Abstraction in Java is the act of hiding unnecessary details and only showing essential
information to the user. For example, a driver sees a car as a car, rather than as its
individual components.
Abstract Classes
Abstract classes are restricted classes that cannot be used to create objects. The
instance variables of an abstract class can be accessed when inherited from another
class. Abstract methods are methods present only in abstract classes which do not have
a body. The body is provided by a subclass that inherits from the abstract class. If a class
has even one abstract method, it is an abstract class.
class AbstractClassDemo {
public static void main(String[] args) {
Car myCar = new Car(); // Create a Car object
Int wheels = myCar.numberOfWheels();
myCar.start();
}
}
Interfaces
Interfaces are completely abstract classes that can be used to group related methods.
Interfaces do not have any non-abstract methods, while abstract classes can have non-
abstract methods.
interface Vehicle{
public abstract int numberOfWheels();
public abstract void start();
}
class AbstractClassDemo {
public static void main(String[] args) {
Car myCar = new Car(); // Create a Car object
int wheels = myCar.numberOfWheels();
myCar.start();
}
}
Inheritance in Java
Inheritance is when one object acquires many of the properties and behaviors of a
parent object.
Inheritance provides code reusability, allowing us to minimize redundant code by
organizing shared attributes in parent classes – known as superclasses. OOP languages
enable a class to add a superclass when it’s declared. Child classes – aka subclasses –
inherit all public and protected variables and methods from their superclasses.
Using a visual example, “Red Apple” and “Green Apple” only need to define what makes
them unique from each other. Their shared attributes will reside within the (parent)
Apple class. The attributes shared between Apple and Orange will live within the Fruit
class.
class CarDemo {
public static void main(String[] args){
SportsCar ferrari = new SportsCar();
//below, we are using the "make" variable, which is defined
Ferrari.make = "Ferrari";
//below, we are using the "model" variable, which is defined
Ferrari.model = "599 XX";
//below, we are using the "hasSpoiler" variable, which is de
Ferrari.hasSpoiler = true;
//below, we are using the "hasRaceTires" variable, which is d
Ferrari.hasRaceTires = true;
//below we are using the "drive()" method which is defined in
ferrari.drive(20);
//below, we are using the "getZeroToSixtyTime" method, which
double time = ferrari.getZeroToSixtyTime();
//...
}
}
An object of the SportsCar class has direct access to all public and protected members
of the Car class. The SportsCar class may use the public and protected variables and
methods in the Car class as though they are their own, as though they were defined in the
SportsCar class. That said, the Car class has no knowledge of the SportsCar class.
Polymorphism in Java
Polymorphism is the ability of an object to take on many forms, thereby allowing a
method to perform different actions based on which object the method is called upon.
For example, in the depiction below, we use the steering wheel in the center as an
analogy for polymorphism in Java. No matter what car you’re driving, there is a steering
wheel. The steering wheel remains constant; however, depending on what type of car
you’re driving – a sports car vs. a vintage car vs. a semi-truck – the mechanism behind the
wheel and the behavior produced can be quite different.
Using the polymorphism OOP concept in Java, we can replicate a concept to make our
code easier, more flexible, and more intuitive.
One great example of polymorphism is the System.out.println() method that we all
use so frequently. It looks like a single method println() – but how does it work in so
many different ways if it's a single method?
For instance, if Java is a strongly typed language, how can a single method take an int, a
double, a String, an object, a char, etc., as a parameter? How is this possible?
Polymorphism. What looks like a single method println() is actually nine separate
methods. Each method takes a different parameter type and has a slightly different
behavior to accomplish the goal of printing that value.
//...
}
public void println(char x) {
//..
}
}
public void println(int x) {
// ...
}
To override a method in a parent class, the child class must declare a method with the
same return type, name, and parameters. The method signatures must match exactly.
@Override is an optional Java annotation that communicates that this method overrides
a method in a parent class.
// parent class Vehicle
class Vehicle {
int mpg;
int fuel_capacity;
String type;
class OverrideDemo {
public static void main(String[] args){
Vehicle vehicle = new Vehicle();
Vehicle moto = new Motorcycle();
// now invoke the start() method on the Motorcycle
// which overrides the start() method in the Vehicle class
moto.start();
// now invoke the start() method on the Vehicle object
// (which will call the start() method in the Vehicle class)
vehicle.start();
}
}
In the example above, the start() method of the Vehicle class is overridden in the
Motorcycle class. This makes perfect sense; while most vehicles start similarly, a
motorcycle has different steps and actions required to start it.
For instance, most motorcycles have a kick-start. Using the concept of overriding, we
can treat a motorcycle as a vehicle like any other, but we can define specific behaviors to
the start() method depending on which type of vehicle we’re dealing with.
Object Association
Object Association is when there is a relationship between objects of two different
classes. For example, we can associate a “Student” with a “Car”. But a student is not
comprised of a car. And a car is not comprised of a student. They are two unique objects
that can be associated. For example:
In the example above, we are “associating the Student and Car. But they are not
codependent. Each can and does exist independently of the other.
Object Composition
Object Composition is what happens when one class is comprised of one or more other
classes. Object composition forms a “part-of” relationship between the two classes. For
example, a Vehicle class is a composition of the Battery and Engine classes. When the
vehicle is destroyed, its components are also destroyed. For example:
Battery battery;
Engine engine;
In the example above, the Vehicle class contains both the Battery and Engine
classes as instance variables. The Vehicle class is composed of multiple sub-objects.
The Vehicle, in this case, much as is the case in the real world, cannot exist without a
Battery and an Engine. This is object composition.
The aggregation association between two or more classes is when the classes can exist
independently but as a group can be interpreted as a larger concept. The classes have a
unidirectional, “has-a” relationship with each other. For example, a Company class is an
aggregation of many objects of the Person class (its employees). However, if the
company ends, the persons will continue to exist.
For example, to build a restaurant management system, you may need to model different
objects such as Restaurant, Menu, MenuItem, Beverage, Employee, and Guest. An
employee may have some attributes irrelevant to the restaurant management system,
such as their hobbies or least favorite color. These are not included in the instance
variables for the Employee class.
Identification of classes
Identification of instance variables of the classes
Identification of methods of the classes
Identification of relationships between classes
Once these elements are identified, you can begin using OOP concepts in Java!
Get Started
Summary – OOP Concepts in Java
OOP simplifies software development and maintenance by allowing us to model the world
around us logically and intuitively. With OOP, you can define the data model and required
functionality once and reuse it everywhere, reducing complexity and development time.
OOP organizes code around data, aka “objects”, instead of functions and logic. OOP uses
classes as blueprints for creating objects. The four main OOP concepts in Java include:
1. Encapsulation: The process of wrapping up data and the methods that operate on
that data together as a single unit within a class. For example, all data and methods
related to a cat will be in the Cat class. All data and methods related to a dog will be
in the Dog class.
2. Data Abstraction: The process of hiding unnecessary details from the user and only
showing essential information and, for example, showing a car as a car rather than
an axle, wheels, doors, windshield, engine, muffler, radiator, etc.
3. Inheritance: When one object acquires many of the properties and behaviors of a
parent object. For example, a Red Apple class and a Green Apple class both inherit
many properties from the Apple class, inheriting many of its properties from the
Fruit class.
4. Polymorphism: Polymorphism is the ability of an object to take on many forms,
thereby allowing a method to perform different actions based on which object the
method is called upon. For example, the steering wheel in a semi-truck acts quite
differently than the steering wheel in a sports car, even though they are both still
steering wheels.
Login
Cookie Policy