8392 OBJECT - nprcet.org

128
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING CS8392 OBJECT ORIENTED PROGRAMMING

Transcript of 8392 OBJECT - nprcet.org

Page 1: 8392 OBJECT - nprcet.org

DEPARTMENT OF COMPUTER SCIENCE AND

ENGINEERING

CS8392 OBJECT ORIENTED PROGRAMMING

Page 2: 8392 OBJECT - nprcet.org

Object-oriented programming (OOP) is an

engineering approach for building software

systems

• Based on the concepts of classes and objects that

are used for modeling the real world entities

Object-oriented programs

• Consist of a group of cooperating objects

• Objects exchange messages, for the purpose of

achieving a common ob4jective

• Implemented in object-oriented languages

Page 3: 8392 OBJECT - nprcet.org

CLASSES AND OBJECTS

• A class is a prototype, idea, and blueprint for

creating objects.

• An object is an instance of a class.

• For example, in Java we define classes,

which in turn are used to create objects

• A class has a constructor for creating objects

• Class is composed of three things: its name,

attributes/properties, and methods.

Page 4: 8392 OBJECT - nprcet.org

CLASS

Objects:

Instances of the class

Class

Instance Properties:

Belong to the object

Class Properties:

Belong to the class

Methods:

Functions of class

Page 5: 8392 OBJECT - nprcet.org

CLASSES EXAMPLE

EX

Page 6: 8392 OBJECT - nprcet.org

hour

minute

void addMinutes( int m )

Time inTime Attributes:

hour = 8 minute = 30

Methods: void addMinutes(int m)

outTime Attributes:

hour = 17 minute = 35

Methods: void addMinutes(int m)

CLASSES & OBJECTS

CLASS

6

objects

Page 7: 8392 OBJECT - nprcet.org

CLASSES – EXAMPLE CLASS

Account

+Owner: Person +Ammountt: double

+suspend() +deposit(sum:double) +withdrraw(sum:double)

Class Attttributes

Operattiions

Page 8: 8392 OBJECT - nprcet.org

CLASSES AND OBJECTS – EXAMPLE

CLASS AND OBJECTS

Account

+Owner: Person +Ammount: double

+suspend(() +deposit(sum:double) +withdraw(sum:double)

Cllass ivanAccount

+Owner="Ivan Kollev" +Ammount=5000.0

peterAccount

+Owner="Peter Kirov" +Ammountt=1825.33

kirilAccount

+Owner="Kiril Kirov"

+Ammount=1245.0

Objject

Objject

Page 9: 8392 OBJECT - nprcet.org

9

CLASS OBJECT

Class is a data type Object is an instance of Class.

It generates OBJECTS It gives life to CLASS

Does not occupy memory

location

It occupies memory location.

It cannot be manipulated

because it is not available in

memory (except static class)

It can be manipulated.

Object is a class in “runtime”

Page 10: 8392 OBJECT - nprcet.org

OOPS CONCEPTS

• INHERITANCE

• ABSTRACTION

• ENCAPSULATION

• POLYMORPHISM

Page 11: 8392 OBJECT - nprcet.org

OBJECT ORIENTED CONCEPTS

Class – A class defines the blue print i.e. structure and functions of an object.

Objects – Objects help us to decompose large systems and help us to modularize our system. Modularity helps to divide our system into understandable components so that we can build our system piece by piece. An object is the fundamental unit (building block) of a system which is used to depict an entity.

Inheritance – Inheritance is a mechanism by which child classes inherit the properties of their parent classes.

Abstraction – Mechanism by which implementation details are hidden from user.

Encapsulation – Binding data together and protecting it from the outer world is referred to as encapsulation.

Polymorphism – Mechanism by which functions or entities are able to exist in different forms.

Page 12: 8392 OBJECT - nprcet.org

CLASS

A class is a user defined blueprint or prototype from which objects are created. It represents the set of properties or methods that are common to all objects of one type. In general, class declarations can include these components, in order:

Modifiers: A class can be public or has default access (Refer this for details).

Class name: The name should begin with a initial letter (capitalized by convention).

Superclass(if any): The name of the class’s parent (superclass), if any, preceded by the keyword extends. A class can only extend (subclass) one parent.

Interfaces(if any): A comma-separated list of interfaces implemented by the class, if any, preceded by the keyword implements. A class can implement more than one interface.

Body: The class body surrounded by braces, { }

Page 13: 8392 OBJECT - nprcet.org

OBJECT

It is a basic unit of Object Oriented Programming and

represents the real life entities. A typical Java program

creates many objects, which as you know, interact by

invoking methods. An object consists of:State : It is

represented by attributes of an object. It also reflects the

properties of an object.

Behavior : It is represented by methods of an object. It

also reflects the response of an object with other objects.

Identity : It gives a unique name to an object and

enables one object to interact with other objects.

Example of an object: dog

Page 14: 8392 OBJECT - nprcet.org
Page 15: 8392 OBJECT - nprcet.org

INHERITANCE

Inheritance is an important pillar of

OOP(Object Oriented Programming). It is the

mechanism in java by which one class is allow to

inherit the features(fields and methods) of another

class

Syntax:

class derived-class extends base-class

{

//methods and fields

}

Page 16: 8392 OBJECT - nprcet.org

INHERITANCE

Inheritance Person

+Name: Sttrriing +Address: String

Employee

+Company: String +Sallarry: double

Student

+Schooll:: String

Subclass Subclass

Page 17: 8392 OBJECT - nprcet.org

class Super

{ ..... ..... }

class Sub extends Super

{ ..... ..... }

TYPES

Single Inheritance

Multiple inheritance

Hierarchical inheritance

Multilevel inheritance

Page 18: 8392 OBJECT - nprcet.org
Page 19: 8392 OBJECT - nprcet.org

IMPORTANT TERMINOLOGY:

Super Class: The class whose features are inherited is known as superclass(or a base class or a parent class).

Sub Class: The class that inherits the other class is known as subclass(or a derived class, extended class, or child class). The subclass can add its own fields and methods in addition to the superclass fields and methods.

Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a new class and there is already a class that includes some of the code that we want, we can derive our new class from the existing class. By doing this, we are reusing the fields and methods of the existing class.

The keyword used for inheritance is extends.

Page 20: 8392 OBJECT - nprcet.org

ENCAPSULATION

Encapsulation is defined as the wrapping up of data under a single unit. It is the mechanism that binds together code and the data it manipulates.

Another way to think about encapsulation is, it is a protective shield that prevents the data from being accessed by the code outside this shield.

Technically in encapsulation, the variables or data of a class is hidden from any other class and can be accessed only through any member function of own class in which they are declared.

As in encapsulation, the data in a class is hidden from other classes, so it is also known as data-hiding.

Encapsulation can be achieved by Declaring all the variables in the class as private and writing public methods in the class to set and get the values of variables.

Page 21: 8392 OBJECT - nprcet.org

ENCAPSULATIO

N

21

Page 22: 8392 OBJECT - nprcet.org

ENCAPSULATION – EXAMPLE

• Data Fields are private

• Constructors and accessor methods are

defined

Page 23: 8392 OBJECT - nprcet.org

ABSTRACTION

Data Abstraction is the property by virtue of which only the essential details are displayed to the user.The trivial or the non-essentials 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 behaviours 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 car or applying brakes will stop the car but he does not know about 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 accelerator, brakes etc in the car. This is what abstraction is.

Page 24: 8392 OBJECT - nprcet.org

POLYMORPHISM

Polymorphism refers to the ability of

OOPs programming languages to differentiate

between entities with the same name efficiently.

This is done by Java with the help of the

signature and declaration of these entities.

Page 25: 8392 OBJECT - nprcet.org

POLYMORPHISM – EXAMPLE

37

Square::calcSurface() {

return size * size;

}

Circle::calcSurface() {

return PI * radius *

raduis;

}

Abstract class

Abstract action

Concrete class

Overriden action Overriden

action

Page 26: 8392 OBJECT - nprcet.org

METHOD

A method is a collection of statements that

perform some specific task and return result to the caller.

A method can perform some specific task without

returning anything. Methods allow us to reuse the code

without retyping the code.

Methods are time savers and help us to reuse the

code without retyping the code.Method Declaration

Page 27: 8392 OBJECT - nprcet.org

In general, method declarations has six components:

Access Modifier: Defines access type of the method i.e. from where it can be accessed in your application. In Java, there 4 type of the access specifiers.

public: accessible in all class in your application.

protected: accessible within the package in which it is defined and in its subclass(es)(including subclasses declared outside the package)

private: accessible only within the class in which it is defined.

default (declared/defined without using any modifier): accessible within same class and package within which its class is defined.

Page 28: 8392 OBJECT - nprcet.org

The return type: The data type of the value returned by the method or void if does not return a value.

Method Name: the rules for field names apply to method names as well, but the convention is a little different.

Parameter list: Comma separated list of the input parameters are defined, preceded with their data type, within the enclosed parenthesis. If there are no parameters, you must use empty parentheses ().

Exception list: The exceptions you expect by the method can throw, you can specify these exception(s).

Method body: it is enclosed between braces. The code you need to be executed to perform your intended operations.

Page 29: 8392 OBJECT - nprcet.org
Page 30: 8392 OBJECT - nprcet.org

MESSAGE PASSING

Objects communicate with one another by

sending and receiving information to each other.

A message for an object is a request for

execution of a procedure and therefore will invoke a

function in the receiving object that generates the desired

results.

Message passing involves specifying the name

of the object, the name of the function and the

information to be sent

Page 31: 8392 OBJECT - nprcet.org

MESSAGES

A request for an object to perform one of its

operations (methods)

All communication between objects is done via

messages

Page 32: 8392 OBJECT - nprcet.org

Object 3

Object 2

OBJECT INTERACTION

32

Object 1

Property

Method

Property

Method

Property

Method

Message

Page 33: 8392 OBJECT - nprcet.org

ADVANTAGES OF OOPS: OOP offers easy to understand and a clear modular structure

for programs.

Objects created for Object-Oriented Programs can be reused in

other programs. Thus it saves significant development cost.

Large programs are difficult to write, but if the development

and designing team follow OOPS concept then they can better

design with minimum flaws.

It also enhances program modularity because every object

exists independently

Page 34: 8392 OBJECT - nprcet.org

WHAT IS JAVA

•Java is a programming language and a platform. Java

is a high level, robust, object-oriented and secure

programming language.

•Java was developed by Sun Microsystems (which is

now the subsidiary of Oracle) in the year 1995. James

Gosling is known as the father of Java. Before Java, its

name was Oak. Since Oak was already a registered

company, so James Gosling and his team changed the

Oak name to Java.

•Platform: Any hardware or software environment in

which a program runs, is known as a platform. Since

Java has a runtime environment (JRE) and API, it is

called a platform

Page 35: 8392 OBJECT - nprcet.org

JAVA EXAMPLE

Let's have a quick look at Java programming example. A

detailed description of Hello Java example .

class Simple{

public static void main(String args[]){

System.out.println("Hello Java");

}

}

Output-Hello Java

Page 36: 8392 OBJECT - nprcet.org

APPLICATIONS

According to Sun, 3 billion devices run Java. There are many devices where Java is currently used. Some of them are as follows:

Desktop Applications such as acrobat reader, media player, antivirus, etc.

Web Applications such as irctc.co.in, javatpoint.com, etc.

Enterprise Applications such as banking applications.

Mobile

Embedded System

Smart Card

Robotics

Games, etc.

Page 37: 8392 OBJECT - nprcet.org

Types of Java Applications

1) Standalone Application

2) Web Application

3) Enterprise Application

4) Mobile Application

Page 38: 8392 OBJECT - nprcet.org

JAVA PLATFORMS / EDITIONS

There are 4 platforms or editions of Java:

1) Java SE (Java Standard Edition)

It is a Java programming platform. It includes Java programming APIs such as java.lang, java.io, java.net, java.util, java.sql, java.math etc. It includes core topics like OOPs, String, Regex, Exception, Inner classes, Multithreading, I/O Stream, Networking, AWT, Swing, Reflection, Collection, etc.

2) Java EE (Java Enterprise Edition)

It is an enterprise platform which is mainly used to develop web and enterprise applications. It is built on the top of the Java SE platform. It includes topics like Servlet, JSP, Web Services, EJB, JPA, etc.

3) Java ME (Java Micro Edition)

It is a micro platform which is mainly used to develop mobile applications.

4) JavaFX

It is used to develop rich internet applications. It uses a light-weight user interface API

Page 39: 8392 OBJECT - nprcet.org

FEATURES OF JAVA

The primary objective of Java programming language

creation was to make it portable, simple and secure

programming language. Apart from this, there are also

some excellent features which play an important role in

the popularity of this language. The features of Java are

also known as java buzzwords

Page 40: 8392 OBJECT - nprcet.org

A list of most important features of Java language is given below.

Simple

Object-Oriented

Portable

Platform independent

Secured

Robust

Architecture neutral

Interpreted

High Performance

Multithreaded

Distributed

Dynamic

Page 41: 8392 OBJECT - nprcet.org
Page 42: 8392 OBJECT - nprcet.org

The Java platform differs from most other

platforms in the sense that it is a software-based

platform that runs on the top of other hardware-

based platforms. It has two components:

Runtime Environment

API(Application Programming Interface)

Page 43: 8392 OBJECT - nprcet.org
Page 44: 8392 OBJECT - nprcet.org

class Simple{

public static void main(String args[]){

System.out.println("Hello Java");

}

}

To compile:javac Simple.java

To execute:java Simple

Output:Hello Java

Page 45: 8392 OBJECT - nprcet.org
Page 46: 8392 OBJECT - nprcet.org

PARAMETERS USED IN FIRST JAVA PROGRAM

Let's see what is the meaning of class, public, static, void, main, String[], System.out.println().

class keyword is used to declare a class in java.

public keyword is an access modifier which represents visibility. It means it is visible to all.

static is a keyword. If we declare any method as static, it is known as the static method. The core advantage of the static method is that there is no need to create an object to invoke the static method. The main method is executed by the JVM, so it doesn't require to create an object to invoke the main method. So it saves memory.

void is the return type of the method. It means it doesn't return any value.

main represents the starting point of the program.

String[] args is used for command line argument. We will learn it later.

System.out.println() is used to print statement. Here, System is a class, out is the object of PrintStream class, println() is the method of PrintStream class. We will learn about the internal working of System.out.println statement later.

Page 47: 8392 OBJECT - nprcet.org

By changing the sequence of the modifiers, method

prototype is not changed in Java.

static public void main(String args[])

The subscript notation in Java array can be used after type,

before the variable or after the variable.

public static void main(String[] args)

public static void main(String []args)

public static void main(String args[])

Page 48: 8392 OBJECT - nprcet.org

VALID JAVA MAIN METHOD SIGNATURE

public static void main(String[] args)

public static void main(String []args)

public static void main(String args[])

public static void main(String... args)

static public void main(String[] args)

public static final void main(String[] args)

final public static void main(String[] args)

final strictfp public static void main(String[] ar

gs)

Page 49: 8392 OBJECT - nprcet.org

INVALID JAVA MAIN METHOD SIGNATURE

public void main(String[] args)

static void main(String[] args)

public void static main(String[] args)

abstract public static void main(String[] args)

Page 50: 8392 OBJECT - nprcet.org

How to set the Temporary Path of JDK in Windows

To set the temporary path of JDK, you need to

follow the following steps:

Open the command prompt

Copy the path of the JDK/bin directory

Write in command prompt: set path=copied_path

For Example:

set path=C:\Program

Files\Java\jdk1.6.0_23\bin

Page 51: 8392 OBJECT - nprcet.org

JRE

JRE is an acronym for JAVA RUNTIME

ENVIRONMENT. It is also written as Java

RTE. The Java Runtime Environment is a set of

software tools which are used for developing Java

applications. It is used to provide the runtime

environment. It is the implementation of JVM. It

physically exists. It contains a set of libraries +

other files that JVM uses at runtime.

Page 52: 8392 OBJECT - nprcet.org

JRE

Page 53: 8392 OBJECT - nprcet.org

JDK

JDK is an acronym for Java Development Kit. The Java Development Kit (JDK) is a software development environment which is used to develop Java applications and applets. It physically exists. It contains JRE + development tools.

JDK is an implementation of any one of the below given Java Platforms released by Oracle Corporation:

Standard Edition Java Platform

Enterprise Edition Java Platform

Micro Edition Java Platform

The JDK contains a private Java Virtual Machine (JVM) and a few other resources such as an interpreter/loader (java), a compiler (javac), an archiver (jar), a documentation generator (Javadoc), etc. to complete the development of a Java Application

Page 54: 8392 OBJECT - nprcet.org

JDK

Page 55: 8392 OBJECT - nprcet.org

JVM

JVM (Java Virtual Machine) is an abstract machine. It is called a virtual machine because it doesn't physically exist. It is a specification that provides a runtime environment in which Java bytecode can be executed. It can also run those programs which are written in other languages and compiled to Java bytecode.

The JVM performs the following main tasks:

Loads code

Verifies code

Executes code

Provides runtime environment

Page 56: 8392 OBJECT - nprcet.org

JVM (JAVA VIRTUAL MACHINE) ARCHITECTURE

JVM (Java Virtual Machine) is an abstract

machine. It is a specification that provides

runtime

environment in which java bytecode can be

executed.

JVMs are available for many hardware and

software platforms (i.e. JVM is platform

dependent)

Page 57: 8392 OBJECT - nprcet.org

WHAT IT DOES

The JVM performs following operation:

Loads code

Verifies code

Executes code

Provides runtime environment

JVM provides definitions for the:

Memory area

Class file format

Register set

Garbage-collected heap

Fatal error reporting etc

Page 58: 8392 OBJECT - nprcet.org

Memory areas

allocated by

JVM

Java

native

libraries

Page 59: 8392 OBJECT - nprcet.org

CLASSLOADER

1)Classloader

is a subsystem of JVM which is used to load class files.

Whenever we run the java program, it is loaded first by the classloader.

There are three built-in classloaders in Java.

Bootstrap ClassLoader: This is the first classloader which is the super

class of Extension classloader. It loads the rt.jar file which contains all class

files of Java Standard Edition like java.lang package classes, java.net

package classes, java.util package classes, java.io package classes, java.sql

package classes etc.

Extension ClassLoader: This is the child classloader of Bootstrap and

parent classloader of System classloader. It loades the jar files located

inside $JAVA_HOME/jre/lib/ext directory.

System/Application ClassLoader: This is the child classloader of

Extension classloader. It loads the classfiles from classpath. By default,

classpath is set to current directory. You can change the classpath using "-

cp" or "-classpath" switch. It is also known as Application classloader.

Page 60: 8392 OBJECT - nprcet.org

JVM ARCHITECTURE

2) Class(Method) Area

Class(Method) Area stores per-class structures such as the runtime constant pool, field and method data, the code for methods.

3) Heap

It is the runtime data area in which objects are allocated.

4) Stack

Java Stack stores frames. It holds local variables and partial results, and plays a part in method invocation and return.

Each thread has a private JVM stack, created at the same time as thread.

A new frame is created each time a method is invoked. A frame is destroyed when its method invocation completes.

5) Program Counter Register

PC (program counter) register contains the address of the Java virtual machine instruction currently being executed.

Page 61: 8392 OBJECT - nprcet.org

6) Native Method Stack

It contains all the native methods used in the application.

7) Execution Engine

It contains:

A virtual processor

Interpreter: Read bytecode stream then execute the instructions.

Just-In-Time(JIT) compiler: It is used to improve the performance. JIT compiles parts of the byte code that have similar functionality at the same time, and hence reduces the amount of time needed for compilation. Here, the term "compiler" refers to a translator from the instruction set of a Java virtual machine (JVM) to the instruction set of a specific CPU.

8) Java Native Interface

Java Native Interface (JNI) is a framework which provides an interface to communicate with another application written in another language like C, C++, Assembly etc. Java uses JNI framework to send output to the Console or interact with OS libraries.

Page 62: 8392 OBJECT - nprcet.org
Page 63: 8392 OBJECT - nprcet.org

DEFINING CLASSES IN JAVA

The class is at the core of Java .A class is a template for an object, and an object is an instance of a class. A class is declared by use of the class keyword

Syntax:

class classname {

type instance-variable1;

type instance-variable2;

// ...

type instance-variableN;type

methodname1(parameter-list) {

// body of method}...

type methodnameN(parameter-list) {

// body of method

}

Page 64: 8392 OBJECT - nprcet.org

The data, or variables, defined within a class are

called instance variables. The code is contained within

methods.

The methods and variables defined within a class

are called members of the class. In most classes, the

instance variables are acted upon and accessed by the

methods defined for that class.

Variables defined within a class are called

instance variables because each instance of the class

(that is, each object of the class) contains its own copy

of these variables. Thus, the data for one object is

separate and unique from the data for another

Page 65: 8392 OBJECT - nprcet.org

A Simple Class

class called Box that defines three instance variables:

width, height, and depth.

class Box

{

double width ;double height; double depth;

}

The new data type is called Box. This name is used to

declare objects of type Box.

The class declaration only creates a template. It does not

create an actual object

Page 66: 8392 OBJECT - nprcet.org
Page 67: 8392 OBJECT - nprcet.org

DECLARING OBJECTS

First, declare a variable of the class type. This variable does not define an object.

Second, you must acquire an actual,physical copy of the object and assign it to that variable.

This is done using the newoperator. The new operator dynamically a

llocates (that is, allocates at run time) memory for an object and returns a reference to it.

This reference is then stored in the variable. Thus,in Java, all class objects must be dynamically allocated

Page 68: 8392 OBJECT - nprcet.org

SYNTAX

Box mybox = new Box();

Box mybox; // declare reference to object

mybox = new Box(); // allocate a Box objec

Page 69: 8392 OBJECT - nprcet.org

The first line declares mybox as a reference to an object of type

Box.

At this point, myboxdoes not yet refer to an actual object. The

next line allocates an object and assigns areference to it to

mybox.

After the second line executes, wecan use mybox as if it were

aBox object.

But in reality, mybox simply holds, in essence, the memory

address of the actualBox object

Page 70: 8392 OBJECT - nprcet.org
Page 71: 8392 OBJECT - nprcet.org

ASSIGNING OBJECT REFERENCE

VARIABLES

Syntax:

Box b1 = new Box();

Box b2 = b1;

Page 72: 8392 OBJECT - nprcet.org
Page 73: 8392 OBJECT - nprcet.org

CONSTRUCTORS Constructors are special member functions whose task is to

initialize the objects of its class.

It is a special member function, it has the same as the class

name.

Java constructors are invoked when their objects are created. It

is named such because, it constructs the value, that isprovides

data for the object and are used to initialize objects.

Every class has a constructor when we don't explicitly declare a

constructor for any java class the compiler creates a default

constructor for that class which does not have any return type.

The constructor in Java cannot be abstract, static, final or

synchronized and these modifiers are not allowed for the

constructor.

Page 74: 8392 OBJECT - nprcet.org

There are two types of constructors:

1.Default constructor (no-arg constructor)

2.Parameterized constructor

Page 75: 8392 OBJECT - nprcet.org

METHODS

Page 76: 8392 OBJECT - nprcet.org

METHOD IN JAVA

In general, a method is a way to perform some task. Similarly, the method in Java is a collection of instructions that performs a specific task.

It provides the reusability of code. We can also easily modify code using methods.

In this section, we will learn what is a method in Java, types of methods, method declaration, and how to call a method in Java.

Page 77: 8392 OBJECT - nprcet.org

METHOD

A method is a block of code or collection of

statements or a set of code grouped together to

perform a certain task or operation. It is used to

achieve the reusability of code

Page 78: 8392 OBJECT - nprcet.org
Page 79: 8392 OBJECT - nprcet.org

Method Signature: Every method has a method signature. It is a part of the method declaration. It includes the method name and parameter list.

Access Specifier: Access specifier or modifier is the access type of the method. It specifies the visibility of the method. Java provides four types of access specifier:

Public: The method is accessible by all classes when we use public specifier in our application.

Private: When we use a private access specifier, the method is accessible only in the classes in which it is defined.

Protected: When we use protected access specifier, the method is accessible within the same package or subclasses in a different package.

Default: When we do not use any access specifier in the method declaration, Java uses default access specifier by default. It is visible only from the same package only.

modifier − It defines the access type of the method and it is optional to use.

Page 80: 8392 OBJECT - nprcet.org

Return Type: Return type is a data type that the method returns. It may have a primitive data type, object, collection, void, etc. If the method does not return anything, we use void keyword.

Method Name: It is a unique name that is used to define the name of a method. It must be corresponding to the functionality of the method. Suppose, if we are creating a method for subtraction of two numbers, the method name must be subtraction(). A method is invoked by its name.

Parameter List: It is the list of parameters separated by a comma and enclosed in the pair of parentheses. It contains the data type and variable name. If the method has no parameter, left the parentheses blank.

Method Body: It is a part of the method declaration. It contains all the actions to be performed. It is enclosed within the pair of curly braces.

Page 81: 8392 OBJECT - nprcet.org

NAMING A METHOD

While defining a method, remember that the method name must be a verb and start with a lowercase letter. If the method name has more than two words, the first name must be a verb followed by adjective or noun. In the multi-word method name, the first letter of each word must be in uppercase except the first word. For example:

Single-word method name: sum(), area()

Multi-word method name: areaOfCircle(), stringComparision()

It is also possible that a method has the same name as another method name in the same class, it is known as method overloading.

Page 82: 8392 OBJECT - nprcet.org

TYPES OF METHOD

There are two types of methods in Java:

Predefined Method

User-defined Method

Predefined Method In Java, predefined methods are the method that is already defined in

the Java class libraries is known as predefined methods. It is also known as the standard library method or built-in method.

We can directly use these methods just by calling them in the program at any point. Some pre-defined methods are length(), equals(), compareTo(), sqrt(), etc.

User-defined Method The method written by the user or programmer is known as a user-

defined method. These methods are modified according to the requirement.

Page 83: 8392 OBJECT - nprcet.org
Page 84: 8392 OBJECT - nprcet.org
Page 85: 8392 OBJECT - nprcet.org

STATIC METHOD

A method that has static keyword is known as static

method. In other words, a method that belongs to a

class rather than an instance of a class is known as a

static method. We can also create a static method by

using the keyword static before the method name.

The main advantage of a static method is that we can

call it without creating an object. It can access static

data members and also change the value of it. It is

used to create an instance method. It is invoked by

using the class name. The best example of a static

method is the main() method.

Page 86: 8392 OBJECT - nprcet.org

INSTANCE METHOD

The method of the class is known as an instance

method. It is a non-static method defined in the class.

Before calling or invoking the instance method, it is

necessary to create an object of its class. Let's see an

example of an instance method.

There are two types of instance method:

Accessor Method

Mutator Method

Page 87: 8392 OBJECT - nprcet.org

ABSTRACT METHOD

The method that does not has method body is

known as abstract method. In other words,

without an implementation is known as

abstract method. It always declares in

the abstract class. It means the class itself

must be abstract if it has abstract method. To

create an abstract method, we use the

keyword abstract.

Syntax

abstract void method_name();

Page 88: 8392 OBJECT - nprcet.org

OVERLOADING METHODS

When two or more methods within the same class that

have the same name, but their parameter declarations are

different.

The methods are said to be overloaded, and the process

is referred to as method overloading

Method overloading is one of the ways that Java

supports polymorphism.

There are two ways to overload the method in java

1. By changing number of arguments

2. By changing the data type

Page 89: 8392 OBJECT - nprcet.org

METHOD OVERRIDING

When a method in a subclass has the same name and

type signature as a method in its superclass, then the

method in the subclass is said to override the method in

the superclass.

When an overridden method is called from within its

subclass, it will always refer to the version of that

method defined by the subclass. The version of the

method defined by the superclass will be hidden.

Page 90: 8392 OBJECT - nprcet.org

ACCESS PROTECTION

The access modifiers in java specifies accessibility (scope) of a data member, method, constructor or class.

There are 4 types of java access modifiers:

1. private -The private access modifier is accessible only within class.

2. default- If you don't use any modifier, it is treated as default bydefault. The default modifier is accessible only within package.

3. protected -The protected access modifier is accessible within package and outside the package but through inheritance only.

4. public –The public access modifier is accessible everywhere. It has the widest scope among all other modifiers.

Page 91: 8392 OBJECT - nprcet.org

STATIC MEMBERS

Static is a non-access modifier in Java which is

applicable for the following:

1. blocks

2. variables

3. methods

4. nested classes

Page 92: 8392 OBJECT - nprcet.org

JAVA COMMENTS

The java comments are statements that are not executed by the compiler and interpreter. The comments can be used to provide information or explanation about the variable, method, class or any statement. It can also be used to hide program code for specific time.

There are 3 types of comments in java.

1. Single Line Comment

Syntax:

//This is single line comment

2. Multi Line Comment

Syntax:

/* This is multi line comment */

3. Documentation Comment

Syntax:

/** This is documentation comment*/

Page 93: 8392 OBJECT - nprcet.org

DATA

TYPES IN JAVA

Page 94: 8392 OBJECT - nprcet.org

DATATYPES IN JAVA

Data types specify the different sizes and

values that can be stored in the variable. There are

two types of data types in Java:

1. Primitive data types:

The primitive data types include Integer,

Character, Boolean, and Floating Point.

2. Non-primitive data types:

The non-primitive data types include Classes,

Interfaces, and Arrays.

Page 95: 8392 OBJECT - nprcet.org
Page 96: 8392 OBJECT - nprcet.org

Java defines eight primitive types of data: byte, short, int,

long, char, float, double, and boolean. These can be put in four

groups:

• Integers This group includes byte, short, int, and long, which

are for wholevalued signed numbers.

Floating-point numbers This group includes float and

double, which represent numbers with fractional precision.

• Characters This group includes char, which represents symbols

in a character set, like letters and numbers.

• Boolean This group includes boolean, which is a special type

for representing true/false values.

Page 97: 8392 OBJECT - nprcet.org

A variable is a container which holds the value and that

can be changed durig the execution of the program.

A variable is assigned with a datatype. Variable is a name

of memory location.

All the variables must be declared before they can be

used.

There are three types of variables in java:

local variable, instance variable and static variable.

Page 98: 8392 OBJECT - nprcet.org

VARIABLE

A variable is a container which holds the value

while the Java program is executed. A variable is

assigned with a data type.

1) Local Variable

A variable defined within a block or method or constructor

is called local variable.

2) Instance Variable

Instance variables are non-static variables and are

declared in a class outside any method, constructor or block.

3) Static variable

Static variables are also known as Class variables.

Page 99: 8392 OBJECT - nprcet.org
Page 100: 8392 OBJECT - nprcet.org
Page 101: 8392 OBJECT - nprcet.org
Page 102: 8392 OBJECT - nprcet.org

OPERATORS IN JAVA

Java provides a rich set of operators to manipulate

variables. We can divide all the Java operators into the

following groups

Arithmetic Operators

Increment and Decrement

Bitwise Operators

Relational Operators

Boolean Operators

Assignment Operator

Ternary Operator

Page 103: 8392 OBJECT - nprcet.org

Arithmetic Operators

Arithmetic operators are used to manipulate

mathematical expressions

Page 104: 8392 OBJECT - nprcet.org
Page 105: 8392 OBJECT - nprcet.org
Page 106: 8392 OBJECT - nprcet.org
Page 107: 8392 OBJECT - nprcet.org
Page 108: 8392 OBJECT - nprcet.org
Page 109: 8392 OBJECT - nprcet.org
Page 110: 8392 OBJECT - nprcet.org
Page 111: 8392 OBJECT - nprcet.org
Page 112: 8392 OBJECT - nprcet.org

JAVA ARRAYS

Java array is an object which contains elements

of a similar data type. Additionally, The elements

of an array are stored in a contiguous memory

location. It is a data structure where we store

similar elements. We can store only a fixed set of

elements in a Java array.

Page 113: 8392 OBJECT - nprcet.org

TYPES OF ARRAY IN JAVA

There are two types of array.

Single Dimensional Array

Multidimensional Array

Page 114: 8392 OBJECT - nprcet.org
Page 115: 8392 OBJECT - nprcet.org

Advantages

Code Optimization: It makes the code optimized,

we can retrieve or sort the data efficiently.

Random access: We can get any data located at an

index position.

Disadvantages

Size Limit: We can store only the fixed size of

elements in the array. It doesn't grow its size at

runtime. To solve this problem, collection framework

is used in Java which grows automatically.

Page 116: 8392 OBJECT - nprcet.org

CONSTRUCTOR

In Java, a constructor is a block of codes similar

to the method. It is called when an instance of

the class is created. At the time of calling

constructor, memory for the object is allocated in

the memory.

It is a special type of method which is used to

initialize the object.

Every time an object is created using the new()

keyword, at least one constructor is called

Page 117: 8392 OBJECT - nprcet.org

A Java constructor is special method that is called

when an object is instantiated. In other words, when you

use the new keyword.

The purpose of a Java constructor is to initializes the

newly created object before it is used

A Java class constructor initializes instances (objects)

of that class

Page 118: 8392 OBJECT - nprcet.org

JAVA PROGRAM TO CREATE AND CALL A

DEFAULT CONSTRUCTOR

class Bike1{

//creating a default constructor

Bike1(){System.out.println("Bike is created");}

//main method

public static void main(String args[]){

//calling a default constructor

Bike1 b=new Bike1();

}

}

Page 119: 8392 OBJECT - nprcet.org

RULES FOR CREATING JAVA

CONSTRUCTOR

Constructor name must be the same as its class

name

A Constructor must have no explicit return type

A Java constructor cannot be abstract, static,

final, and synchronized

[We can use access modifiers while declaring a

constructor. It controls the object creation. In

other words, we can have private, protected,

public or default constructor in Java]

Page 120: 8392 OBJECT - nprcet.org

TYPES OF JAVA CONSTRUCTORS

Default constructor (no-arg constructor)

Parameterized constructor

Page 121: 8392 OBJECT - nprcet.org

RULE: IF THERE IS NO CONSTRUCTOR IN A CLASS,

COMPILER AUTOMATICALLY CREATES A DEFAULT

CONSTRUCTOR.

Page 122: 8392 OBJECT - nprcet.org

DEFAULT CONSTRUCTOR

The default constructor is used to provide the

default values to the object like 0, null, etc.,

depending on the type.

A constructor is called "Default Constructor"

when it doesn't have any parameter

Page 123: 8392 OBJECT - nprcet.org

DEFAULT CONSTRUCTOR

Page 124: 8392 OBJECT - nprcet.org

JAVA DEFAULT CONSTRUCTOR

A constructor is called "Default Constructor"

when it doesn't have any parameter.

Syntax of default constructor:

<class_name>(){}

Page 125: 8392 OBJECT - nprcet.org

JAVA PARAMETERIZED CONSTRUCTOR

A constructor which has a specific number of

parameters is called a parameterized constructor.

The parameterized constructor is used to

provide different values to distinct objects.

However, you can provide the same values also.

Page 126: 8392 OBJECT - nprcet.org

JAVA PARAMETERIZED CONSTRUCTOR

Page 127: 8392 OBJECT - nprcet.org
Page 128: 8392 OBJECT - nprcet.org