0% found this document useful (0 votes)
17 views131 pages

Unit 1 Oopj

The document outlines the course PCCCE201 on Object Oriented Paradigm in Java, detailing its teaching and examination schemes, course outcomes, and key concepts such as encapsulation, inheritance, and polymorphism. It also covers the history, features, and benefits of Java, along with its application in internet programming through applets. The course aims to equip learners with the ability to apply object-oriented programming concepts effectively using Java.

Uploaded by

Aarya Patil
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views131 pages

Unit 1 Oopj

The document outlines the course PCCCE201 on Object Oriented Paradigm in Java, detailing its teaching and examination schemes, course outcomes, and key concepts such as encapsulation, inheritance, and polymorphism. It also covers the history, features, and benefits of Java, along with its application in internet programming through applets. The course aims to equip learners with the ability to apply object-oriented programming concepts effectively using Java.

Uploaded by

Aarya Patil
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 131

PCCCE201

Object Oriented Paradigm in Java


Teaching Scheme:
Lecture: 2 Hr/week
Examination Scheme:
In-Sem: 25 Marks
End-Sem: 25 Marks
Credits: 2
PCCCE201 Object Oriented Paradigm in Java
Course Outcome:
By taking this course, the learner will be able to:
1. Make use of object oriented programming concepts using Java such as Class, Object
constructor and control structures for program development.
2. Apply polymorphism and Inheritance for readability and reusability of code
3. Apply concepts of abstract class, interface and packages for program development.
4. Demonstrate Exception handling concepts using in-built classes and user defined
exceptions.
PCCCE201 Object Oriented Paradigm in Java

Unit-I : Introduction to Object Oriented Paradigm in Java

Unit-II : Polymorphism and Inheritance

Unit-III : Abstract Class and Interfaces

Unit-IV: Exception Handling in Java


PCCCE201 Object Oriented Paradigm in Java
Text Books:

1. Herbert Schilt, “JAVA Complete Reference”, Tata McGraw Hill, (9 th Edition), (2014)
2. Eckel B., "Thinking in Java", Pearson Education, (3 rd Edition)

Reference Books:

1. Kathy Sierra & Bert Bates, “Head First Java”, Oreilly publication,(2 nd Edition) (2009)
2. Barry Burd “Beginning Programming with Java for Dummies”, Oreilly publication, (5 th Edition)
(2017)
3. Paul Deital and Harvey Deital,”Java How to program”, Prentice Hall Publication,(9 th Edition)
(2011)
Unit-I : Introduction to Object Oriented Paradigm in Java

What is a programming language?


1. It is a computer language developed by a person (known as the programmer). It is a formal
language comprising of certain set of instructions providing various types of outputs.
2. It has its own grammar known as its syntax.
3. Once the language rules, syntax and structure are finalized, the programmer writes a code
which is known as the source code in the text editor.
4. This source code is compiled into a machine language, which is a low level programming
language that controls the CPU.
Unit-I : Introduction to Object Oriented Paradigm in Java

Need for a programming language?


1. Assist humans to communicate their ideas and thoughts in an efficient and
effective manner
2. Help humans express their opinions and plans with precision and in a
concise manner
3. It lacks ambiguity and vagueness
4. Single repeatable outcome
Unit-I : Introduction to Object Oriented Paradigm in Java
Programming paradigms are a way to classify programming languages based on their features.
Common programming paradigms are,
1. Imperative in which the programmer instructs the machine how to change its state. It can be
further divided into,
a. procedural which groups instructions into procedures
b. object-oriented which groups instructions with the part of the state they operate on
2. Declarative in which the programmer declares properties of the desired result, but not how to
compute it. It can be further classified into,
a. functional in which the desired result is declared as the value of a series of function
applications,
b. logic in which the desired result is declared as the answer to a question about a system
of facts and rules
c. mathematical in which the desired result is declared as the solution of an optimization
problem
d. reactive in which the desired result is declared with data streams and the propagation of
change
Procedural Programming Vs Object Oriented Programming

Procedural Programming Object Oriented Programming


Large programs are divided into smaller programs Programs are divided into objects
known as functions
Data is not hidden and can be accessed by external Data is hidden and cannot be accessed by
functions external functions
Follow top down approach in the program design Follows bottom-up approach in the program
design
Data may communicate with each other through Objects may communicate with each other
functions through methods
Emphasize is on procedure rather than data Emphasize is on data rather than procedure
What is Object Oriented Programming (OOP)?

Object-oriented programming (OOP) is a programming paradigm based on the concept of "objects",


which may contain data, in the form of fields, often known as attributes; and code, in the form of
procedures, often known as methods. For example, a person is an object which has certain properties such
as height, gender, age, etc. It also has certain methods such as move, talk, and so on.
1. Object
2. Class
3. Encapsulation
4. Inheritance
5. Polymorphism

1. Object - This is the basic unit of object-oriented programming. That is both data and function that
operate on data are bundled as a unit called an object.

2. Class - When you define a class, you define a blueprint for an object. This doesn't actually define
any data, but it does define what the class name means, that is, what an object of the class will
consist of and what operations can be performed on such an object.
Need for Object Oriented Paradigm (OOP):

➢ it produces reusable code/objects because of encapsulation and inheritance.


3. Encapsulation is the combining of data items (or attributes or properties) with procedures
(methods) for manipulating those data items, into a single unit called an object.
An object consists of a data structure plus a set of procedures for manipulating that data
structure. The data can be manipulated only by those procedures contained within the object.
4. Inheritance is a relationship among classes/objects wherein one class/object shares the
structure and/or behaviour defined in one (single inheritance) or more (multiple inheritance)
other classes/objects.
A class is a template defining a set of objects which share a common data structure (set of
attributes or properties) and a common behaviour (set of methods).
Need for Object Oriented Paradigm (OOP):

➢ the data is protected because it can be altered only by the encapsulated methods.
➢ it is more efficient to write programs which use predefined objects.
➢ the storage structure and/or procedures within an object type could be altered if required
without affecting programs that make use of that object type.
➢ new functions can easily be added to objects by using inheritance
➢ the code produced is likely to contain fewer errors because pretested objects are being
used.
➢ less maintenance effort will be required by the developer because objects can be reused.
5. Polymorphism is the ability of an inherited class to customize an inherited method. Two
different classes may inherit a particular method from a common parent, but they may redefine
it in different ways.
OOP Concepts
Basic concept of Object Oriented Paradigm (OOP):

1. Encapsulation
Encapsulation in Java is a mechanism for wrapping the data (variables) and
code acting on the data (methods) together as a single unit. In encapsulation, the
variables of a class will be hidden from other classes and can be accessed only
through the methods of their current class. Therefore, it is also known as data
hiding. In Java, to achieve encapsulation −
a. Declare the variables of a class as private.
b. Provide public setter and getter methods to modify and view the variables
values.
Basic concept of Object Oriented Paradigm (OOP):

2. Abstraction
Abstraction is a process of hiding the implementation details from the user, only
the functionality will be provided to the user. In other words, the user will have
the information on what the object does instead of how it does it. In Java,
abstraction is achieved using Abstract classes and interfaces.
3. Inheritance
Inheritance can be defined as the process where one (parent/super) class
acquires the properties (methods and fields) of another (child/sub). With the use
of inheritance, the information is made manageable in a hierarchical order.
Basic concept of Object Oriented Paradigm (OOP):

4. Polymorphism
Polymorphism is the ability of an object to perform different actions (or, exhibit different
behaviors) based on the context.
Benefits of Object Oriented Paradigm (OOP):

➢ The programs are modularized based on the principles of classes and objects. Linking code and object allows
related objects to share common code. This reduces code duplication and code reusability.
➢ Creation and implementation of OOP code is easy and reduces software development time.
➢ The concept of data abstraction separates object specification and object implementation.
➢ Data encapsulated along with functions. Therefore external non- member function cannot access or modify
data, thus proving data security.
➢ Easier to develop complex software, because complexity can be minimized through inheritance.
➢ OOP can communicate through message passing which makes interface description with outside system very
simple
Drawbacks of Object Oriented Paradigm (OOP):

➢ Larger program size:


➢ Slower Programs:
➢ To convert a real world problem into an object oriented model is difficult.
➢ OOP’s software development, debugging and testing tools are not
standardized.
➢ Polymorphism and dynamic binding also requires processing time, due to
overload of function calls during run time.
General characteristics of Object Oriented Paradigm (OOP):

➢ Emphasis on data rather than on algorithms/procedures


➢ Data is hidden and cannot be accessed by external functions (encapsulation)
➢ Objects may communicate with each other through functions
➢ New data and functions can easily be added whenever required
➢ Follows bottom-up approach
➢ Ability to create one object from another (inheritance)
➢ Design of new classes is based on single class (polymorphism)
General characteristics of Object Oriented Paradigm (OOP):

➢ Message passing - the manner in which the objects


communicate with each other
➢ Garbage collection - automatic memory management that
destroys objects that are no longer in use
Object:

➢ Objects are basic building blocks for designing programs.


➢ An object is a collection of data members and associated
member functions.
➢ An object may represent a person, place or a table of data.
➢ Each object is identified by a unique name.
➢ Each object must be a member of a particular class.
➢ For example: Apple, orange, mango are the objects of class fruit
Class

➢ The objects can be made user defined data types with the help of a class.
➢ A class is a collection of objects that have identical properties, common
behavior and shared relationship.
➢ Once class is defined, any number of objects of that class is created.
➢ Classes are user defined data types.
➢ A class can hold both data and functions.
➢ For example: class solar system consists of members or objects - planets,
sun, moon.
Class:
What is Java?
Java is an object oriented, simple, distributed, interpreted, robust, architecture
neutral, portable, high performance, multithreaded, dynamic, powerful and
versatile programming language originally developed by Sun Microsystems and
released in 1995 for developing software running on the mobile device, desktop
computer, and server.
History
● James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and Mike
Sheridan at Sun Microsystems, Inc. initiated the Java language project in
June 1991.
● Java was originally designed used to create software to be embedded in
various consumer electronic devices, such as microwave ovens and remote
controls.
● This language was initially called “Oak,” but was renamed “Java” in 1995.
Version till date:
Java 8 is free officially supported. Major release versions of Java, along with their release
dates:
● JDK 1.0 (January 23, 1996)[38]
● JDK 1.1 (February 19, 1997)
● J2SE 1.2 (December 8, 1998)
● J2SE 1.3 (May 8, 2000)
● J2SE 1.4 (February 6, 2002)
● J2SE 5.0 (September 30, 2004)
● Java SE 6 (December 11, 2006)
● Java SE 7 (July 28, 2011)
● Java SE 8 (LTS) (March 18, 2014)
● Java SE 9 (September 2017)
● Java SE 10 (March 2018)
● Java SE 11 (LTS) (September 2018)
● Java SE 12 (March 2019)
● C -> C++ -> Java
● Java derives its syntax - > C
● Java's OO features -> C++
● C:
○ First powerful, efficient, structured language that was relatively easy to learn.
○ Programmer's language
○ Java inherited this legacy..!!
Features of java
Features of Java
● Simple
○ If you already understand the basic concepts of object-oriented
programming, learning Java will be even easier.
○ It inherits the syntax from C/C++ and many object-oriented features of C++.
● Object-Oriented
○ All programs in java are based on objects.
○ Object model in Java is simple and easy to extend.
○ Supports Encapsulation, Inheritance, Polymorphism, Dynamic Binding.
Features of Java
● Robust
○ Java is a strictly typed language, it checks your code at compile
time. However it also checks your code at run-time.
○ Two of the main reasons for program failure:
■ memory management mistakes
■ mishandled exceptional conditions
○ Java virtually eliminates these problems by managing memory
allocation and deallocation (Garbage Collection Mechanism).
○ Java helps in this area by providing object-oriented exception
handling.
Features of Java
● Multithreaded
○ Java was designed to meet the real-world requirement of
creating interactive, networked programs.
○ To accomplish this, Java supports multithreaded programming,
which allows you to write programs that do many things
simultaneously.
● Architecture-Neutral and Portable
○ Before Java, central issue was of code longevity and
portability.
○ Operating system upgrades, processor upgrades, and changes
in core system resources all combined to make a program
Features:
● Interpreted and High Performance
○ Java enables the creation of cross-platform programs by compiling into
an intermediate representation called Java bytecode.
○ This code can be executed on any system that implements the Java
Virtual Machine.
○ The Java bytecode was carefully designed so that it would be easy to
translate directly into native machine code for very high performance by
using a just-in-time compiler.
● Distributed
○ Java is designed for the distributed environment of the Internet because
it handles TCP/IP protocols.
○ Java also supports Remote Method Invocation (RMI). This feature
enables a program to invoke methods across a network.
Features:
● Dynamic
○ Java programs carry with them substantial amounts of run-time type
information that is used to verify and resolve accesses to objects at run
time.
○ This makes it possible to dynamically link code in a safe and expedient
manner.
○ This is crucial to the robustness of the Java environment, in which small
fragments of byte-code may be dynamically updated on a running system.
● Secure
○ Java does not use memory pointers explicitly
○ All programs are executed under Sand Box.
○ It uses public key encryption system to allow the java application to transmit
over the Internet.
Java and Internet
● Java Applets - An applet is a special kind of program that is transmitted over the Internet and automatically
executed by the Java-compatible web browser. Applets are usually small programs and these helped in
moving some user interactive programs from server to client, hence improving the usability of the web
application. The typical examples of applets are tax calculator or some forms with input fields having lots of
interaction between them.
● Security - Since applets are automatically downloaded and run on the client machine, there are restrictions
on what can be done in Applets. They can use only a subset of all the functions supported by Java. e.g., They
can not access local file system or they can not launch other programs on the client system. Java achieved
this protection by restricting an applet to Java execution environment and not allowing it access to other
parts of the computer.
● Portability - Since Internet is comprised of many different types of computers and operating systems, it is
important for the programs to run on all these systems. Either we have to have a separate program for every
operating system or write a portable (or platform independent) program like Java Applet which runs
everywhere. This portability is achieved by using Bytecode In Java
Java Translation
1. The Java compiler translates Java source code into a special
representation called bytecode
2. Java bytecode is not the machine language for any traditional CPU
3. Another software tool, called an interpreter, translates bytecode into
machine language and executes it
4. Therefore the Java compiler is not tied to any particular machine

Java is both Compiled and interpreted


Java Virtual Machine (JVM)
•Platform independent means program created on one
operating system can be run on any other operating
system unlike C, C++.
•Java Virtual Machine (JVM) makes Java program
platform independent.
•A Java Virtual Machine (JVM) is a software that
implements the Java run time system and executes
Java applications.
•Convert byte code into machine level representation.
JRE(JAVA Runtime Environment)

● It is the implementation of JVM.It physically exists.It


contains set of libraries (.jar files)and other files that
JVM uses at runtime.
● Jar-Java Archieve
− .jar file contains java byte code
JDK(JAVA Development Kit)

● It physically exists.It contains JRE + development tools.


How the code executes in java?
How the code executes in java?
First Program
Simple.java

class Simple{

// This is my first java program.

public static void main(String args[]){

System.out.println("Hello World!");

}
Hello (standalone)
Note that String is built in
Main is method of the class..
All the program enclosed into the class..Hello
println is a member function for the System.out class
Command Line Argument
● Java command-line argument is an argument i.e. passed at the time of running the java
program.
● The arguments passed from the console can be received in the java program and it can be
used as an input.
● So, it provides a convenient way to check the behavior of the program for the different
values. You can pass N (1,2,3 and so on) numbers of arguments from the command
prompt.
Simple example of command-line argument in java

In this example, we are receiving only one argument and printing it. To run this java program, you must pass
at least one argument from the command prompt.
class CommandLineExample{
public static void main(String args[]){
System.out.println("Your first argument is: "+args[0]);
}
}
-------------------------------------------------------------------------------------------------------------------------------------------------------
compile by > javac CommandLineExample.java
run by > java CommandLineExample sonoo
____________________________________________________________________
Output: Your first argument is: sonoo
Java Programming elements:

● Data types
● Arrays
● Control Structures
● Class
● Object
● Method
● constructor
● Encapsulation
● Abstraction and Polymorphism
Java Programming elements:

1. Data types
2. Arrays
3. Control Structures
4. Class
5. Object
6. Method
7. constructor
8. Encapsulation
9. Abstraction and
Polymorphism
Java Programming elements:

1. Data types
2. Arrays
3. Control Structures
4. Class 1 Primitive types
5. Object
6. Method
7. constructor
8. Encapsulation
9. Abstraction and
Polymorphism
Data Types
A set of values together with a set of operations.
Primitive Data Types

● Integers – byte, short, int, long


● Floating point numbers – float, double
● Characters - char
● Boolean - boolean
Primitive Data Type: Integer
Integer data Type
Primitive Data Type: Floating Point
Primitive Data Type: Floating Point

// Compute the area of a circle.

public class Area


{
public static void main(String args[])
{
double pi, r, a;
r = 10.8; // radius of circle
pi = 3.1416; // pi, approximately
a = pi * r * r; // compute area
System.out.println("Area of circle is " + a);
}
}
Primitive Types : Character

● C/C++ - char – ASCII


- 8 bit
● Java – char – Unicode
– 16 bit
● Range : 0 - 65538
Primitive Types : Boolean
● For logical values – returns true or false
b is false
b is true
// Demonstrate boolean values.
This is executed.
public class BoolTest
{ 10 > 9 is true
public static void main(String args[])
{
boolean b;
b = false;
System.out.println("b is " + b);
b = true;
System.out.println("b is " + b);
// a boolean value can control the if statement
if(b) System.out.println("This is executed.");
b = false;
Java Programming elements:

1. Data types
2. Arrays
3. Control Structures
4. Class
5. Object
6. Method
7. constructor
8. Encapsulation
9. Abstraction and
Polymorphism
Arrays
1. Java array is an object which contains elements of a similar data type.
2. The elements of an array are stored in a contiguous memory location
3. fixed set of elements in a Java array
Arrays
Advantages
1. Code Optimization: It makes the code optimized, we can retrieve or sort the data
efficiently.
2. Random access: We can get any data located at an index position.

Disadvantages
1. 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.
Arrays
Types of Array in java
1. Single Dimensional Array 2. Multidimensional Array
Operations on Array in Java

1. Array Declaration
2. Access the Elements of an Array
3. Array Length
4. Passing array to a method
5. Returning array from a method
6. Array of object
Arrays Declaration
An array declaration has two components: the type and the name.

int abc[]; // both are valid declarations


or
int[] abc;
To link abc with an actual, physical array of integers,
abc = new int[10]; // allocating memory to array or Instantiating an Array
Combining declaration and instantiation
int[] abc = new int[10]; // declaration and instantiation
or
int abc[] = new int[10];
Or
int[] abc = {1,2,3,4,5,6,7,8,9,10}; // Declaring array literal or

String languages[] = {"Prolog", "Java"}; //declaration, instantiation and initialization

To find the length of array


System.out.println(“abc.length”); // find the length of array
Accessing an element of an array
Elements

Direct indexing Using for loop


Output:

int arr[]={1,2,3,4,5}; for(int i=0;i<arr.length;i++) 1


System.out.println(arr[3]); { 2
System.out.println(arr[3]); 3
Output: 4 } 4
Array Length

In C Programming language you have used sizeof( ), but in java you have in-build function

called as length() using object property.


Passing array to a method
public class Test
{
public static void main(String args[]) // Driver method
{ Output:
int arr[] = { 3, 1, 2, 5, 4 };
sum(arr); // passing array to method m1 sum of array values : 15
}
public static void sum(int[] arr)
{
int sum = 0; // getting sum of array values
for (int i = 0; i < arr.length; i++)
{
sum = sum+arr[i];
}
System.out.println("sum of array values : " + sum);
}
}
Returning array from a method
class Test {
public static void main(String args[]) // Driver
method Output:
{
int arr[] = m1(); sum of array values : 1 2 3

for (int i = 0; i < arr.length; i++)


System.out.print(arr[i] + " ");
}

public static int[] m1()


{
int a[]={ 1, 2, 3 }; // returning array
return a;
}
}
Example of single dimensional array
// Demonstrate a one-dimensional array.
class Array {
public static void main(String args[])
{
int month_days[];
month_days = new int[12];
month_days[0] = 31;
month_days[1] = 28;
month_days[2] = 31;
month_days[3] = 30;
month_days[4] = 31;
month_days[5] = 30;
month_days[6] = 31;
month_days[7] = 31;
month_days[8] = 30;
month_days[9] = 31;
month_days[10] = 30;
month_days[11] = 31;
System.out.println("April has " + month_days[3] + " days.");
}
}
Multidimensional Array in Java

1. A multidimensional array is an array containing one or more arrays.


2. A multidimensional array is created by appending one set of square brackets ([]) per dimension.

Examples:

int[ ] [ ] intArray = new int[10][20]; //a 2D array or matrix

int[ ] [ ] [ ] intArray = new int[10][20][10]; //a 3D array

int[ ][ ] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };


Multidimensional
Arrays
Array of object
An array of objects is created like an array of
primitive-type data items in the following way.
Syntax:
ClassName obj[]=new
ClassName[array_length];

Or ClassName[] objArray;

Or ClassName objeArray[];

Example:

Employee department1[20];

Employee department2[20];

Employee department3[20];
Java Programming elements:

1. Data types 1 if
1. Data types
2. Arrays
2. Arrays 2 switch
3. Control Structures
3. Control Structures
4. Class
4. Encapsulation 3 for
5. Object
5. Abstraction and
6. Method 4 while
Polymorphism
7. constructor
6.
8.
Class
Encapsulation
5 do-while
7. object
9. Abstraction and
8. constructor
Polymorphism
Control Statements are like C

1. if (x < y) 5. while (x < y)


{ {
smaller = x; y = y - x;
} }
2. if (x < y) 6. do
{ {
smaller=x;sum += x; y = y - x;
} } while (x < y);
else
{ 7. for (int i = 0; i < max; i++)
smaller = y; sum += y; sum += i;
}

3. Nested if statement
Control Structure

1. if
2. switch
3. for
4. while
5. do-while
if condition

Syntax: Example:

if (condition) if (20 > 18)

{ {

// block of code to be executed if System.out.println("20 is greater than


the condition is true 18");

} }
if-else condition
Syntax:
Example:
if (condition)
if (20 > 18)
{
{
// block of code to be executed if the condition is
true System.out.println("20 is greater than 18");
}
}
else
Else{
{
System.out.println("20 is smaller than 18");
// block of code to be executed if the condition
is false }

}
switch statement

Syntax: Example :

switch (n + 1) {
case 0: m = n - 1; break; switch(expression) { int day = 4;
case 1: m = n + 1; break; case x: switch (day) {
case 3: m = m * n; break;
default: m = -n; break; // code block
case 1:
} break;
System.out.println("Monday");
case y:
break;
// code block
case 2:
break;
default: System.out.println("Tuesday");

// code block break;

} }
for loop

Syntax:
for (statement 1; statement 2; statement 3) Example:

{
for (int i = 0; i < 5; i++)
// code block to be executed
{
}
System.out.println(i);
Statement 1: initialization
}
Statement 2: condition

Statement 3: increment/ decrement


while loop

Syntax: Example:
int i = 0;
while (condition)
while (i < 5)
{
{
// code block to be executed System.out.println(i);
} i++;

}
do-while loop

Example:
Syntax:

do { int i = 0;

// code block to be executed do {

} System.out.println(i);

while (condition); i++;

}while (i < 5);


Java Programming elements:

1. Data types
2. Arrays
3. Control Structures
4. Class
5. Object
6. Method
7. constructor
8. Encapsulation
9. Abstraction and
Polymorphism
A typical Java file looks like:

import java.lang.*;
import java.util.*;
public class SomethingOrOther {
// object definitions go here
. . .
}
This must be in a file named SomethingOrOther.java !
Class
1. The class is at the core of Java.
2. It is the logical construct upon which the entire Java language is built
because it defines the shape and nature of an object.
3. Any concept you wish to implement in a Java program must be
encapsulated within a class.
4. While defining a class, you declare its exact form and nature, by
specifying the data that it contains and the code that operates on that
data.
5. While very simple classes may contain only code or only data, most
real-world classes contain both.
Class (cont.)
class classname
{
1. A class is declared by use of the class type instance-variable1;
type instance-variable2;
keyword. // …………
type instance-variableN;
2. The data, or variables, defined within a
class are called instance variables. type methodname1(parameter-list)
{
3. The code is contained within methods. // body of method
}
4. Collectively, the methods and variables type methodname2(parameter-list)
defined within a class are called {
// body of method
members of the class. }
// ...
type methodnameN(parameter-list)
{
// body of method
}
}
Class deceleration
Example:
Syntax
class Student
class class_name
{
{
int roll;
Attribute declaration;
char name;;
//data members
//data members
Function declaration;
int getdata();
// member function
void marks();
} // member function
}
Class
1. A class consists of a collection of fields, or variables, very
much like the named fields of a struct all the operations (called
methods) that can be performed on those fields

2. A class describes objects and operations defined on those


objects
Variable
class Person {
String name;
int age; Method
void birthday ( ) {
age++;
System.out.println (name +
' is now ' + age);
}
}
Class Example
Question

Can I access class variables and methods without creating objects?


Ans:
Yes,using static keyword. (Example)
Java Programming elements:

1. Data types
2. Arrays
3. Control Structures
4. Class
5. Method
6. object
7. constructor
8. Encapsulation
9. Abstraction and
Polymorphism
Declaring Object in Java
1. When you create a class, you are creating a new data type. You can
use this type to declare objects of that type.
2. Obtaining objects of a class is a two-step process:
a. First, you must declare a variable of the class type.
i. This variable does not define an object.
ii. Instead, it is simply a variable that can refer to an object.
b. Second, you must acquire an actual, physical copy of the object
and assign it to that variable.
i. This is achieved using the new operator.
Declaring Object in Java
1. The new operator dynamically allocates (that is, allocates at run time)
memory for an object and returns a reference to it.
2. This reference is, more or less, the address in memory of the object
allocated by new.
3. This reference is then stored in the variable.
Box mybox = new Box();

Box mybox; //declare reference to object


mybox = new Box(); //allocate a Box object
Declaring Object in Java
Java Programming elements:

1. Data types
2. Arrays
3. Control Structures
4. Class
5. Object
6. Method
7. constructor
8. Encapsulation
9. Abstraction and
Polymorphism
Methods
1. Syntax:
type name(parameter-list)
{
// body of method
}
2. type specifies the type of data returned by the method.
a. This can be any valid type, including class types that you create.
b. If the method does not return a value, its return type must be
void.
Methods
1. The name of the method is specified by name.
a. This can be any legal identifier other than those already used by
other items within the current scope.
2. The parameter-list is a sequence of type and identifier pairs
separated by commas.
a. Parameters are essentially variables that receive the value of the
arguments passed to the method when it is called.
b. If the method has no parameters, then the parameter list will be
empty.
Methods

1. Methods that have a return type other than void return a value to the
calling routine using the following form of the return statement:
2. return value;
a. Here, value is the value returned.
Adding Methods
Adding Methods

Output:
Volume is 3000.0
Volume is 162.0
Adding Methods
1. Inside the volume( ) method: the instance variables width, height, and
depth are referred to directly, without preceding them with an object
name or the dot operator.
2. When a method uses an instance variable that is defined by its class, it
does so directly, without explicit reference to an object and without use of
the dot operator.
3. A method is always invoked relative to some object of its class.
4. Once this invocation has occurred, the object is known.
5. Thus, within a method, there is no need to specify the object a second
time.
6. This means that width, height, and depth inside volume( ) implicitly refer
to the copies of those variables found in the object that invokes volume( )
.
Returning a Value
Returning
a Value
Example
public class example {
class Rect { public static void main(String[]
int len; args) {
int bth; Rect r = new Rect();
int area() { r.len = 5;
int y; r.bth = 2;
y = len * bth; int x;
x = r.area();
return y;
System.out.println("Area of
} rectangle is: " + x);
} }
}
Method with Parameter
1. Parameters allow a method to be generalized.
2. That is, a parameterized method can operate on a variety of
data and/or be used in a number of slightly different situations.

int square() int square(int i)


{ {
return 10 * 10; return i * i;
} }
Example
class Rect public class example
{ {
int len; public static void main(String[] args)
int bth; {
void setDim(int x, int y) Rect r = new Rect();
{ r.setDim(5,2);
len = x; int x;
bth = y; x = r.area();
} System.out.println("Area of rectangle is: " + x);
int area() }
{ }
int y;
y = len * bth;
return y;
}
}
Method with Parameter
Method with Parameter
Class and Object example:
we can consider a car as a class that has characteristics like steering wheels,
seats, brakes, etc. And its behavior is mobility. But we can say Honda City
having a reg.number 4654 is an ‘object’ that belongs to the class ‘car’.
Java Programming elements:

1. Data types
2. Arrays
3. Control Structures
4. Class
5. Object
6. Method
7. constructor
8. Encapsulation
9. Abstraction and
Polymorphism
Constructors
● A constructor is a block of codes similar to the method.
● Java constructor is invoked at the time of object creation. It constructs the
values i.e. provides data for the object that is why it is known as constructor
● 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 internal
state of the object.
● Every time an object is created using the new() keyword, at least one
constructor is called.
Constructors
● It has the same name as the class in which it resides and is syntactically similar
to a method.
● Once defined, the constructor is automatically called when the object is created,
before the new operator completes.
● Constructors have no return type, not even void.
● This is because the implicit return type of a class’ constructor is the class type
itself.
● It is the constructor’s job to initialize the internal state of an object so that the
code creating an instance will have a fully initialized, usable object immediately.
Example with method
Types of constructors

1. Default constructor (no-arg constructor)

2. Parameterized constructor
Java Default Constructor

A constructor that have no parameter is known as default


constructor.
Java creates a default constructor for the class, when a
constructor is not defined explicitly for a class.
The default constructor automatically initializes all instance
variables to their default values, which are zero, null, and
false, for numeric types, reference types, and boolean,
respectively.
Syntax of default constructor:
<class_name>(){}
class Bike1 Example of default constructor
{
Bike1()
{
System.out.println("Bike is created");
}
public static void main(String args[])
{
Bike1 b=new Bike1();
}

}
Output:

Bike is created
If there is no constructor in a class, compiler automatically creates a
default constructor. Default constructor provides the default values to
the object which are zero, null, and false, for numeric types,
reference types, and boolean, respectively.

class Student{
int id;
String name;
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student s1=new Student();
s1.display();
}
}
Output: 0 null
Example with constructor:
Parameterized constructor

A constructor that have parameters is known as parameterized


constructor.
● Parameterized constructor is used to provide different values
to the distinct objects.
● It may be necessary to initialize the various data elements of
different objects with different values when they are created.
● This is achieved by passing arguments to the constructor function
when the objects are created.
class Student{
int id;
String name;

Student(int i,String n){


id = i;
name = n;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student s1 = new Student(111,"Karan");
s1.display();
}
}
Output:
111 Karan
Parameterized Constructors
Parameterized Constructors

Box myBox3 = new Box();


Constructor Overloading

Constructor overloading is a technique in Java in which a class


can have any number of constructors that differ in parameter
lists.

The compiler differentiates these constructors by taking into


account the number of parameters in the list and their type.
class Student5{
int id;
String name;
int age;
Student5(int i,String n){
id = i;
name = n;
}
Student5(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}
public static void main(String args[]){
Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s1.display();
s2.display();
}
}
Output: 111 Karan 0
222 Aryan 25
Parameterized Constructors
Parameterized Constructors
Difference between constructor and method
in java

You might also like