2. Basic Concepts of Object Orientation
Object
Class
Abstraction
Encapsulation
Inheritance
Polymorphism
3. What Is an Object?
Informally, an object represents an entity, either
physical, conceptual, or software.
Physical entity
Conceptual entity
Software entity
Truck
Chemical
Process
Linked List
4. A More Formal Definition
An object is an entity with
a well-defined boundary
and identity that
encapsulates state and
behavior.
State is represented by
attributes and relationships.
Behavior is represented by
operations, methods, and
state machines.
Object
Operations
Attributes
5. What Is a Class?
A class is a description of a set of objects that share the
same properties and behavior.
An object is an instance of a class.
Data Items:
manufacturer‟s name
model name
year made
color
number of doors
size of engine
etc.
Methods:
Define data items
Change a data item
Display data items
Calculate cost
etc.
Class: Automobile
6. Object
Defined as instance of a class. for e.g. table, chair are all
instances of the class Furniture.
Objects have unique identity, state and behavior
State is defined by the attributes of the object.
Different objects have different attributes ( characteristics)
For e.g. the attributes of student are name, roll number etc
Behavior actually determines the way an object interacts with
other objects.
Synonym to functions
7. Class
Blueprint for an object, a plan, or template
Description of a number of similar objects is also
called class.
A class is also defined as a new data type; a user
defined type.
Defining a class doesn‟t create an object.
Classes are logical in nature.
For e.g. Furniture do not have any existence but
tables and chairs do exist.
9. What Is Abstraction?
• Any model that includes the most important, or
essential aspects of something while suppressing
or ignoring less important, immaterial, details..
• Hide the complexity
• Emphasizes relevant characteristics.
BriefCase
- Capacity
- Weight
+ open()
+ close()
10. What Is Abstraction?
Another example is car
ignore the details of how the engine,
transmission, and braking systems work
From the outside, the car is a single object.
Inside, the car consists of several subsystems
The point is that you manage the complexity of
the car through the use of hierarchical
abstractions
11. Encapsulation
Encapsulation is the mechanism that binds
together code and the data it manipulates,
and keeps both safe from outside interference
and misuse.
Restrict any one to directly alter our data.
Also known as Data hiding.
Example: Car
In Java the basis of encapsulation is the class
13. What Is Inheritance ?
Inheritance —a way of organizing classes
Inheritance is the process by which one object acquires the
properties of another object.
Way to adopt characteristics of a class into another class.
Have two types of classes one is base class and other is
subclass.
A parent-child relationship among classes in inheritance.
A subclass inherits all the properties of base class. In
addition to this it can add its own features (properties and
behavior).
Is an “is a kind of” relationship
14. An Inheritance Hierarchy
Vehicle
Automobile Motorcycle Bus
Sedan Sports Car School Bus Luxury Bus
What properties does each vehicle inherit from
the types of vehicles above it in the diagram?
15. Example: Single Inheritance
One class inherits from another.
Checking
Savings
Superclass
(parent)
Subclasses
Inheritance
Relationship
Ancestor
Descendents
Account
- balance
- name
- number
+ withdraw()
+ createStatement()
16. Polymorphism
Polymorphism means many forms.
Same thing being used in different forms.
Example :Addition operator (+)
addition of two integers
concatenation of two strings.
19. Java Environment
Development tools-part of java development kit (JDK).
Classes and methods-part of Java Standard Library (JSL),
also known as Application Programming Interface (API).
JDK:
Appletviewer ( for viewing applets)
javac (Compiler)
java (Interpreter)
javap (Java disassembler)
javah (for C header files)
javadoc ( for creating HTML description)
jdb (Java Debugger)
19
20. Java Environment
Application Programming Interface (API)
Contains hundreds of classes and methods grouped into several
functional packages:
Language Support Package (lang)
Utility Packages (util)
Input/Output Packages (io)
Networking Packages (net)
AWT Package (awt)
Applet Package (applet)
20
21. Features of Java
1. Simple, Small and Familiar
2. Compiled and Interpreted
3. Object Oriented
4. Platform Independent and portable
5. Robust and Secure
6. Distributed / Network Oriented
7. Multithreaded and Interactive
8. High Performance
9. Dynamic
21
22. Java Virtual Machine
Java compiler produces an intermediate code known as byte
code for a machine, known as JVM.
It exists only inside the computer memory.
Machine code is generated by the java interpreter by acting
as an intermediary between the virtual machine and real
machine.
Java Program
.java file
Java Compiler
Virtual Machine
.class file (byte code)
Virtual machine
Bytecode
Java Interpreter
Real machine
Machine Code
22
23. Simple JAVA program
class Hello
{
public static void main(String
args[])
{
System.out.println(“HELLO
WORLD”);
}
}
OUTPUT
HELLO WORLD
To save:
Hello.java
To compile:
javac Hello.java
To execute:
java Hello
24. Keyword Description & use
class • keyword in java
•Used to define class
public • Is an access specifier
•Member is accessible every where in program
static • call/invoke a function without creating an object
void • return type of method
• returns nothing
main • name of method
• staring point of program execution
String • class in Java
args[] • array of String type objects
• used to take command line arguments as a input
System • class in Java
• provides access to the system (input/output)
out • output stream that is connected to console
println() • method of System class
• used to display string passed to it or other type of
information
25. Tokens in JAVA
Character set
Keywords
Identifiers
Constant and variables
Data types
Operators
28. Variables
Variables represent names of memory locations
during program execution.
Data values processed in the program are stored in
memory locations and referenced through variables.
Example:
X
Abc
Sum
Sum_5
Sum_of_values
29. Identifiers
Identifiers are names assigned to variables,
constants, methods, classes, packages and
interfaces.
No limit has been specified for the length of
a variable name.
30. Rules for Naming
The first character of an identifier must be a letter, an
underscore (_), or a dollar sign ($).
Use letter, underscore, dollar sign, or digit for subsequent
characters.
white spaces are not allowed within identifiers.
Identifiers are case-sensitive. This means that Total_Price
and total_price are different identifiers.
Do not use Java‟s reserved words ie. Keywords.
31. Valid and invalid identifiers
Legal Identifiers
MyClass
$amount
_totalPay
total_Commission
Illegal Identifiers
My Class
23amount
-totalpay
total@commission
32. Naming Conventions
Class or Interface identifiers begin with a capital letter. First alphabet of
every internal word is capitalized. All other letters are in lowercase.
Variable or Method identifiers start with a lowercase letter. First
alphabet of every Internal word is capitalized. All other letters are in
lowercase.
Constant identifiers All letters are specified in Upper case. Underscore
is used to separate internal words (_).
Package identifiers consist of all lowercase letters.
33. Java defines eight simple (or elemental) 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 whole-valued 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.
Data types in JAVA
34. Integer type
Data
type
Size Range Default value Example
byte
1-byte/
8-bits
-128 to +127 0 byte b=100;
short
2-byte/
16-bits
– 32,768 to 32,767 0 short s=200;
int
4-byte/
32-bits
–2,147,483,648 to 2,147,483,647 0 int i=20000;
long
8-byte/
64-bits
–9,223,372,036,854,775,808 to
9 ,223,372,036,854,775,807
0L
long
l=20000000;
Java defines four integer types: byte, short, int, and long. All of these are signed,
positive and negative values. Java does not support unsigned, positive-only
integers.
35. Floating-point type
Data
type
Size Range Default value Example
float
4-byte/
32-bits
3.4e–038 to 3.4e+038 0.0F float f=3.14f;
double
8-byte/
64-bits
1.7e–308 to 1.7e+308 0.0D double d=215.5;
Floating-point numbers, also known as
real numbers, are used when evaluating
expressions that require fractional
precision.
36. Character type
Data
type
Size Range Default value Example
char
2-byte/
16-bits
0-65536 ‘u0000’ char ch='A';
•Java uses Unicode to represent characters.
•Unicode defines a fully international character set
that can represent all of the characters found in all
human languages.
•It is a unification of dozens of character sets, such as
Latin, Greek, Arabic, Cyrillic, Hebrew, Katakana,
Hangul, and many more.
37. Boolean type
Data
type
Size Range Default value Example
boolean
1-byte/
8 bits
true/false false
boolean
b=false;
Java has a simple type, called boolean, for logical values. It can
have only one of two possible values, true or false.
39. Assignment Operator
Operator Result Example
= assignment a=b
p=10
x=b+c
Assign value of the variable, constant or result of
expression to the left hand side variable.
LHS- always a variable
RHS- may be variable, constant or expression
40. Arithmetic Operators
Operator Result Example
+ Addition a=b+c
- Subtraction (also unary minus) a=b-c
* Multiplication a=b*c
/ Division a=b/c
% Modulus a=b%c
Used to perform arithmetic operations like addition,
subtraction, multiplication and division.
41. Arithmetic assignment operators
Operator Result Example
+= Addition assignment a+=b => a=a+b
-= Subtraction assignment a-=b => a=a-b
*= Multiplication assignment a*=b => a=a*b
/= Division assignment a/=b => a=a/b
%= Modulus assignment a%=b => a=a%b
Used to perform arithmetic operations when left
hand side variable is also present on right hand
side or result of expression evaluation is stored in
one of the right hand side variable.
42. Increment/Decrement operator
Operator Result Example
++ Increment a++ or ++a
- - Decrement a-- or –a
Prefix increment/ decrement- first perform the
increment/decrement operation and then use updated
value in current expression.
Postfix increment/ decrement- first use the value
of the variable and the perform the
increment/decrement operation.
43. Relational Operators
In Java, true and false are nonnumeric values which do not
relate to zero or nonzero. Therefore, to test for zero or nonzero,
you must explicitly employ one or more of the relational
operators.
Operator Result Example
== Equal to (5==5) gives true
!= Not equal to (4!=5) gives true
> Greater than (6>5) gives true
< Less than (5<4) gives false
>= Greater than or equal to (5>=5) gives true
<= Less than or equal to (6<=5) gives false
44. Logical operators
Used to check two or more conditions
Operator Result Example
&& Logical AND (5<6)&&(6>7) gives false
|| Logical OR (5<6)||(6>7) gives true
! Logical NOT !(5<6) gives false
46. Bitwise operators
Operator Result Example
& Bitwise AND 2&3=2
| Bitwise OR 2|3=3
~ Bitwise NOT 2^3=1
^ Bitwise EXOR ~2=-3
<< LEFT SHIFT 10<<2
>> RIGHT SHIFT 10>>2
>>> RIGHT SHIFT WITH
ZERO FILL
10>>>2
50. 52
Classes
A Class is a collection of data members (data)
and member functions(methods or procedure).
Data members are nothing but simply variables(to specify
attributes) that we declare inside the class
Member functions are the function or methods(to specify
behavior) which we declare inside the class
e.g.
Circle
radius
circumference()
area()
51. 53
Classes
The basic syntax for a class definition:
The data, or variables, defined within a class are also called the instance
variables
class classname {
type instance-variable1;
type instance-variable2;
//……….
type instance-variableN;
return type methodname1(parameter-list)
{
// body of method
}
return type methodname2(parameter-list)
{
// body of method
}
}
52. 54
Adding Variables & Methods
class Circle {
double r; // radius of circle
double c ,a; //area and circumference
//Methods to return circumference and area
void circumference() {
c=2*3.14*r;
System.out.println(“Circumference =“ +c);
}
void area() {
return 3.14 * r * r;
System.out.println(“Area =“ +a);
}
}
53. 55
Creating objects of a class
Declare the Circle class, have created a new data type and we
can define variables (objects) of that type:
Syntax :
classname objectname;
e.g.
Circle c1; //declaring object
Circle c2;
c1
Points to nothing (Null Reference)
c2
Points to nothing (Null Reference)
null null
54. 56
Creating objects of a class
Objects are created dynamically using the new keyword.
Syntax:
classname objectname;
objectname=new classname(); //allocate memory
e.g. Circle c1;
c1 = new Circle() ;
or
Circle c1 = new Circle(); //combine 2 statements
c2= new Circle() ;
c1 = new Circle() ;
c1.r
circumference()
area()
c2.r
circumference()
area()
55. 57
Accessing Object/Circle Data
Similar to C syntax for accessing data defined
in a structure.
Circle c1= new Circle();
c1.r = 2.0 // initialize radius
c1.area(); //calling method
ObjectName.VariableName
ObjectName.MethodName(parameter-list)
56. Using Circle Class
class Circle {
double r; // radius of circle
double c ,a; //area and circumference
//Methods to calculate circumference and
area
void circumference() {
c=2*3.14*r;
System.out.println(“Circumference =“ +c);
}
void area() {
a=3.14 * r * r;
System.out.println(“Area =“ +a);
}
}
class MyMain
{
public static void main(String args[])
{
Circle c1; // creating reference
c1 = new Circle(); // creating object
c1.r = 5; // assigning value to data field
// invoking method
c1.area();
c1.circumference();
}
}
58
57. Method returning value
class Circle {
double r; // radius of circle
double c ,a; //area and circumference
//Methods to return circumference and area
double circumference() {
c=2*3.14*r;
return c ;
}
double area() {
a=3.14 * r * r;
return a;
}
}
class MyMain
{
public static void main(String args[])
{
double area,circumference;
Circle c1; // creating reference
c1 = new Circle(); // creating object
c1.r = 5; // assigning value to data field
// invoking method
area=c1.area();
circumference=c1.circumference();
System.out.println(“Area =“ +area);
System.out.println(“Circumference =“ +circumference);
}
}
59
58. Methods with parameters
class Circle {
double c ,a; //area and circumference
//Methods to return circumference and area
void circumference( int r) {
c=2*3.14*r;
System.out.println(“Circumference =“ +c);
}
void area(int r) {
a=3.14 * r * r;
System.out.println(“Area =“ +a);
}
}
class MyMain
{
public static void main(String args[])
{
Circle c1; // creating reference
c1 = new Circle(); // creating object
int radius= 5;
// invoking method
c1.area(radius);
c1.circumference(radius);
}
}
60
59. Exercise
WAP to create class rectangle and calculate area
and perimeter of it.
WAP to create class Student. Add methods to
read and display student information such as roll
number, marks of two subjects.
61