2. Today’s Lecture
What is a class?
Class Composition
Components of Class
Fields
Methods
Main() Method, Setter Method, Getter Method, immutator.
Calling Method in same class Main method
Calling Method in other class.
Creating Objects from class
2
3. Class
What is a class?
Assume you want to model a traffic simulation. One kind of entity that you
have to deal with is cars.
What is a car in our context : Is it a class or object?
A few questions helps us to make decision
What color is a car? How fast it go? Where is it right now?
If I ask question about “My car parked in University Parking”
Now I am talking about Object and before it was a class.
3
4. Class
What is a class?
In OOP we create general sketch for each kind of object and then we create
different instances using this sketch we call this sketch a class.
All objects of same kind exhibit identical characteristics (information
structure and behavior) however they have data of their own.
A class is a blueprint from which individual objects are created.
A class is a concept
Class in OOP
In object-oriented programming, a class is an extensible program-code-
template for creating objects, providing initial values for state (member
variables) and implementations of behavior (member functions or
methods).
4
7. Class
Class Representation?
We can represent a class using rectangle as follows
7
(Class Name)
(attributes)
(operations)
(Class Name)
Normal Form
Suppressed Form
9. Class
Classes & Object
A Java program consists of one or more classes
A class is an abstract description of objects
Here is example of class
public class Dog {
Inner part of class will go here
} braces define the scope of class
Here are some objects of class
9
Reserved words
must be in lower
case
User defined name for
the class. conventionally
starts with upper letter
10. Class
Classes Header
The text of classes can be broken down into two parts: a small outer wrapping
that simply names the class and the inner part that does all the work
(previous slide).
the outer wrapping of different classes all look pretty much the same.
The outer wrapping contains the class header, whose main purpose is to
provide a name for the class.
Class Activity
Write out what you think the outer wrappers of the Student and LabClass
classes might look like; do not worry about the inner part.
10
11. Class
Components of a class?
A class has following three components
1. Fields
2. Constructor
3. Methods
Order is insignificant. We can write them in any order.
11
12. Class with blanks
public class Test
{
}
====================
public class Test()
{
int marks;
public setmarks(int i)
{
Marks=I;
}
}
12
13. 13
public class Welcome
{
public static void main(String[] args)
{
System.out.prinln("Welcome to GCU");
}
}
Writing First Program
14. Java Virtual Machine (JVM)
What is JVM
A Java virtual machine (JVM) is an abstract computing machine that enables
a computer to run a Java program.
Java is interpreter
14
15. Java Virtual Machine (JVM)
Compile Once Run every where. Platform Independent 15
26. Class
What is a Field?
Also known as attributes. Another name is instance variable or data
For each instance of the class (object), values of attributes can vary, hence
instance variable
Consider the Example Person Class
Attributes: name, address, phone
Consider the Objects of Person Class
Imran Object
Name is Imran, address is Lahore, phone is 111222333
Ali Object
Name is Ali, address is Karachi, phone is 111222333
As the value of name, address, and phone belongs to objects that’s why it is
also called instance variable.
This is what we also called as state of object
26
27. Class
Field Example
Classes describes the data (fields) held by each of its object
public class Dog {
private String name;
private int age;
rest of class
}
Usually fields are defined as private.
The word private and public will be explained in the coming lectures.
27
Data Types
Instance variable /
Field name
28. Class
What is a Constructor?
Constructor in java is a special type of method that is used to initialize the
object.
Java constructor is invoked at the time of object creation.
It constructs the values i.e. provides data for the object that is why it is
known as constructor.
The constructors are responsible for ensuring that an object is set up properly
when it is first created.
The construction process is also known as initialization.
If a constructor is not defined in the class, Java will create a default
constructor that will invoke automatically when object is create. 28
29. Class
What is a Constructor?
Constructor is called at the time of object creation.
Once object has been created, the constructor plays no further role in that
object life and can not be called on it.
One of the distinguished feature of constructor is that it has the same name as
the class in which they are defined.
In the constructor the fields are initialized with default values or external
information passed into object at the time of creation.
29
30. Class
Constructor Rules and Example
Constructor name must be same as class name.
Constructor must have no explicit return type.
public class Dog {
private String name;
private int age;
public Dog(){
name=NULL;
age=0;
}
rest of class
}
30
31. Class
Types of Constructor
There are two types of Constructor
1. Default Constructor (No arguments required)
A constructor that have no parameter (as in previous slide)
2. Parameterized Constructor
A constructor that have parameter. Example
public Dog(String dogname, int dogage){
name=dogname;
age=dogage;
}
Class Activity
Can you guess what types some of the Book class’s fields might be, from the
parameters in its constructor? Can you assume anything about the names of
its fields? 31
32. Class
Exercise
To what class the following constructor belong?
Public Student (String name)
Suppose that the class Pet has a field called name that is of type String. Write
an assignment statement in the body of the following constructor so that the
name field will be initialized with the value of the constructor’s parameter.
public Pet(String petsName){
}
Write the constructor header for the following constructor call.
Date(“September”,08,2015)
Try to give meaningful name to the parameters
32
33. Class
What is a Method?
Method defines the behaviour or basic functionality of the class.
Methods have two parts: a header and a body.
Methods belong to a class
– Defined inside the class
Heading
– Return type (e.g. int, float, void)
– Name (e.g. nextInt, println)
– Parameters (e.g. println(…) )
– More…
Body
– enclosed in braces {}.
– Declarations and/or statements.
33
34. Class
Method Examples
public class Dog {
private String name;
private int age;
public Dog(){
name=NULL;
age=0;
}
public setName(String dogName){
name=dogName;
}
public String getName(){
return name;
}
}
34
35. Program Structure
35
• A program consists of
one or more classes
• Typically, each class is
in a separate .java file
File File
File
File
Class
Variables
Constructors
Methods
Variables
Variables
Statements
Statements
Program
36. Class
Accessor & Mutator Methods
Accessor methods are those which returns information to the caller about the
state of the object; they provide access to information about the state of object
Accessor usually contains the return statement in order to pass back that
information.
getName()
Mutator method is one that change the state of an object.
The most basic form of object is one that takes a single parameter whose
value is used to directly overwrite what is stored in the object’s field.
setName()
36
39. Class & Objects
Creating Objects from Class
There are different ways to create an object of a class.
Using Non Parameterized or Default constructor
Dog fido=new Dog();
Using Parameterized Constructor
Dog fido=new Dog(“Fido”,5);
39
40. Writing & Running a Program
40
When you write a program, you are writing classes and all the things
that go into classes
Your program typically contains commands to create objects (that is,
“calls” to constructors)
– Analogy: A class is like a cookie cutter, objects are like cookies.
When you run a program, it creates objects, and those objects interact
with one another and do whatever they do to cause something to
happen
– Analogy: Writing a program is like writing the rules to a game;
running a program is like actually playing the game
You never know how well the rules are going to work until you try
them out
41. Writing & Running a Program
41
Getting Started
Question: Where do objects come from?
– Answer: They are created by other objects.
Question: Where does the first object come from?
– Answer: Programs have a special main method, not part of any object,
that is executed in order to get things started
public static void main(String[ ] args) {
Dog fido=new Dog(“Fido”,5); // creates a Dog
}
The special keyword static says that the main method belongs to the class
itself, not to objects of the class
– Hence, the main method can be “called” before any objects are created
– Usually, the main method gets things started by creating one or more
objects and telling them what to do
42. Writing & Running a Program
42
A Complete Program
class Dog {
String name;
int age;
Dog(String n, int age) {
name = n;
this.age = age;
}
void bark() {
System.out.println("Woof!");
}
void wakeTheNeighbors( ) {
int i = 50;
while (i > 0) {
bark( );
i = i – 1;
}
}
public static void main(String[ ] args) {
Dog fido = new Dog("Fido", 5);
fido.wakeTheNeighbors();
}
} // ends the class
43. Home Assignment/ Self Review Exericse
43
1. Write out a class Person. Write out a constructor that should take two
parameters.
The first is of type String and is called myName.
The second is of type int and is called myAge.
The first parameter should be used to set the value of a field called
name, and the second should set a field called age. You don’t have to
include the definitions for the fields, just the text of the constructor.
2. Write an accessor method called getName that returns the value of a field
called name, whose type is String.
3. Write a mutator method called setAge that takes a single parameter of type
int and sets the value of a field called age.
4. Write a method called printDetails for a class that has a field of type
String called name. The printDetails method should print out a string of
the form “The name of this person is”, followed by the value of the name
field. For instance, if the value of the name field is “Ali”, then printDetails
would print:
The name of this person is Ali
45. 45
Writing First Program
public class Welcome
{
public static void main(String[] args)
{
System.out.prinln("Welcome to GCU");
}
}
46. 46
Compiling and execution o your First Java Application
Save the program with java extenstion
Welcome.java
Class name and file name must be same
Compile the program with
Javac Welcome.java
Execute the program
Java Welcome
Java is case sensitive
Comment allowed in JAVA with
// or /* */
47. 47
Compiling and execution o your First Java Application
Open the command prompt window
Change the directory where the program is strored
To compile javac Welcome.java
Execute the program with java Welcome
Editor's Notes
No linking is done
. Class file contain byte codoe