Csc186topic 3 - Part1
Csc186topic 3 - Part1
3
INTRODUCTION TO CLASS
CLASS CONCEPT
A Java program is composed of one or more classes.
▪ A class is a template that describes the characteristics of a group
of objects of the same type.
▪ It is a description of a group of common objects.
▪ Some are predefined classes, others can be user/programmer
defined class.
▪ Example: Class - Bicycle
4
INTRODUCTION TO CLASS
WHY WE NEED A CLASS
bike1 bike2
ownerName - Adam Smith ownerName - Ben Jones
Class Name
This class must be defined Object Name
before this declaration can Object is declared here.
be stated.
Bicycle bike1,bike2;
1 Bicycle bike1;
2 bike1 = new Bicycle( );
Object Name
Method Name Argument
Name of the object to
The name of the message The argument we are
which we are sending a
we are sending. passing with the message.
message.
bike1.setName(“Adam Smith”);
Import Statements
Class Comment
Data Members
Methods
(incl. Constructor)
}
11
INTRODUCTION TO CLASS
THE DEFINITION OF THE BICYCLE CLASS
class Bicycle {
// Data Member
private String ownerName;
return ownerName;
}
ownerName = name;
}
} 12
INTRODUCTION TO CLASS
MULTIPLE INSTANCES
bike1 bike2
bike1.setOwnerName("Adam Smith");
bike2.setOwnerName("Ben Jones");
String owner1;
owner1=bike1.getOwnerName();
System.out.println("First owner:"+owner1);
System.out.println("Second
owner:"+bike2.getOwnerName());
}
} 14
INTRODUCTION TO CLASS
MEMBER ACCESS MODIFIER
private
Can only be accessed from within the class
they are declared in.
15
INTRODUCTION TO CLASS
MEMBER ACCESS MODIFIER (cont’)
protected
Can only be accessed from within the class
they are declared in and sub-classes. (used
with inheritance)
package / default
Can be accessed within the class and
package/folder
16
INTRODUCTION TO CLASS
MEMBER ACCESS MODIFIER (cont’)
Modifier Class Subclass Package World
private X
protected X X X
public X X X X
package/ X X
default
17
INTRODUCTION TO CLASS
DATA MEMBER DECLARATION
18
INTRODUCTION TO CLASS
MORE EXAMPLE(Let’s do it together)