Professional Documents
Culture Documents
LANGUAGE II
Lecture 2 &3: Classes & objects
Lecture Contents
What is a class?
Class basics:
Data
Methods
Objects
Defining and using a class
Access identifiers
Private
Public
Set/get methods
Data initialization
What is a constructor?
Defining constructors
Overloading constructor
Using this reference
Example:
int data type has:
Data: +-32,767
Operations: +, - , * , / , %
Same with classes
Collection of data values together with set of basic
operations to be allowed for the values
Class
design
Object
creation
Member
access
Public
keyword
access modifier //methods...
class is
“available to //not static!!
the public
No main
can’t execute
}
Dot separator
//call a method
}
Dr. Amal Khalifa, 2016
Controlling Access to Members
Access modifiers
Public Methods
Client’s view of the services provided by the class
Private data
not accessible outside the class (Data Hiding)
protected.
//methods public
}
Dr. Amal Khalifa, 2016
Set/get methods
• Object needs to “have access" to its data
• accessor methods
• Allow object to read data
• Also called "get methods"
• Simple retrieval of member data
• Mutator methods
• Allow object to change data
• Also called “set methods"
• Manipulated based on application
Dr. Amal Khalifa, 2016
Example: set/get methods
// Student.java
. Class
Methods have public class Student {
direct access // data
to class
members
(data or
methods) //methods
//set methods
//get methods
}
Dr. Amal Khalifa, 2016
Instance Variables, Initial values
Primitive-type
initialized by default
byte,char, short, int, long, float and double initialized to 0
Boolean initialized to false.
//other methods
}
//print data
}
//constructors
public Student()
{
}
//set/get methods
//other methods
}
//print data
}
More on classes :
The finalize method
static members
final members
The student case study :
static
Arrays as data members
Use set
methods inside
constructors
Check for
valid inputs
Time2 class
7
Time2 class
8
static field:
called a class variable
represents class-wide information—only one copy is
be shared by all objects of a class.
The declaration begins with the keyword static.
public static members can be accessed through a
reference to any object of the class, or by qualifying the
member name with the class name and a dot (.).
If a static variable is not initialized, the compiler assigns
it a default value.
A static
variable is
accessible by
all methods in
a class
Example
18
Static methods
are used to
access static
variables
Static methods
can be called
whether or not
there are any
objects or not
Call to static
method either
through the
class name or
created
objects
Example
20
Good practice
to set
references to
null for
garbage
collector
static Class Members (Cont.)
21
A static import:
enables you to access the static members of a class
via their unqualified names (class name and a dot (.)
are not required)
Two forms
One that imports a particular static member (which
is known as single static import)
One that imports all static members of a class
(which is known as static import on demand)
Use Math
functions with
their simple
names
final Instance Variables
24
Keyword final :
specifies that a variable is not modifiable (i.e., it’s a constant)
private final int INCREMENT;
Preventing code from accidental modification of
variable values.
final variables can be initialized:
when they are declared, or
by each of the class’s constructors so that each object
of the class has a different value.
If a class provides multiple constructors, every one would be
required to initialize each final variable.
Dr. Amal Khalifa, 2014
Example
25
Final
variables must
be initialized
in constructor
Example
26
Use
constructor
to initialize
final
member
27 Dr. Amal Khalifa, 2014
Apply on Student class!!
28
static members:
Add a static field to count the number of active student
objects.
Add the needed methods to access the count
information
Enrolled courses
Max / semester = 7
Arrays?
Composition
What?
When?
How?
Case Study
Date class
Full constructor
Check input
values
Check input
ranges
Leap year??
Output format
Reference to
objects of
other classes
Date objects
used to
initialize date
objects
Implicit call to
the toString()
method
admissionDate
What is Inheritance?
Super-class & sub class
The object class
Using extends keyword
@override keyword
Creating subclasses
Protected members
What is protected?
Data Hiding issues
Inheritance Hierarchy
Case study : Campus Community
Constructors call chain
Superclasses
“more
general”
subclasses
“more
specific.”
every
subclass
object is an
object of its
superclass
Extends
object not
required; this
will be done
implicitly
Constructors
are not
inherited
Set/get
methods
Set/get
methods
Set/get
methods
@Override
ensures
overridded
method has
the same
signature as
the base class
New
employee
object
Implicit call
to the
method
toString
Inheritance issue
A subclass can inherit methods that it does not need or
should not have.
Even when a superclass method is appropriate for a
subclass, that subclass often needs a customized
version of the method.
The subclass can override (redefine) the superclass
method with an appropriate implementation.
An overrided subclass method can access the superclass method
using the keyword super and a dot (.) separator.
New class
defined
based on an
existing one
public
members are
accessible
from
anywhere
private
members are
accessible
only within the
class itself.
A superclass’s
private
members are
hidden in its
subclasses
Compilation
errors occur
when the
subclass
attempts to
access the
superclass’s
private
instance
variables.
What if data
is private??
Encapsulation
better
design
Use set/get,
either within
class or in
subclasses
Information
hiding
Starting from
the bottom,
you can follow
the arrows
and apply the
is-a
relationship
up to the
topmost
superclass.
CommunityMember
First Name
Last Name
SSN
BirthDate
Employee Student
Title UnvID
HireDate Faculty
Salary Level
Faculty Staff
CS111: PROGRAMMING
LANGUAGE II
Computer Science
Department
Lecture 6: Arrays & ArrayLists
Lecture Contents
2
What is a Array?
Arrays of objects
ArrayList
What is an array?
data structures
related data items of the same type.
fixed length once created.
Elements referred to using index or subscript.
declare
MyClass[] arr;
create
arr = new MyClass[SIZE];
initialize
for(int i=0;i<SIZE;i++)
arr[i] = new MyClass(…);
The Student Class
6
@Override
public String toString() {
return "Student{" + super.toString() + "\nUnvId = " +
UnvId + ", Faculty= " + Faculty + ", Level= " + Level + '}';
}
//don’t forget
//import java.util.ArrayList
ArrayList<Student> MyList = new ArrayList<Student>();
System.out.println("before add " + MyList.size());
MyList.add(new Student("Malak", "Hamad", "12345",new
MyDate(12,3,1997),"22222", "Arts", 2));
What is polymorphism?
Demonstratingpolymorphic behavior.
Overridden methods and polymorphism
Polymorphic processing
Application
animal Move
Abstract classes
Sometimes it’s useful to declare classes for which you never intend to
create objects.
Cannot be used to instantiate objects—abstract classes are incomplete.
An abstract class provides a superclass from which other classes can
inherit and thus share a common design.
Used only as superclasses in inheritance hierarchies, so they are
sometimes called abstract superclasses.
Not all hierarchies contain abstract classes.
Abstract classes sometimes constitute several levels of a hierarchy.
Abstract class
abstract
keyword
One concrete
class
hourly
employees
are paid by
the hour and
receive
overtime pay
(i.e., 1.5 times
their hourly
salary rate)
for all hours
worked in
excess of 40
hours,
commission
employees
are paid a
percentage
of their
sales
Array of
references to
the base class
Each reference
is instantiated
as an object of
a concrete
class.
Dynamic
binding
different
method calls
according to
actual type!!
downcasting
enables a
program to
invoke
subclass
methods that
are not in the
superclass.
getClass
method
returns an
object of type
Class including
its class name.
39 dr. Amal Khalifa, 2016
40 dr. Amal Khalifa, 2016
41 dr. Amal Khalifa, 2016
Polymorphism Example
42
What is an interface?
Creating and using interfaces in java
When a class
implements an
interface, it
should
implement
each of the
methods in the
interface or
declared
abstract.
Any concrete
subclass of the
abstract class
inherits the
superclass’s
contract and
thus must
implement the
interface
methods.
Objects of
any subclasses
of a class that
implements an
interface can
also be
thought of as
objects of the
interface
type.
catch
Finally
throws clause
Types of exceptions
Examples:
ArrayIndexOutOfBoundsException occurs
when an attempt is made to access an element past
either end of an array.
ClassCastException occurs when an attempt is
made to cast an object that does not have an is-a
relationship with the type specified in the cast operator.
NullPointerException occurs when a null
reference is used where an object is expected.
Information includes:
The name of the exception in a descriptive message
that indicates the problem that occurred
The method-call stack (i.e., the call chain) at the time it
occurred. Represents the path of execution that led to
the exception method by method.
This information helps you debug the program.
throws
clause—
specifies the
exceptions a
method
throws.
can throw
exceptions of
the classes
listed in its
throws clause
or of their
subclasses.
try block
encloses code
that might throw
an exception
ArithmeticExcepti
ons and
InputMistmatchEx
ceptions may
arise.
When an
exception
occurs in a try
block, the
catch block
that executes
is the first one
whose type
matches the
type of the
exception that
occurred
Use the
System.err
object to
output error
messages.