Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
26 views

Principles of Object-Oriented Programming in Java

Uploaded by

BSI BARGARH
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

Principles of Object-Oriented Programming in Java

Uploaded by

BSI BARGARH
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

Blog Post

OOP Concepts in Java


33 min to complete · By Ryan Desmond

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.

Continue reading about Object Oriented Programming, OOP Concepts, Elements,


Languages, Modeling, and more.
What is Object Oriented Programming?
Object Oriented Programming is a coding paradigm that organizes code around data, aka
“objects”, rather than functions and procedures. OOP simplifies software development
by enabling us to model any data that we need and work 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.

Why is OOP Important?


1. Reduces complexity: OOP promotes data reuse, helping reduce development time
and complexity. Using OOP concepts in Java, you can write a functionality once and
reuse it everywhere else.
2. Reduces maintenance time: OOP makes projects modular, allowing you to isolate
and solve issues more efficiently. For example, if the bill amount is incorrect, the
problem is with the Bill class, and one can go directly there and start debugging.
3. Widely applicable: OOP can be used to model any scenario imaginable, making it
highly useful and applicable in various business use cases.

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.

Want to become a Data Scientist


or Machine Learning Engineer?
Data Science (DS) and Machine Learning (ML) are two of the most useful skills
you can develop to future-proof your career

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

Learn DS/ML Now

OOP Elements in Java


Class
A Class is a template – or a blueprint – that defines the form of an object. A class
specifies the data and the code that acts on objects within that class. Objects are
instances of a class, while data members are instance variables.

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.

All objects have three essential features:

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

OOP Concepts in Java


There are four primary OOP concepts in Java: Encapsulation, Data Abstraction,
Polymorphism, and Inheritance.

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.

Abstraction can be achieved with either abstract classes or interfaces.

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.

abstract class Vehicle{


// Abstract method - the method below does not have a “method body
public abstract int numberOfWheels();

// Below is a standard method with a body


public void start() {
System.out.println("Starting vehicle.");
}
}

// Subclass (inherits from Vehicle)


class Car extends Vehicle{
public int numberOfWheels() {
// The method body of numberOfWheels() is provided here
System.out.println("Car has 4 wheels");
return 4;
}
}

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 that implements the Vehicle interface


class Car implements Vehicle{
public int numberOfWheels() {
System.out.println("Car has 4 wheels");
return 4;
}
public void start() {
System.out.println("Starting car.");
}
}

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.

For example, using code:


class Car {
public String make;
public String model;
public void drive(int distance){
// some action(s) to drive the car
}
}

class SportsCar extends Car {


boolean hasRaceTires;
boolean hasSpoiler;
public double getZerotoSixtyTime(){
// do something to determine time from zero to sixty MPH
}
}

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(boolean x) { Copy

//...
}
public void println(char x) {
//..
}
}
public void println(int x) {
// ...
}

// and there are 6 more println() methods

The polymorphism demonstrated by println() results from “overloading”. In this case,


the println() method is “overloaded” nine times in the Java source code. This allows
us to call this method in nine different ways. That said, to the end-user, it looks like a
single method.

Another great example of polymorphism in Java is the concept of “overriding”. In this


case, a parent class can define a method, and a child class can override the behavior of
the parent class. This is where Inheritance and Polymorphism overlap.

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;

// parent method start()


public void start(){
System.out.println("Vehicle starting...");
// do steps to start a vehicle
}
}

// child class Motorcycle


class Motorcycle extends Vehicle {
Motorcycle(){
mpg = 30;
fuel_capacity = 10;
type = "motorcycle";
}

// the method below overrides the behavior of the start() method


@Override
public void start(){
System.out.println("Motorcycle starting...");
// do steps to start a motorcycle
}
}

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: Composition and Aggregation


Now that you understand the core OOP concepts in Java, the next step is to consider how
all these objects interact with or relate to one another. In short, we can associate objects
with one another, we can create objects that are composed of other objects, and we can
aggregate objects that, as a whole, represent a larger concept. Let’s take a look at each
below.

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:

Student student = new Student(...);


Car car = new Car(...);
System.out.println(student.name + “ drives a “ + car.brand);

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:

public class Vehicle {

Battery battery;
Engine engine;

public Vehicle(Battery battery, Vehicle vehicle){


this.battery = battery;
this.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.

Object-Oriented Modeling (OOM)


Now that you understand OOP concepts and Object Association, Object-oriented
modeling (OOM) is the first step in actual development when using an object-oriented
approach. Here, you model the problem by creating classes corresponding to real-world
entities. Only the attributes and behaviors of the object relevant to the current task at
hand are retained, and the others are discarded.

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.

Steps in Object-Oriented Modeling


Object-oriented modeling typically has the following steps:

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!

Ready to start making serious progress?


Join Premium Membership and get:

Award-winning support on CodingNomads' private Discord server


Unlimited access to 1500+ written tutorials and 700+ video tutorials
Hands-on practice with IDEs, quizzes, journals, labs, challenges, and
interactive features
Professional credibility with hosted and shareable completion certificates
(example)

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.

Want to learn more?


If you’d like to diver even deeper into OOP concepts in Java and to build OOP projects on
your own, click below to check out CodingNomads’ Java Programming Courses and Java
Career Track.

READ NEXT: TOP 7 REASONS TO LEARN JAVA


Create an account and accelerate your career

Login

Beginner - Intermediate Courses Intermediate - Advanced Courses


Java Programming Spring Framework
Python Programming Data Science + Machine Learning
JavaScript Programming Deep Learning with Python
Git & GitHub Django Web Development
SQL + Databases Flask Web Development

Career Tracks Resources


Java Engineering Career Track About CodingNomads
Python Web Dev Career Track Corporate Partnerships
Data Science / ML Career Track Contact us
Career Services Blog
Discord

© 2016-2024 CodingNomads LLC All Rights Reserved admin@codingnomads.com +1.415.523.4643


Privacy Policy Terms of Use Acceptable Use Policy Disclaimer DSAR Consent Preferences

Cookie Policy

You might also like