Chapter 3 - Final
Chapter 3 - Final
1
Introduction
In procedural programming, data and operations on the data are separate.
Object-oriented programming places data and the operation that pertain to them within a single
entity called an Object.
The object-oriented programming approach organizes in a way that mirrors the real world, in
which all objects are associated with both attributes and activities.
2
Cont’d …
Using objects improves software reusability and makes program easier to develop and easier to maintain.
Programming in java involves thinking in terms of objects; a Java program can be viewed as a collection of
cooperating objects.
An object represents an entity in the real world that can be distinctly identified.
For example, a student, a desk, a circle, a button, and even a loan can all be viewed as objects.
In a program, properties of an object are represented using variables which are also known as data (or data
members) and behaviors are represented using functions which are also known as member functions
A student object has properties like name, roll no, DOB, email etc.
A book object has properties like title, author name, pages price etc. Similarly a circle object has properties like
radius, coordinates of center etc.
3
Class Fundamentals
A class is a user defined data type which binds data and function into a single unit
Collection of similar objects which possesses common properties (also called attributes) and behavior(also
called operation) is known as class.
It is a template or blueprint from which objects are created Specifies both the data and the code that will
operate on that data.
Java uses a class specification to construct objects.
N.B Class is logical abstraction & method and member that constitute class is called member of a class.
Although there is no syntactic rule that enforces it, a well-designed class should define one and only one
logical entity.
4
Cont…
Although there is no syntactic rule that enforces it, a well-designed class should define one
and only one logical entity.
E.g a class that stores names and telephone numbers will not normally also store information
about the stock market, average rainfall, sunspot cycles, or other unrelated information
Putting unrelated information into the same class will quickly de structure your code!
Until now we have seen one method(main) Soon we will see how to create others. However,
notice that the general form of a class does not specify a main( ) method.
A main( ) method is required only if that class is the starting point for your program.
5
Defining a Class
To define a class we use the access modifier , keyword class followed by the
name of the class, followed by a pair of curl braces enclosing the details of
the definition.
6
Cont…
A class definition creates a new data type. In this case, the new data type is called Vehicle.
class declaration is only a type description; it does not create an actual object.
The general form of a statement that does that is this:
ClassName InstanceVariableName(ObjectName) = new ClassName();
Each time you create an instance of a class, you are creating an object that contains its own
copy of each instance variable defined by the class.
7
Cont…
After this statement executes, sinoTruck will be an instance of Vehicle. Thus, it will have “physical”
reality.
Each time we create an instance of a class(object), we are creating an object that contains its own copy
of each instance variable defined by the class.
Every Vehicle object will contain its own copies of the instance variables passengers, fuelcap, and
mpg.
8
Cont…
► Example
9
Introduction to classes and objects
Few examples of Classes. Examples of Objects
10
Java class and main class
Java class
Main class
Java class is a class with out main method Class Named Student_Test contains main method
11
Object
An Object can be defined as an instance of a class.
The state defines the object, and the behavior defines what the object does.
The state of an object consists of a set of data fields (also known as properties) with their current
values.
12
Cont’d …
If you create a software object that models our television.
The object would have variables describing the television's current state, such as
✓ Its status is on,
✓ the current channel setting is 8,
✓ the current volume setting is 23, and
✓ there is no input coming from the remote control.
The object would also have methods that describe the permissible actions, such as
✓ turn the television on or off,
✓ change the channel,
✓ change the volume, and
✓ accept input from the remote control.
13
Class and Instances
Objects of the same type are defined using a common class.
In other words, a class is a blueprint, template, or prototype that defines and describes the static
attributes and dynamic behaviors common to all objects of the same kind.
▪ Variables (or attribute, state, field): contains the static attributes of the class.
▪ Methods (or behaviour, function, operation): contains the dynamic behaviors of the class.
14
Cont’d …
The followings figure shows a few examples of classes:
15
Cont’d …
An instance is a realization of a particular item of a class. In other words, an instance is
an instantiation of a class.
All the instances of a class have similar properties, as described in the class definition.
For example, you can define a class called "Student" and create two instances of the class
"Student" for "Peter", and "Paul“.
As well those created instances such as Peter and Paul can use all the field member
variables.
The term "object" is often used loosely, which may refer to a class or an instance.
16
Cont’d …
The following figure shows two instances of the class Student.
The above class diagrams are drawn according to the UML (Unified Modeling Language) notations.
Class name is shown in bold and centralized. Instance name is shown as instanceName:Classname and
underlined.
17
Cont’d …
.
⚫ Each object within a class retains its own states and behaviors.
18
Cont’d …
The relationship between classes and object is analogous to the relationship between apple recipes and
apple pie.
A single class can be used to instantiate multiple objects. This means that we can have many active
objects or instances of a class.
A class usually represent a noun, such as a person, place or (possibly quite abstract) thing - it is a model
of a concept within a computer program.
A Java class uses variables to define data fields and methods to define behaviors.
19
Cont’d …
Concepts that can be represented by a class:
Tree
Building
Man
Car
Animal
Hotel
Student Computer Title Attributes
Author / Fields/
Book … PubDate Properties
ISBN
setTitle(…)
setAuthor (…)
setPubDate (…)
Methods/
setISBN (…)
Behavior
getTitle (…)
getAuthor (…)
…
20
How Objects Are Created
declares a variable called sinoTruck of the class type Vehicle but define an
object.
Second, the declaration creates a physical copy of the object and assigns to
sinoTruck a reference to that object.
new operator dynamically allocates (that is, allocates at run time) memory for an
object and returns a reference to it.
21
Methods
22
Con’t… Example
Naming method :While defining a method,
remember that the method name must be
a verb and start with a lowercase letter.
If the method name has more than two words,
the first name must be a verb followed by
adjective or noun.
In the multi-word method name, the first letter
of each word must be in uppercase except the
first word.
E.g sum(), area(), areaOfCircle(),
stringComparision()
23
Con’t ….
Predefined Method
Types of Method: There are two
types of methods in Java:
• Predefined Method
• User-defined Method.
In Java, predefined methods are the
method that is already defined in the Java
class libraries is known as predefined
methods. It is also known as the standard
library method or built-in method.
Some pre-defined methods are length(),
equals(), compareTo(), sqrt(), etc
24
Constructor and its type
Java constructors or constructors in Java is a terminology used to construct something in our programs.
The constructor is called when an object of a class is created. It can be used to set initial values for
object attributes.
At the time of calling the constructor, memory for the object is allocated in the memory. It is a special
type of method that is used to initialize the object.
Every time an object is created using the new() keyword, at least one constructor is called.
25
Constructor and its type
How Java Constructors are Different From Java
Methods? There are three types of constructors
Constructors must have the same name as the class 1. No argument constructor
within which it is defined it is not necessary for the 2. Parametrized constructor
method in Java.
3. Default constructors
Constructors do not return any type while method(s)
When the program is executed, the Java compiler
have the return type or void if does not return any
automatically constructs constructor without
value.
argument, if we don’t create one ourselves. The
Constructors are called only once at the time of Object
default constructor is the name given to this
creation while method(s) can be called any number of
times. constructor.
26
Examples for each constructure type
Parametrized constructor
Non Argument Constructor
27
Data fields
Data Fields are variables declared directly inside a class (not inside method or constructor of a class)
Data fields can be variables of primitive types or reference types.
Example public class Student {
String name;
int age;
boolean isSci;
char gender;
}
The default value of a data field is null for a reference type, 0 for a numeric type, false for a boolean
type, and '\u0000' for a char type.
Data fields can be initialized during their declaration.
However, the most common way to initialize data fields is inside constructors.
28
Cont’d …
Java assigns no default value to a local variable inside a method.
29
Types of Variables
Local variable: Created inside a method or block of statement
E.g. public int getSum(int a, int b)
{
int sum=0;
sum=a+b; This method has local variables such as a, b, sum.
return sum; Their scope is limited to the method.
}
} Each object has its own data for the instance variable O2
Instance
30 variable
Static and final variables
Static keyword Final Keyword
Objects of static class can’t be created. Its value, once declared, can’t be changed or re-initialized.
32
Cont’d …
We define class variables by including the static keyword before the variable itself.
String name;
int age;
... }
Instances of the class FamilyMember each have their own values for name and age.
But the class variable surname has only one value for all family members.
33
Static/Class methods
Class methods, like class variables, apply to the class as a whole and not to its instances.
Class methods are commonly used for general utility methods that may not operate directly on an
instance of that class, but fit with that class conceptually.
For example, the class method Math.max() takes two arguments and returns the larger of the two.
You don't need to create a new instance of Math; just call the method anywhere you need it, like this:
34
Cont’d …
Good practice in java is that, static methods should be invoked with using the class name though it
can be invoked using an object.
ClassName.methodName(arguments)
OR
objectName.methodName(arguments)
35
Cont’d …
Access Modifiers
▪ private
▪ protected
▪ no modifier (also sometimes referred as ‘package-
private’ or ‘default’ or ‘friendly’ access. )
▪ public
36
Cont’d …
1. Class level access modifiers (java classes only)
Only two access modifiers is allowed, public and no modifier
If a class is ‘public’, then it CAN be accessed from
ANYWHERE.
If a class has ‘no modifer’, then it CAN ONLY be accessed
from ’same package’.
37
Cont’d …
public access modifier
The class, data, or method is visible to any class in any package.
Fields, methods and constructors declared public (least
restrictive) within a public class are visible to any class in the
Java program, whether these classes are in the same package or
in another package.
private access modifier
The private (most restrictive) fields or methods can be
accessed only by the declaring class.
Fields, methods or constructors declared private are strictly
controlled, which means they cannot be accesses by anywhere
outside the enclosing class.
A standard design strategy is to make all fields private and
provide public getter and setter methods for them to read and
modify.
38
Cont’d …
protected access modifier
The protected fields or methods cannot be used for classes in
different package.
Fields, methods and constructors declared protected in a
superclass can be accessed only by subclasses in other
packages.
Classes in the same package can also access protected fields,
methods and constructors as well, even if they are not a
subclass of the protected member’s class.
No modifier (default access modifier)
Java provides a default specifier which is used when no
access modifier is present.
Any class, field, method or constructor that has no declared
access modifier is accessible only by classes in the same
package.
39
Cont’d …
For better understanding, member level access is formulated as a
table:
Same Other
Access Same Class Subclass
Package packages
Modifiers
public Y Y Y Y
protected Y Y Y N
no access
Y Y N N
modifier
private Y N N N
40
Continued…
Next
Method overloading
41