Upload
others
View
7
Download
0
Embed Size (px)
Citation preview
Introduction to Java
Classes
Lecture 3
15 March 2007 Java : Lecture 3 2
Object-oriented programming
• A computer-programming methodology that
focuses on data items rather than processes.
“The essence of the object-oriented
approach is the use of abstract data
types, polymorphism, and reuse through
inheritance ”
15 March 2007 Java : Lecture 3 3
Object-oriented programming
• Early languages had only arrays
– all elements had to be of the same type
• Then languages introduced structures (called records, or structs)
– allowed different data types to be grouped
• Then Abstract Data Types (ADTs) became popular
– grouped operations along with the data
“ Object-oriented programming languages give abstract data types the name class”
15 March 2007 Java : Lecture 3 4
So, what is a class?
• 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
– can be instantiated
• A class describes objects and operations
defined on those objects
15 March 2007 Java : Lecture 3 5
Method Signatures
• A method signature specifies:
– The name of the method.
– The type and name of each parameter.
– The type of the value (or object) returned by the method.
– The checked exceptions thrown by the method.
– Various method modifiers.
– modifiers type name ( parameter list ) [throws exceptions ]
public float convertCelsius (float tCelsius ) {}
public boolean setUserInfo ( int i, int j, String name ) throws
IndexOutOfBoundsException {}
15 March 2007 Java : Lecture 3 6
Methods
• A method is a named sequence of code that can be invoked by other Java code.
• A method takes some parameters, performs some computations and then optionally returns a value (or object).
• Methods can be used as part of an expression statement.
public float convertCelsius(float tempC) {
return( ((tempC * 9.0f) / 5.0f) + 32.0 );
}
15 March 2007 Java : Lecture 3 7
An example of a class
class Person {
String name;
int age;
void birthday ( )
{
age++;
System.out.println(name + "is now"+age);
}
}
Variable
Method
15 March 2007 Java : Lecture 3 8
Creating and using an object
• Person john;
john = new Person ( );
john.name = "John Smith";
john.age = 37;
• Person mary = new Person ( );
mary.name = "Mary Brown";
mary.age = 33;
mary.birthday ( );
15 March 2007 Java : Lecture 3 9
The three principles of OOP
• Encapsulation– Objects hide their functions
(methods) and data (instance variables)
• Inheritance– Each subclass inherits all
variables of its superclass
• Polymorphism– Interface same despite
different data types
car
auto-
maticmanual
Super class
Subclasses
draw() draw()
15 March 2007 Java : Lecture 3 10
Encapsulation
• Storing data and functions in a single unit
(class) is encapsulation. Data cannot be
accessible to the outside world and only
those functions which are stored in the class
can access it.
15 March 2007 Java : Lecture 3 11
Inheritance
• The process by which objects can acquire the
properties of objects of other class. In OOP,
inheritance provides reusability, like, adding
additional features to an existing class without
modifying it. This is achieved by deriving a new
class from the existing one. The new class will
have combined features of both the classes.
15 March 2007 Java : Lecture 3 12
Polymorphism
• The ability to take more than one form. An
operation may exhibit different behaviors in
different instances. The behavior depends
on the data types used in the operation.
Polymorphism is extensively used in
implementing Inheritance.
15 March 2007 Java : Lecture 3 13
Polymorphism
• A polymorphic reference can refer to different types of objects at different times– In java every reference can be polymorphic except of references to
base types and final classes.
• It is the type of the object being referenced, not the reference type, that determines which method is invoked– Polymorphic references are therefore resolved at run-time, not
during compilation; this is called dynamic binding
• Careful use of polymorphic references can lead to elegant, robust software designs
15 March 2007 Java : Lecture 3 14
Static and Dynamic Binding
• Static Binding
– Determining which method will be invoked to respond
to a message at compile time
• Dynamic Binding
– Determining which method will be invoked to respond
to a message at run time
– Required when method definitions are overridden in
subclasses, since type of the receiver class may not be
known until run time
15 March 2007 Java : Lecture 3 15
Access Specifiers
• Encapsulation : Concerns the hiding of data in a class and making this class available only through methods. In this way the chance of making accidental mistakes in changing values is minimized. Java allows you to control access to classes, methods, and fields via so-called access specifiers.
• Java offers four access specifiers, listed below in decreasing accessibility: – public
– protected
– default (no specifier)
– private
15 March 2007 Java : Lecture 3 16
Access Specifiers
The following table summarizes the access level
permitted by each specifier. .
no no no, unless it is a
subclassyes
Accessible to class
from different package?
no yes yes yes Accessible to class
from same package?
privatedefaultprotectedpublicSituation
15 March 2007 Java : Lecture 3 17
The final Modifier
The final modifier keyword makes that the programmer cannot change the value anymore. The actual meaning depends on whether it is applied to a class, a variable, or a method.
•final Classes
– A final class cannot have subclasses. An example:
public final class MathConstants { ... }
•final Variables
– A final variable cannot be changed once it is initialized. for example (define a numerical approximation of pi) :
public final static double PI = 3.141592654;
•final Methods
– A final method cannot be overridden by subclasses. It Disallows subclasses to change the meaning of the method for example :
public final static randomNumber() { ... }
15 March 2007 Java : Lecture 3 18
The static Modifier
A variable or method that is shared by all instances of a class is called a class variable or class method. You recognize such a variable in Java by the static keyword in the declaration.
•These exist independent of any object
•This means that a Class’s
– static methods can be called even if no objects of that class have been created and
– static data is “shared” by all instances (i.e., one value per class instead of one per instance)
15 March 2007 Java : Lecture 3 19
Constructors
• A constructor is a method that is fired
automatically by the new operator.
• Constructors can be picked out because they
have exactly the same name as the class,
and no return type.
• Constructors are used to initialize the object
to a reasonable state. You can pass in
parameters to do this, eg the tail number.
15 March 2007 Java : Lecture 3 20
Constructors
• What if you don’t write a constructor?
• It turns out that Java will create an implicit
no-args constructor for you. None of the
instance variables will be initialized, but
you can create a new object with just
ClassName().
• If any constructors are declared, this won’t
work. You’ll have to use one of the declared
constructors.
15 March 2007 Java : Lecture 3 21
Destructors
• Java doesn’t have them. Memory
management is taken care of automatically
by the garbage collector.
• You don’t have to worry about memory
leaks.
15 March 2007 Java : Lecture 3 22
Example : Class Helicopterpublic class Helicopter extends Object
{
protected int tailNumber;
public Helicopter()
{ tailNumber = 0;
}
public Helicopter(int newTailNumber)
{ tailNumber = newTailNumber;
}
public int getTailNumber()
{ return tailNumber;
}}
15 March 2007 Java : Lecture 3 23
Garbage Collection
• Something like the below would result in a
memory leak in C++, but not Java
Helicopter myHelo = new Helicopter(24);
Helicopter airForce1 = new Helicopter(42);
airForce1 = myHelo;
15 March 2007 Java : Lecture 3 24
Garbage Collection
• When memory runs low, or at certain times,
the Java runtime executes GC, finds
orphaned memory, and frees it for you.
• The process is usually very unobtrusive,
unless you’re doing time-critical realtime
OS work.
• This is a major win from a programmer
productivity standpoint. Memory errors are
very, very difficult to track down.
15 March 2007 Java : Lecture 3 25
finalize()
• The prior statement contained one small lie.
Java has a finalize() method that is called by
the garbage collector just prior to the
object’s being destroyed. You can use this
to release system resources other than
memory, such as open files, open network
connections, etc.
15 March 2007 Java : Lecture 3 26
An array is an object
• Person mary = new Person ( );
• int myArray[ ] = new int[5];
– or:
• int myArray[ ] = {1, 4, 9, 16,
25};
• String languages [ ] =
{"Prolog", "Java"};
15 March 2007 Java : Lecture 3 27
Arrays of Objects
• So far we have looked at an array of primitive types.
– integers
– could also use doubles, floats, characters…
• Often want to have an array of objects
– Students, Books, Loans ……
• Need to follow 3 steps.
15 March 2007 Java : Lecture 3 28
Declaring the Array1. Declare the array
private Student studentList[];
– this declares studentList
2 .Create the array
studentList = new Student[10];
– this sets up 10 spaces in memory that can hold references to Student objects
3. Create Student objects and add them to the array:
studentList[0] = new Student("Cathy", "Computing");
15 March 2007 Java : Lecture 3 29
Nested Classes
• In addition to a class containing data and methods,
it can also contain other classes
• A class declared within another class is called a
nested class
Outer Class
Nested
Class
15 March 2007 Java : Lecture 3 30
Nested Classes• A nested class has access to the variables and methods of
the outer class, even if they are declared private
• In certain situations this makes the implementation of the
classes easier because they can easily share information
• Furthermore, the nested class can be protected by the outer
class from external use
• This is a special relationship and should be used with care
15 March 2007 Java : Lecture 3 31
Nested Classes
• A nested class produces a separate bytecode file
• If a nested class called Inside is declared in an outer class
called Outside, two bytecode files will be produced:
Outside.class
Outside$Inside.class
• Nested classes can be declared as static, in which case they
cannot refer to instance variables or methods
• A nonstatic nested class is called an inner class
15 March 2007 Java : Lecture 3 32