Download as pdf or txt
Download as pdf or txt
You are on page 1of 36

BASIC CONCEPTS

IN JAVA
OBJECTIVES:
1. Explain and use the basic object-
oriented concepts in your programs

► CLASS
► OBJECT
► ATTRIBUTE
► METHOD
► CONSTRUCTOR
OBJECTIVES:
2. Describe advanced object-oriented
concepts and apply them in
programming as well.

► PACKAGE ► INHERITANCE
► ESCAPSULATION ► POLYMORPHISM
► ABSTRACTION ► INTERFACE
OBJECTIVES:

3. Describe and use this, super, final, and


static keywords.

4. Differentiate between method


overloading and method overriding.
Object-Oriented Design
Object-oriented design is a technique that focuses design
on objects and classes based on real world scenarios. It
emphasizes state, behavior and interaction of objects. It
provides the benefits of faster development, increased
quality, easier maintenance, enhanced modifiability and
increase software reuse.

It is the process of planning a system of interacting objects


for the purpose of solving a software problem.
While Procedural programming is about writing procedures or methods
that perform operations on the data, Object-oriented programming is
about creating objects that contain both data and methods.

Object-oriented programming has several advantages over procedural


programming:

• OOP is faster and easier to execute.


• OOP provides a clear structure for the programs.
• OOP helps to keep the Java code DRY "Don't Repeat Yourself", and
makes the code easier to maintain, modify and debug.
• OOP makes it possible to create full reusable applications with less
code and shorter development time.
Class
A class allows you to define new data types. It serves as a
blueprint, which is a model for the objects you create
based on this new data type.

The template student is an example of a class. We can


define every student to have a set of qualities such as
name, student number and school level. We can also
define students to have the ability to enroll and to attend
school.
A class — in the context of Java — is a template used to create objects and to
define object data types and methods.

Classes are categories, and objects are items within each category. All class
objects should have the basic class properties.

For example: In the real world, a specific cat is an object of the “cats” class. All
cats in the world share some characteristics from the same template such as
being a feline, having a tail, or being the coolest of all animals.

In Java, the “Cat” class is the blueprint from which all individual cats can be
generated that includes all cat characteristics, such as race, fur color, tail length,
eyes shape, etc.

So, for example, you cannot create a house from the cat class, because a house
must have certain characteristics — such as having a door, windows and a roof —
and none of these object properties can be found in the cat class.
Object
An object is an entity that has a state, behavior and identity with a
well-defined role in problem space. It is an actual instance of a
class. Thus, it is also known as an instance. It is created every time
you instantiate a class using the new keyword.

In a student registration system, an example of an object would be


a student entity, say Anna. Anna is an object of the class student.
Thus, the qualities and abilities defined in the student template are
all applicable to Anna.
A Java object is a member (also called an instance) of a Java class. Each
object has an identity, a behavior and a state.

The state of an object is stored in fields (variables), while methods (functions)


display the object's behavior. Objects are created at runtime from
templates, which are also known as classes.

In Java, an object is created using the keyword "new".

Java objects are very similar to the objects we can observe in the real world.
A cat, a lighter, a pen, or a car are all objects.

They are characterized by three features:


• Identity
• State
• Behavior

For example, a cat’s state includes its color, size, gender, and age, while its
behavior is sleeping, purring, meowing for food, or running around like crazy
at 4 AM.
IDENTITY
The identity is a characteristic used to uniquely identify that object – such as
a random ID number or an address in memory. Simpler objects like a lighter
may have only two states (on and off) and behaviors (turn on, turn off), but
they still have an identity (that item’s manufacturing ID, for example).

STATE
A Java object’s states are stored in fields that represent the individual
characteristics of that object. For example, in a first-person shooter video
game, a pistol with an eight-bullets clip has nine states in total: one for each
bullet (e.g. 8 bullets, 7 bullets, 5 bullets, etc.), plus another one when it’s
empty (0 bullets).

BEHAVIOR
The object’s behavior is exposed through methods that operate its internal
state. For example, the “shooting” behavior will change the state of the
pistol from “8 bullets'' to “7 bullets” and so forth every time the player shoots
with the gun.
Example:
public class Main { Output:
int x = 5;
5
public static void main(String[] args) { 5
Main myObj1 = new Main();
Main myObj2 = new Main();
System.out.println(myObj1.x);
System.out.println(myObj2.x);
}
}
Attribute
An attribute refers to the data element of an object. It
stores information about the object. It is also known as a
data member, an instance variable, a property or a
data field. Going back to the student registration system
example, some attributes of a student entity include
name, student number and school level.

Variables that belong to an object are usually called attributes, but you might
also see them called “fields”.
Example:
public class Main { public class Main {
int x = 5; String Fname = “Kai”;
int y = 3; String Lname = “Jin;
} int age = “27”;
}
Method
A method describes the behavior of an object. It is also
called a function or a procedure. For example, possible
methods available for a student entity are enroll and
attend school.
A method is a block of code that performs a specific task.

Suppose you need to create a program to create a circle and


color it. You can create two methods to solve this problem:

• A method to draw the circle


• A method to color the circle
• Dividing a complex problem into smaller chunks makes your
program easy to understand and reusable.

In Java, there are two types of methods:

• User-defined Methods: We can create our own method based


on our requirements.
• Standard Library Methods: These are built-in methods in Java
that are available to use.
Example:
Create the methods

public class Main {

public void fullThrottle() {


System.out.println("The car is going as fast as it can!");
}
public void speed(int maxSpeed) {
System.out.println("Max speed is: " + maxSpeed);
}
public static void main(String[] args) {
Main myCar = new Main(); Create a myCar object.
myCar.fullThrottle(); Call a fullThrottle() method.
myCar.speed(200); Call a speed() method.
}
}
Constructor
A constructor is a special type of method used for
creating and initializing a new object. Remember that
constructors are not members (i.e., attributes, methods
or inner classes of an object).
A constructor in Java is similar to a method that is
invoked when an object of the class is created.

Unlike Java methods, a constructor has the same name


as that of the class and does not have any return type.

Importance of return type in Java?


A return statement causes the program control to
transfer back to the caller of a method. Every method in
Java is declared with a return type and it is mandatory
for all java methods. A return type may be a primitive
type like int, float, double, a reference type or void
type(returns nothing).
Example:
Creates the Main class.

public class Main {


int x; Create a class attribute.

public Main() {
x = 5; Create a class constructor for the Main class.
} Set the initial value for the class attribute x.

public static void main(String[] args) {


Main myObj = new Main(); Create an object of class
Main (calls the constructor).
System.out.println(myObj.x);
} Prints the value of x.
}
Package
A package refers to a grouping of classes and/or
subpackages. Its structure is analogous to that of a
directory.
JAVA PACKAGES & API

A package in Java is used to group related classes. Think


of it as a folder in a file directory. We use packages to
avoid name conflicts, and to write a better maintainable
code. Packages are divided into two categories:

• Built-in Packages (packages from the Java API)


• User-defined Packages (create your own packages)
Syntax:
import package.name.Class; // Import a single class
Import package.name.*; // Import the whole package

Example:
import java.util.Scanner;
Encapsulation
Encapsulation refers to the principle of hiding design or
implementation information that are not relevant to the
current object.
Encapsulation in Java is a powerful mechanism for storing the data members
and data methods of a class together. It is done in the form of a secure field
accessible by only the members of the same class.

Encapsulation in Java is the process by which data (variables) and the code
that acts upon them (methods) are integrated as a single unit. By
encapsulating a class's variables, other classes cannot access them, and only
the methods of the class can access them.

Encapsulation in Java refers to integrating data (variables) and code


(methods) into a single unit. In encapsulation, a class's variables are hidden
from other classes and can only be accessed by the methods of the class in
which they are found.

Encapsulation in Java is an object-oriented procedure of combining the data


members and data methods of the class inside the user-defined class. It is
important to declare this class as private.
Abstraction
While encapsulation is hiding the details away,
abstraction refers to ignoring aspects of a subject
that are not relevant to the current purpose in order
to concentrate more fully on those that are.
Data Abstraction is the property by virtue of which only the essential
details are displayed to the user. The trivial or the non-essential units are
not displayed to the user. Ex: A car is viewed as a car rather than its
individual components.

Data Abstraction may also be defined as the process of identifying only


the required characteristics of an object ignoring the irrelevant details. The
properties and behaviors of an object differentiate it from other objects of
similar type and also help in classifying/grouping the objects.

Consider a real-life example of a man driving a car. The man only knows
that pressing the accelerators will increase the speed of a car or applying
brakes will stop the car, but he does not know how on pressing the
accelerator the speed is actually increasing, he does not know about the
inner mechanism of the car or the implementation of the accelerator,
brakes, etc in the car. This is what abstraction is.
Abstract class in Java
A class which is declared as abstract is known as an abstract class. It can
have abstract and non-abstract methods. It needs to be extended and its
method implemented. It cannot be instantiated.

Points to Remember
An abstract class must be declared with an abstract keyword.
It can have abstract and non-abstract methods.
It cannot be instantiated.
It can have constructors and static methods also.
It can have final methods which will force the subclass not to change the
body of the method.
Abstract classes and Abstract methods :

• An abstract class is a class that is declared with an abstract keyword.


• An abstract method is a method that is declared without
implementation.
• An abstract class may or may not have all abstract methods. Some of
them can be concrete methods
• A method-defined abstract must always be redefined in the subclass,
thus making overriding compulsory or making the subclass itself abstract.
• Any class that contains one or more abstract methods must also be
declared with an abstract keyword.
• There can be no object of an abstract class. That is, an abstract class
can not be directly instantiated with the new operator.
• An abstract class can have parameterized constructors and the default
constructor is always present in an abstract class.
Inheritance
Inheritance is a relationship between classes wherein
one class is the superclass or the parent class of
another. It refers to the properties and behaviors
received from an ancestor. It is also know as a "is-a"
relationship. Consider the following hierarchy.

Superhero

FlyingSuperhero UnderwaterSuperhero
Polymorphism
Polymorphism is the ability of an object to assume
may different forms. Literally, "poly" means many
while "morph" means form.

Referring to the previous example for inheritance, we


see that a SuperHero object can also be a
FlyingSuperHero object or an UnderwaterSuperHero
object.
Polymorphism is an important concept of object-oriented programming. It
simply means more than one form.
That is, the same entity (method or operator or object) can perform
different operations in different scenarios.

Why Polymorphism?
Polymorphism allows us to create consistent code.

We can achieve polymorphism in Java using the following ways:


• Method Overriding
• Method Overloading
• Operator Overloading
Interface
An interface is a contract in the form of a collection
of method and constant declarations. When a class
implements an interface, it promises to implement all
of the methods declared in that interface.
An Interface in Java programming language is defined as an abstract type
used to specify the behavior of a class. An interface in Java is a blueprint of a
behaviour. A Java interface contains static constants and abstract methods.

The interface in Java is a mechanism to achieve abstraction. There can be


only abstract methods in the Java interface, not the method body. It is used
to achieve abstraction and multiple inheritance in Java. In other words, you
can say that interfaces can have abstract methods and variables. It cannot
have a method body. Java Interface also represents the IS-A relationship.

When we decide a type of entity by its behaviour and not via attribute we
should define it as an interface.
Like a class, an interface can have methods and variables, but the methods
declared in an interface are by default abstract (only method signature, no
body).

• Interfaces specify what a class must do and not how. It is the blueprint of
the behaviour.
• Interface do not have constructor.
• Represent behaviour as interface unless every sub-type of the class is
guarantee to have that behaviour.
• An Interface is about capabilities like a Player may be an interface and
any class implementing Player must be able to (or must implement)
move(). So it specifies a set of methods that the class has to implement.
• If a class implements an interface and does not provide method bodies for
all functions specified in the interface, then the class must be declared
abstract.
• A Java library example is Comparator Interface. If a class implements this
interface, then it can be used to sort a collection.
interface {

// declare constant fields


// declare methods that abstract
// by default.
}

To declare an interface, use the interface keyword. It is used to provide total


abstraction. That means all the methods in an interface are declared with an
empty body and are public and all fields are public, static, and final by
default. A class that implements an interface must implement all the methods
declared in the interface. To implement interface use implements keyword.

You might also like