JAVA PPT Extract (1-97)
JAVA PPT Extract (1-97)
JAVA PPT Extract (1-97)
⚫ Object
⚫ Class
⚫ Data Abstraction & Encapsulation
⚫ Inheritance
⚫ Polymorphism
⚫ Dynamic Binding
Object
⚫Objects are the basic run time entities in an object-
oriented system. They may represent a person, a place,
a bank account, a table of data or any item that the
program has to handle.
Class
⚫ The entire set of data and code of an object can be made of a
user defined data type with the help of a class.
⚫ In fact, Objects are variables of the type class. Once a class has
been defined, we can create any number of objects belonging to
that class.
⚫ Classes are data types based on which objects are created.
Objects with similar properties and methods are grouped
together to form a Class. Thus a Class represents a set of
individual objects.
⚫ Characteristics of an object are represented in a class as
Properties. The actions that can be performed by objects
become functions of the class and is referred to as
Methods.
⚫
A class is thus a collection of objects of similar type .
for example: mango, apple, and orange are members of
the class fruit . ex: fruit mango; will create an object
mango belonging to the class fruit.
Example for
class
⚫ class Human
⚫{
private:
⚫ EyeColor IColor;
⚫ NAME personname;
⚫ public:
⚫ };
Data abstraction
⚫ Abstraction refers to the act of representing essential features
without including the background details or explanations. since the
classes use the concept of data abstraction ,they are known as
abstraction data type(ADT).
class
FIGUR
Ob1
E
Ob3
CIRCL Ob SQUARE
E 2
RECTANG
LE
syntax of CLASS
class <ClassName>
{
attributes/variables;
Constructors()
; methods();
}
INSTANCE
• Instance is an Object of a class which is an entity with its
own
attribute values and methods.
• Creating an Instance
ClassName
refVariable;
refVariable = new
Constructor();
or
ClassName
refVariable = new
Java Class Hierarchy
• In Java, class “Object” is the base class to all other classes
– If we do not explicitly say extends in a new class
definition,
it implicitly extends Object
Animal
weight : int
+ getWeight() : int
Bird
+ fly() : void
Method Overriding.
There may be some occasions when we want an object to
respond to the same method but have different behavior
when that method is called.
That means, we should override the method defined in the
super class. This is possible by defining a method in a sub class
that has the same name, same arguments and same return
type as a method in the super class.
Then when that method is called, the method defined in the
sub class is invoked and executed instead of the one in the
super class. This is known as overriding.
Exceptions in Java
• Exception is an abnormal condition that arises in the
code sequence.
• Exceptions occur during compile time or run time.
• “throwable” is the super class in exception hierarchy.
• Compile time errors occurs due to incorrect syntax.
• Run-time errors happen when
– User enters incorrect input
– Resource is not available (ex. file)
– Logic error (bug) that was not fixed
Abstraction in Object-Oriented Programming
Procedural Abstraction
• Procedural Abstractions organize
instructions.
Function Power
Give me two numbers (base & exponent)
I’ll return baseexponent
Implementation
Data Abstraction
• Data Abstractions organize data.
StudentTy
pe
Name (string)
Marks (num)
Grade (char)
Student Number
(num)
Data
Types
⚫ Java defines eight simple types:
1)byte – 8-bit integer type
2)short – 16-bit integer type 3)int
– 32-bit integer type
4)long – 64- bit integer
type
5)float – 32-bit floating-point
type 6)double – 64-bit floating-
point type 7)char – symbols in
a character set
8)boolean – logical values true
Variable
Declaration
⚫ We can declare several variables at the
same time: type identifier [=value][,
identifier [=value] …];
Examples:
int a, b, c;
int d = 3, e, f
= 5; byte g
= 22;
double pi =
3.14159; char
ch = 'x';
L
2.4
Variable
⚫
Scope
Scope determines the visibility of program elements
with respect
to other program elements.
⚫ In Java, scope is defined separately for classes and
methods:
1)variables defined by a class have a global scope
2)variables defined by a method have a
local scope A scope is defined by a block:
{
…
}
A variable declared inside the scope is
not visible outside:
{
int n;
}
n = 1;// this is illegal
Array
s
⚫ An array is a group of liked-typed variables
referred to by a common
⚫ name, with individual variables accessed by
their index.
⚫ Arrays are:
1)declared
2)created
3)initialized
4)used
⚫ Also, arrays can have one or several
dimensions.
Array
Declaration
⚫ Array declaration involves:
1)declaring an array identifier
2)declaring the number of dimensions
3)declaring the data type of the array
elements
⚫ Two styles of array declaration:
type array-variable[];
or
type [] array-variable;
L
2.8
Array Creation
⚫ After declaration, no array actually
exists.
⚫In order to create an array, we
use the new operator:
type array-variable[];
array-variable = new
type[size];
⚫This creates a new array to hold size
elements of type type, which
reference will be kept in the variable
Array
Indexing
⚫ Later we can refer to the elements of this
array through their indexes:
⚫ array-variable[index]
⚫ The array index always starts with zero!
⚫ The Java run-time system makes sure that all
array indexes are in the correct range,
otherwise raises a run- time error.
Array
Initialization
⚫ Arrays can be initialized when they are
declared:
⚫ int monthDays[] =
{31,28,31,30,31,30,31,31,30,31,30,31};
⚫ Note:
1)there is no need to use the new operator
2)the array is created large enough to hold
all specified elements
Operators
Types
⚫ Java operators are used to build value
expressions.
⚫ Java provides a rich set of operators:
1)assignment
2)arithmetic
3)relational
4) logical
5)bitwise
L
2.13
Arithmetic assignments
+= v += expr; v = v + expr ;
-= v -=expr; v = v - expr ;
*= v *= expr; v = v * expr ;
/= v /= expr; v = v / expr ;
%= v %= expr; v = v % expr ;
Basic Arithmetic Operators
+ op1 + op2 ADD
L
2.15
Relational
operator
== Equals to Apply to any type
L
3.3
Jump Statements
L
4.3
Object Creation
class Box {
double
width;
double
height;
double
depth;
Box() {
System.out.
println("Co
nstructing
Box");
width = 10;
height = L
5.2
Parameterized Constructor
class Box {
double
width;
double
height;
double
depth;
Box(double w, double h,
double d) { width = w;
height = h; depth = d;
}
double volume()
{ return width * height *
Methods
L
5.6
Access Control: Data
Hiding and
• Encapsulation
Java provides control over the visibility
of variables and methods.
• Encapsulation, safely sealing data within
the capsule of the class Prevents
programmers from relying on details of
class implementation, so you can update
without worry
• Helps in protecting against accidental
or wrong usage.
• Keeps code elegant and clean (easier
to maintain)
Access Modifiers: Public,
Private,
Protected
• Public: keyword applied to a class,
makes it available/visible everywhere.
Applied to a method or variable,
completely visible.
• Default(No visibility modifier is
specified): it behaves like public in its
package and private in other
packages.
• Default Public keyword applied to a
class, makes it available/visible
everywhere. Applied to a method or
variable, completely visible.
L
6.2
⚫ Private fields or methods for a class only
visible within that class. Private members are
not visible within subclasses, and are not
inherited.
⚫ Protected members of a class are visible
within the class, subclasses and also within
all classes that are in the same package as
that class.
Visibilit
public class Circle {
y
private double x,y,r;
// Constructor
public Circle (double x, double y, double r)
{ this.x = x;
this.y = y; this.r
= r;
}
//Methods to return circumference and area
public double circumference() { return 2*3.14*r;}
public double area() { return 3.14 * r * r; }
}
L
6.4
String Handling
⚫String is probably the most commonly used
class in Java's class library. The obvious
reason for this is that strings are a very
important part of programming.
⚫The first thing to understand about
strings is that every string you create is
actually an object of type String. Even
string constants are actually String
objects.
⚫ For example, in the statement
System.out.println("This is a
String, too");
the string "This is a String, too" is
⚫ Java defines one operator for String
objects: +.
⚫ It is used to concatenate two strings. For
example, this statement
⚫ String myString = "I" + " like "
+ "Java."; results in myString
containing
"I like Java."
L
8.4
⚫ The String class contains several methods that
you can use. Here are a few. You can
⚫ test two strings for equality by using
equals( ). You can obtain the length of a string by
calling the length( ) method. You can obtain the
character at a specified index within a string by
calling charAt( ). The general forms of these
three methods are shown here:
⚫ // Demonstrating some String
methods. class StringDemo2 {
public static void main(String
args[]) { String strOb1 =
"First String";
String strOb2 = "Second
String"; String strOb3 =
strOb1;
System.out.println("Length of strOb1:
"+
System.out.println ("Char at index 3 in
strOb1: " +
strOb1.charAt(3));
if(strOb1.equals(strOb2))
System.out.println("strOb1 ==
strOb2"); else
System.out.println("strOb1 !=
strOb2");
if(strOb1.equals(strOb3))
System.out.println("strOb1 ==
strOb3"); else
System.out.println("strOb1 !=
strOb3");
}}
10
Class
⚫
Hierarchy
A child class of one parent can be the parent
of another
child, forming class hierarchies
Animal
Animal
⚫ inheritance is transitive
⚫ An instance of class Parrot is also an
instance of Bird, an instance of Animal, …,
and an instance of class Object
Base Class Object
⚫ In Java, all classes use inheritance.
⚫ If no parent class is specified explicitly, the base class Object is
implicitly inherited.
⚫ All classes defined in Java, is a child of Object class, which provides
minimal functionality guaranteed to e common to all objects.
⚫ Methods defined in Object class are;
1. equals(Object obj): Determine whether the argument object is the
same as the receiver.
2. getClass(): Returns the class of the receiver, an object of type Class.
3. hashCode(): Returns a hash value for this object. Should be
overridden when the equals method is changed.
4. toString(): Converts object into a string value. This method is
also often overridden.
Base class
1)a class obtains variables and methods from another
class
2)the former is called subclass, the latter super-class
(Base class)
3)a sub-class provides a specialized behavior with
respect to its super-class
4)inheritance facilitates code reuse and avoids
duplication of
data
Allows to extend rom only one class
class Two extends One
Extends
f class One
{ int { from another class
Is a keyword used to inherit a class
+ getWeight() : int
Bird
+ fly() : void
Substitutability (Deriving
Subclasses)
⚫ In Java, we use the reserved word extends to establish
an
inheritance relationship
class Animal
{
// class contents
int weight;
public void int
getWeight() {…}
}
⚫ Program Size
⚫ Message-Passing Overhead
SUPE SUPE
R R
exten exten
ds ds
SU SUB SUB
B 1 2
2. Multi 3.
Level Multiple
Inheritanc SUPE Inheritan
e SUPE R1 SUPE
R R2 ce
impleme
exten
nt
ds SUPE SUPE
s R1 R2
SU
SU
B
B
exten impleme
exten
ds nt s
ds
SUB SU
SUB B
The protected
Modifier
⚫ The protected visibility modifier allows a member
of a base
class to be accessed in the child
⚫ protected visibility provides more
encapsulation than
public does
⚫ protected visibility is not as tightly
encapsulated as Book
private visibility protected int pages
+ getPages() : int
+ setPages(): void
Dictionary
+ getDefinitions() : int
+ setDefinitions(): void
+ computeRatios() : double
“super” uses
‘super’ is a keyword used to refer to hidden variables of super
class from sub class.
super.a=a;