Title: We've been using predefined classes' Now we will learn to write our own classes to define new object
1Lecture 5
Writing Classes
- We've been using predefined classes. Now we will
learn to write our own classes to define new
objects - Lecture 5 focuses on
- class declarations
- method declarations
- method overloading
- method overriding
- constructors
- encapsulation
2Objects
- An object has
- state - descriptive characteristics
- behaviors - what it can do (or be done to it)
- For example, consider a coin that can be flipped
so that it's face shows either "heads" or "tails" - The state of the coin is its current face (heads
or tails) - The behavior of the coin is that it can be
flipped - Note that the behavior of the coin might change
its state
3Classes
- A class is a blueprint of an object
- It is the model or pattern from which objects are
created - For example, the String class is used to define
String objects - Each String object contains specific characters
(its state) - Each String object can perform services
(behaviors) such as toUpperCase
4Classes
- The String class was provided for us by the Java
standard class library - But we can also write our own classes that define
specific objects that we need - For example, suppose we wanted to write a program
that simulates the flipping of a coin - We could write a Coin class to represent a coin
object
5Classes
- A class contains data declarations and method
declarations
Data declarations
Method declarations
6Declaring Member Variables
- public class myClass extends Applet implements
ItemListener, ActionListener - public String myString
-
- myString is a member variable
- myString data type is String.
- "public" specifies the access level
7Instance Variables Vs Class variables
- Instance variable in a class is associated with
each object uniquely. - The class variable is associated with the class,
and is shared by all objects of the class.
8Data Scope
- The scope of data is the area in a program in
which that data can be used (referenced) - Data declared at the class level can be used by
all methods in that class - Data declared within a method can only be used in
that method - Data declared within a method is called local data
9Possible Components of Member variable
declaration.
- Access Level
- Indicates the access level for this member
- static
- Declares a class member
- final
- indicates that it is constant.
- transient
- This variable is transient
10Possible Components of Member variable
declaration.(Cont.)
- volatile
- This variable is volatile.
- type name
- The type and the name of the variable.
11Access Specifies
- private
- Only accessible from within the class (not merely
the instance). - protected
- Also accessible from subclasses and package
members. - package
- Accessible from package members. (Friends, not
family) - public
- No restrictions. Accessible from anywhere.
12Final variable
Class Fun extends Object public static final
int TYPE 1 public static final int TYPEB 2
private static int count 0 static void
addOne() count static final String
name Fun // more code here
13Final variable
- The final keyword means that the field cannot
be changed once initialized. - Note if word final is attached to a reference
variable, the associated object must be created
in the declaration statement.
14Classes with only static Members
- You can have a class that can have all static
members, do not have constructors, and thus can
not be used to create object. - Example
- Math class in the Java API.
- A better way to refer to a static variable is via
the class name. - Methods, as well as data can be declared static.
Static methods are not allowed to use the
non-static features of their class.
15Static (cont.)
- static members may be invoked before even a
single instance of the class is constructed. - Ex class AnyClass
- static int I 48
- int j 1
- public static void main(String args)
- I100
- j 5 //This will cause error
-
-
16Static (cont.)
- If a static method needs to access a non-static
variable or call a non-static method, it must
specify which instance of its class owns the
variable or execute the method. - Example on next page.
17Static (cont.)
- Import java.awt.
- public class MyFrame extends Frame
- MyFrame()
- sietSize(300, 350)
-
- public static void main(String args)
- MyFrame theFrame new MyFrame()
- theFrame.setVisible(true)
-
-
18Static Initializers
- It is legal for a class to have static code
block. - Example
- public class StaticDemo
- static int I 5
- public static void main(String args)
- System.out.println(main I I)
-
- static
- System.out.println(Static code I I)
-
19transient
- transient modifier applies only to variables.
- This keyword is used to indicate variables that
need not be saved when an object is saved using
the object serialization methods. - Example
- class WealthyCustomer extends Customer implements
Serializable - private float wealth
- private transient String accessCode
20volatile
- Only variables can be volatile.
- If you declare a variable volatile that means
that variable can be changed asynchronously, so
the compiler takes special precautions. - Volatile variables are of interest in
multiprocessor environments.
21Methods
Public object push(object item)
items.addElement (item) return item
22Methods (Cont.)
- Two major parts
- Method declaration
- Method body
- Methods are defined with method declaration.The
elements in - method declaration are access modifier,
additional modifiers, - return type, method name, parameter list, and
exceptions. - Declaration require method name, return type and
a pair of - parentheses. Rest of the things are optional and
appears if - programmer think necessary.
23Writing Methods
- A method declaration specifies the code that will
be executed when the method is invoked (or
called) - When a method is invoked, the flow of control
jumps to the method and executes its code - When complete, the flow returns to the place
where the method was called and continues - The invocation may or may not return a value,
depending on how the method was defined
24Method Control Flow
- The called method could be within the same class,
in which case only the method name is needed
25Method Control Flow
- The called method could be part of another class
or object
26The Coin Class
- In our Coin class we could define the following
data - face, an integer that represents the current face
- HEADS and TAILS, integer constants that represent
the two possible states - We might also define the following methods
- a Coin constructor, to set up the object
- a flip method, to flip the coin
- a getFace method, to return the current face
- a toString method, to return a string description
for printing
27The Coin Class
- See CountFlips.java
- See Coin.java
- Once the Coin class has been defined, we can use
it again in other programs as needed - Note that the CountFlips program did not use the
toString method - A program will not necessarily use every service
provided by an object
28Instance Data
- The face variable in the Coin class is called
instance data because each instance (object) of
the Coin class has its own - A class declares the type of the data, but it
does not reserve any memory space for it - Every time a Coin object is created, a new face
variable is created as well - The objects of a class share the method
definitions, but they have unique data space - That's the only way two objects can have
different states
29Instance Data
30Encapsulation
- You can take one of two views of an object
- internal - the structure of its data, the
algorithms used by its methods - external - the interaction of the object with
other objects in the program - From the external view, an object is an
encapsulated entity, providing a set of specific
services - These services define the interface to the object
31Encapsulation
- An object should be self-governing
- Any changes to the object's state (its variables)
should be accomplished by that object's methods - We should make it difficult, if not impossible,
for one object to "reach in" and alter another
object's state - The user, or client, of an object can request its
services, but it should not have to be aware of
how those services are accomplished
32Encapsulation
- An encapsulated object can be thought of as a
black box - Its inner workings are hidden to the client,
which only invokes the interface methods
Methods
Client
Data
33Method Declarations Revisited
- A method declaration begins with a method header
char calc (int num1, int num2, String message)
method name
parameter list
The parameter list specifies the type and name of
each parameter The name of a parameter in the
method declaration is called a formal argument
return type
34Method Declarations
- The method header is followed by the method body
char calc (int num1, int num2, String message)
int sum num1 num2 char result
message.charAt (sum) return result
sum and result are local data They are created
each time the method is called, and are destroyed
when it finishes executing
The return expression must be consistent with the
return type
35Writing Methods Cont.
36Access Level
- As with member variables, you control access to
methods by using public, protected, package, or
private. - Note if no access modifier is there then the
default is visibility within the package.
37Abstract
- The abstract modifier can be applied to calsses
and methods. - Abstrat methods declared without any
implementation. - EX.
- Abstract void travel ( )
- A super class provides only the method name and
signature. Any subclass must provide an
implementation of abstract method/methods. Or
declared itself abstract.
38Class hierarchy with abstraction
abstract class Animal
abstract void travel ( )
void ravel( )
void ravel( )
void ravel( )
class Bird
class Fish
class Snake
39When class must be abstract
- Class must be declared abstract if any of the
following occur. - The class has one or more abstract methods.
- The class inherits one or more abstract method
(from an abstract parent) for which it does not
provide implementations. - The class declares that it implements an
interface but does not provide implementations
for every method of that interface. - Remember abstract is opposite of the final.
40final
- A final method may not be overridden.
- EX.
- class Faculty
- final void facHabits ( )
-
- class CISFaculty extends Faculty
- void facHabits ( ) //error on this line
41native
- The native modifier can refer only to methods.
Like the abstract keyword, native indicates that
the body of a method is to be found elsewhere. - With native methods, the body lies entirely
outside the JVM, in a library. - Native code is written in non-Java language,
typically C or C. - Ex.
- Class NativeExample
- native void nativeLocal (int I)
- static
- System.loadLibrary (NativeLibrary)
-
42Native Cont.
- Callers do not have to know that the method is
native. Look at the following call. - NativeExample myNative
- myNative new NativeExample ( )
- myNative. nativeLocal (5)
43synchronized
- The synchronized modifier is used to contorl
access to critical code in multithreaded
programs. - ( We will discuss this in detail later.)
44Return type
- You declare a method's return type in its method
declaration. Within the body of the method, you
use the return operator to return the value. Any
method that is not declared void must contain a
return statement. The Stack class declares the
isEmpty method, which returns a boolean - public boolean isEmpty()
- if (items.size() 0)
- return true
- else
- return false
-
45Return type Cont.
- The data type of the return value must match the
method's return type. - When a method returns an object, the class of the
returned object must be either a subclass of or
the exact class of the return type. - Ex.
46Return type Cont.
- Now suppose you have a method declared to return
a Number - public Number returnANumber()
- . . .
-
- The returnANumber method can return an
ImaginaryNumber but not an Object
47Parameters
- Each time a method is called, the actual
arguments in the invocation are copied into the
formal arguments
ch obj.calc (25, count, "Hello")
48Writing Classes
- See BankAccounts.java
- See Account.java
- An aggregate object is an object that contains
references to other objects - An Account object is an aggregate object because
it contains a reference to a String object (that
holds the owner's name) - An aggregate object represents a has-a
relationship - A bank account has a name
49Writing Classes
- Sometimes an object has to interact with other
objects of the same type - For example, we might add two Rational number
objects together as follows - r3 r1.add(r2)
- One object (r1) is executing the method and
another (r2) is passed as a parameter - See RationalNumbers.java
- See Rational.java
50Overloading Methods
- Method overloading is the process of using the
same method name for multiple methods - The signature of each overloaded method must be
unique - The signature includes the number, type, and
order of the parameters - The compiler must be able to determine which
version of the method is being invoked by
analyzing the parameters - The return type of the method is not part of the
signature
51Overloading Methods
52Overloaded Methods
- The println method is overloaded
- println (String s)
- println (int i)
- println (double d)
- etc.
- The following lines invoke different versions of
the println method - System.out.println ("The total is")
- System.out.println (total)
53Method Overriding
- When a method in a derived class has the same
name and signature as a method in the parent
class, we say that the parent class method is
overridden. - Example
- class Rectangle
- int x, y, w, h
- public void setSize(int w, int h)
- this.w w
- this .h h
-
54Class DisplayedRectangle extends Rectangle
public void setSize(int w, int h) this.w
w this.h h redisplay( )
//implementation public void redisplay ( )
//..implementation not shown
55public class TestRectangle public static void
main (String args ) Rectangle recs
new Rectangle 4 recs0 new Rectangle ( )
recs1 new DisplayedRectangle ( )
recs2 new DisplayedRectangle ( ) recs3
new Rectangle ( ) for (int r 0 rlt4
r) int w ((int) (math.random( ) 400))
int h ((int))(Math.random( ) 200))
recsr.setSize(w, h)
56Method overriding cont.
- A method which has an identical name, and
identical number, types and order of arguments as
a method in a parent class is an overriding
method. - The return type must be identical.
- The accessibility must not be more restricted
than the original method. - Any exception declared must be of the same class
as that thrown by the parent class or of a
subclass of that exception. - Each parent class method may be overridden at
most once in any one subclass. - A static method may not be overridden to be
non-static.
57Can you override a Variable?
- Yes you can override a variable.
- A subclass can have a variable with same name as
a variable in the parent class.
58this and super
- Non-static methods have an implicit variable
named this, which is a reference to the object
executing the method. - In non-static code, you can refer to a variable
or method without specifying which objects
variable or method you mean. The compiler assumes
you mean this. - Class XYZ
- int w
- void bumpW( )
- w // this is actually (this.w )
-
-
59this and super
- With static methods, there is no this.
- When we need to refer to overridden variable or
method within the subclass we use keyword super - Ex
- super. myVariable
60Local variables
- Local variables are declared inside methods or
smaller block of code. - The storage of these variables does not exist in
an object. - Local variables are not initialized
automatically. You must provide a value before
you can use them. - The only modifier that can be applied to a local
variable is final.
61Constructors
- Constructors are the piece of code used to
initialize a new object. - All java classes must have at least one
constructor. (declared or default) - Constructor is not a method
- Constructor always have the name of the class and
no return type. - A class can have any no. of constructors provided
with different signature. - Constructors are not inherited, so each defined
class must specifically implement any
constructors it needs.
62Constructors cont.
- Modifiers abstract, static, final, native, or
synchronized can not be used with constructors. - Ex.
- public Rectangle (int x, int y, int width, int
height) - If I wanted to write a class, MyRect, extending
Rectangle, one possible constructor is as
follows - public MyRect(int w, int h)
- super(0,0,w,h)
- //other initialization code
63Constructors cont.
- In an invocation of the super constructor is used
it must be the first line of constructor code. - If the first line of the code body does not have
an invocation of the super constructor, the
compiler inserts super( ) , an invocation of
the default constructor that takes no parameters
belonging to the parent class.
64Default Constructors
- If no other constructor is declared in the class,
the compiler will create a default constructor
that takes no parameters and simply calls the
parent class constructor, which takes no
parameter. - Problem Ex.
- (next page)
65Class Base extends Object int type Base(int
n) type n class Xbase extends Base
String X // you should get error no
constructor matching Base( ) found in Base.
66Constructors cont.
- A constructor can invoke another constructor in
the class, but this must be done in the first
line of code in the constructor body.
67Overloading Constructors
- Constructors can be overloaded
- An overloaded constructor provides multiple ways
to set up a new object - See SnakeEyes.java
- See Die.java
68The StringTokenizer Class
- The next example makes use of the StringTokenizer
class, which is defined in the java.util package - A StringTokenizer object separates a string into
smaller substrings (tokens) - By default, the tokenizer separates the string at
white space - The StringTokenizer constructor takes the
original string to be separated as a parameter - Each call to the nextToken method returns the
next token in the string
69Method Decomposition
- A method should be relatively small, so that it
can be readily understood as a single entity - A potentially large method should be decomposed
into several smaller methods as needed for
clarity - Therefore, a service method of an object may call
one or more support methods to accomplish its
goal - See PigLatin.java
- See PigLatinTranslator.java
70Applet Methods
- In previous examples we've used the paint method
of the Applet class to draw on an applet - The Applet class has several methods that are
invoked automatically at certain points in an
applet's life - The init method, for instance, is executed only
once when the applet is initially loaded - The Applet class also contains other methods that
generally assist in applet processing
71Graphical Objects
- Any object we define by writing a class can have
graphical elements - The object must simply obtain a graphics context
(a Graphics object) in which to draw - An applet can pass its graphics context to
another object just as it can any other parameter - See LineUp.java
- See StickFigure.java