Java PPT Ib
Java PPT Ib
⚫ Object
⚫ Class
⚫ Data Abstraction & Encapsulation
⚫ Inheritance
⚫ Polymorphism
⚫ Dynamic Binding
⚫ Message Passing
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.
⚫{
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
FIGURE
Ob1 Ob3
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 Constructor();
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
– The tree of classes that extend from Object and all of its
subclasses are is called the class hierarchy
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.
StudentType
Name (string)
Marks (num)
Grade (char)
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 variabledeclared inside the scope is not visible outside:
{
int n;
}
n = 1;// this is illegal
Arrays
⚫ 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
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-variable.
Array Indexing
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
! ! op Logical NOT
L 3.3
Jump Statements
L 4.3
Object Creation
L 4.5
Class
L 4.7
Example: Class Usage
class Box {
double width;
double height;
double depth;
}
class BoxDemo {
public static void main(String args[]) {
Box mybox = new Box();
double vol;
mybox.width = 10;
mybox.height = 20;
mybox.depth = 15;
vol = mybox.width * mybox.height * mybox.depth;
System.out.println ("Volume is " + vol);
} }
Constructor
⚫ A constructor initializes the instance variables of an object.
⚫ It is called immediately after the object is created but before
the new operator completes.
1) it is syntactically similar to a method:
2) it has the same name as the name of its class
3)it is written without return type; the default
return type of a class
⚫ constructor is the same classWhen the class has no
constructor, the default constructor automatically initializes
all its instance variables with zero.
Example: Constructor
class Box {
double width;
double height;
double depth;
Box() {
System.out.println("Constructing Box");
width = 10; height = 10; depth = 10;
}
doublevolume() {
return width * height * depth;
}
}
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 * depth;
}
}
Methods
L 5.4
Example: Method
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.
Visibility
public class Circle {
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 a String constant
⚫ 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: " +
strOb1.length());
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");
}}
107
I⚫nInhheerirtaintcae nrelcateionships are often shown
graphically in a class diagram, with the arrow
pointing to the parent class
Animal
weight : int
Inheritance
+ getWeight() : int should create an
is-a relationship,
meaning the
Bird child is a more
specific version
of the parent
+ fly() : void
108
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() {…}
}
109
Class Hierarchy
⚫ A child class of one parent can be the parent of another
child, forming class hierarchies
Animal
111
Defining Methods in the Child Class:
Overriding by Replacement
⚫ A child class can override the definition of an inherited method in
favor of its own
⚫ that is, a child can redefine a method that it inherits from its parent
⚫ the new method must have the same signature as the parent's method,
but can have different code in the body
112
Defining Methods in the Child Class:
Overriding by Refinement
⚫ Constructors in a subclass override the definition of an inherited constructor
method by refining them (instead of replacing them)
- Assume class Animal has constructors
Animal(), Animal(int weight), Animal(int weight, int livespan)
- Assume class Bird which extends Animal has constructors
Bird(), Bird(int weight), Bird(int weight, int livespan)
113
Recap: Class Hierarchy
⚫ In Java, a class can extend a single other class
(If none is stated then it implicitly extends an Object class)
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
Extends
Is a keyword used to inherit a class from another class
Allows to extend f rom only one class
class One class Two extends One
{ int a=5; {
} int b=10;
}
Subclass, Subtype and Substitutability
⚫ A subtype is a class that satisfies the principle of
substitutability.
⚫ A subclass is something constructed using inheritance,
whether or not it satisfies the principle of substitutability.
⚫ The two concepts are independent. Not all subclasses are
subtypes, and (at least in some languages) you can
construct subtypes that are not subclasses.
⚫ Substitutability is fundamental to many of the powerful
software development techniques in OOP.
⚫ The idea is that, declared a variable in one type may hold
the value of different type.
⚫ Substitutability can occur through use of inheritance,
whether using extends, or using implements keywords.
Subclass, Subtype, and Substitutability
When new classes are constructed using inheritance, the argument
used to justify the validity of substitutability is as follows;
• Instances of the subclass must possess all data fields associated
with its parent class.
•Instances of the subclass must implement, through inheritance
at least, all functionality defined for parent class. (Defining new
methods is not important for the argument.)
•Thus, an instance of a child class can mimic the behavior of the
parent class and should be indistinguishable from an instance of
parent class if substituted in a similar situation.
Subclass, Subtype, and
Substitutability
The term subtype is used to describe the relationship between
types that explicitly recognizes the principle of substitution. A type
B is considered to be a subtype of A if an instances of B can legally
be assigned to a variable declared as of type A.
The term subclass refers to inheritance mechanism made by
extends keyword.
Not all subclasses are subtypes. Subtypes can also be formed
using interface, linking types that have no inheritance relationship.
Subclass
⚫ Methods allows to reuse a sequenceof statements
+ 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
SUPER SUPER
extends extends
implement
extends
s
SUPER 1 SUPER 2
SUB
SUB
extends implement
extends
s
Book
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;