Classes and Instances Revision
Download
Report
Transcript Classes and Instances Revision
Classes and Instances
• Introduction
• Classes, Objects, Methods and Instance Variables
• Declaring a Class with a Method and Instantiating an
Object of a Class
• Declaring a Method with a Parameter
• Instance Variables, set Methods and get Methods
• Primitive Types vs. Reference Types
• Initializing Objects with Constructors
Class
• There are many objects of the same type, customers,
cars, bicycles…
• The same kinds of objects are grouped into classes
• A class defines the fields and the methods that each
object of that type will have
– a class is a blueprint or template
• E.g. Customer class defines all the fields and the
method implementations that each customer will have
Instances
• Each object of a particular type is an instance of the
class
– your bike is an instance of the class Bicycle
– Joe Bloggs is an instance of the class Customer
• All instance objects share the same blueprint i.e.
class
• Each instance object of a class is separate, and
individual
– each has the same structure and behaviour
– each has different actual values
• There are many instance objects for each class
Class vs Instance Objects
Class
Instance 1
Instance 4
Instance 2
Instance 3
All instances of the same class
Class vs Instance Objects
Student
Mary Black
Sean Smith
Niamh Connor
Eoin Murphy
All instances of the same class
Declaring a Class with a Method and
Instantiating an Object of a Class
• keyword public is an access modifier
• Class declarations include:
– Access modifier
– Keyword class
– Pair of left and right braces
classes are defined in the following
way:
class MyClass {
//field, constructor, and method declarations
}
Class Definition
class Student {
// fields
String name;
int studentNo;
String course;
//related to other Objects
// methods
void register(){
...
}
void completeYear(int year){
...
}
void graduate(){
...
}
}
Class Members
• There are two types of members of a class
– class members
– instance members
• Class members are associated with the class object
– exist once, a single copy
• Instance members are associated with each instance
object
– multiple copies of an instance member exists, one
copy in each instance object
• Note:
object members = object fields + object methods
Class vs Instance Members
Class: Student
Reg Fee: E600
changeFee(double)
Mary Black
0345678
FT211
register()
Sean Smith
completeYear(int)
05076543
Niamh Connor
graduate()
FT228register()
04565656
Eoin Murphy
completeYear(
FT211
05234567
register()
graduate()
FT228
completeYear(int)register()
graduate()
completeYear(int)
graduate()
Class
vs
Instance
members
class Student {
// instance fields
String name;
classint
members
studentNo;
declared
usingcourse;
String
keyword static
// class fields
static double regFee = 600;
// class methods
static void changeFee(double fee){
...
}
// instance methods
void register(){
...
}
}
Class members
• Class fields
– a class field has the same value for all
instances of the object
– a class field declared with a final modifier is a
constant
public static final double PI=3.14159;
• Class methods
– a class method cannot use any instance
members (fields or methods)
Declaring a Class with a Method and
Instantiating an Object of a Class
• Method declarations
– Keyword public indicates method is available
to public
– Keyword void indicates no return type
– Access modifier, return type, name of
method and parentheses comprise method
header
Creating Instance Objects
- new keyword
• Instance objects are created from the class
definition
• To create instance objects need a special
type of method called a constructor
• Instance objects are created using the
keyword new
• E.g.
Student me = new Student();
class type
instance object
variable name
constructor
Constructor
• The constructor
– has the same name as the class
(watch case sensitivity!)
– allocates enough space for an instance
object of the class specified
– does not specify a return type
– should initialise all instance fields
Constructor
class Student {
// fields
String name;
int studentNo;
String course;
// constructor
Student (String n, int s, String c){
name=n;
studentNo=s;
course=c;
}
// methods
...
}
Program Structure
• An OO program is a collection of objects
interacting with each other
• There are three types of classes
– business class – for objects which represent
persistent data in the system,
– interface class – for objects that represents an
interface (e.g. screen, file reader, etc…)
– control class – for objects that control the flow of
interaction
• All programs need a program control class that
starts the program running (i.e. has the main
method)
Example
• One technique is to
– instantiate the program control class in the main
method
– include the work of the program in the program
control class constructor
• Could include main work of program in main but
cannot access instance members…
Simple Program
Simple Program
class Classid{
// constructor
Classid(){
Data
and Control
}
// main method to start execution
public static void main (String[] args) {
new Classid();
// instantiating
}
}
The Java system calls the main method which instantiates the program via a new on the
constructor for Classid. Execution of the program proceeds from the constructor and
ends with the last statement in sequence has been reached.
Example:
Creating
Objects
program
control class
public class HelloWorld1{
// constructor
HelloWorld1(){
System.out.println(
"Hello World yet again...");
}
// main method to start execution
public static void main (String[] args) {
new HelloWorld1();
}
}
// instantiating
Another Example
•
// Class declaration with one method.
•
•
•
•
•
•
•
•
•
•
public class GradeBook
{
public GradeBook(){
System.out.println( "Welcome to the Grade Book!" );
}
// display a welcome message to the GradeBook user
public void displayMessage()
{
System.out.println( "Welcome to the Grade Book!" );
} // end method displayMessage
•
} // end class GradeBook
This is called from this class
•
// Create a GradeBook object and call its displayMessage method.
•
•
public class GradeBookTest
{
•
•
•
•
•
GradeBookTest()
{
// create a GradeBook object and assign it to myGradeBook
// call the constructor for the class GradeBook
GradeBook myGradeBook = new GradeBook();
•
•
•
// call myGradeBook's displayMessage method
myGradeBook.displayMessage();
} // end main
•
•
•
public static void main (String[] args) {
// Start the program running from its constructor
new GradeBookTest();}
•
} // end class GradeBookTest
Consider what is happening
• We are creating an instance of GradeBook
from this class GradeBookTest
• See the line
• GradeBook myGradeBook = new GradeBook();
• We then call on the line
• myGradeBook.displayMessage();
• This calls the displayMessage method from the
GradeBook class
Next Lecture
• How do we implement all this
Some Background Activities
Around Classes
• We discussed some classes and
programs that called them.
• For example we had the GradeBook and
Grade Book Test Classes
Another Example
• // Class declaration with one method.
• public class GradeBook
• {
•
// display a welcome message to the GradeBook user
•
public void displayMessage()
•
{
•
System.out.println( "Welcome to the Grade Book!" );
•
} // end method displayMessage
• } // end class GradeBook
This is called from this class
•
// Create a GradeBook object and call its displayMessage method.
•
•
public class GradeBookTest
{
•
•
•
•
•
GradeBookTest()
{
// create a GradeBook object and assign it to myGradeBook
// call the constructor for the class GradeBook
GradeBook myGradeBook = new GradeBook();
•
•
•
// call myGradeBook's displayMessage method
myGradeBook.displayMessage();
} // end main
•
•
•
public static void main (String[] args) {
// Start the program running from its constructor
new GradeBookTest();}
•
} // end class GradeBookTest
Consider what is happening
• We are creating an instance of GradeBook
from this class GradeBookTest
• See the line
• GradeBook myGradeBook = new GradeBook();
• We then call on the line
• myGradeBook.displayMessage();
• This calls the displayMessage method from the
GradeBook class
Next
• How do we implement all this
• We need to do this by linking all the classes
together.
• One way of doing this is with the
–
classpath qualifier at compilation time using the
javac command
• We have already seen this at run time with the
java command. But we can use the same idea at
compilation time
• This will tell the compiler where to find classes.
• See the following dialogue
Directory mnemonics
• In Dos the directory hierarchy uses some short
cuts
• \ refers to the root directory
• So if we type cd \
• We will be returned to the root directory
• The parent directory of any directory is indicated
by ..
• So if we were in C:\johns\java\progs and we
typed cd ..
• We will be returned to C:\johns\java
Directory mnemonics . notation
• The current directory is indicated by .
• So when we use . We are referring to the
current directory
• So javac –classpath . GradeBook will look
for classes in the current directory. So the
java classes used must be there.
Consider the following two Classes
• Book
• And Bookstore1 due to June Barrett
• Their Code is
Book.java
•
public class Book {
•
•
•
// Declare instance fields
String name;
int price;
•
•
•
•
•
// The constructor initialises the instance fields
Book (String n, int p) {
name = n;
price = p;
}
•
•
•
•
•
// a method to output the object details
void write() {
System.out.println(name + " for £" +price);
}
}
BookStore1.java
• public class BookStore1 {
•
•
/* Illustrating the basic structure of an object
oriented program */
// Declare three object variables representing
type of
•
// goods sold in the store
•
Book TextBook, Novel,ShortStory;
BookStore1.java continued
•
•
•
// The constructor for the program is
// where the initial work gets done
BookStore1 () {
•
•
•
•
// Create three objects with different initial values
TextBook = new Book("Java Programming", 6);
Novel = new Book("The Unsung Hero", 30);
ShortStory = new Book("Stories for 5 year olds", 80);
•
•
// Print out a header
System.out.println("The Book Store sells\n");
•
•
•
•
•
// Print the values contained in each of the objects
TextBook.write();
Novel.write();
ShortStory.write();
}
And Finally
•
•
•
•
•
•
// The program control class must have
a main method
public static void main (String[] args) {
// Start the program running from
its constructor
new BookStore1 ();
}
}
The Constructor BookStore1
• We see from the code that the constructor
BookStore1() make three instance of the
class Book, namely TextBook,Novel and
ShortStory
• It then calls on the Book write method to
display details about the book.
Next How do we compile these
• Firstly Book.java and BookStore1.java
must be in the same directory
From a Directory Listing
• We see that they are both in the c:\
directory
• Next we compile and run the classes using
the
• Javac and Java commands with
• –classpath .
From this screen we see
• That the class correctly executes the
specific objects.
Some Dos issues
• The javac command is in the jdk bin
subdirectory and I am fed up typing out
• C:\program files\java\jdk1.5.0_16\bin\javac
• Or whatever in order to use the command
Solution set a dos path
• set path=c:\program files\java\jdk1.5.0_16\bin
• This is the path on my computer for Java jdk version 5
• NBNBNB
You need whatever path there is to the bin directory in
java jdk where javac is stored ON YOUR
COMPUTER!!!!!
• Then the O/S will try this path when you invoke javac