0% found this document useful (0 votes)
3 views

Lecture 2.2 - Class and Object

The document outlines the fundamental concepts of classes and objects in Java, including definitions, instance variables, methods, and constructors. It explains how classes serve as blueprints for objects, the process of instantiation, and the visibility of methods and variables. Additionally, it covers the initialization of objects and the use of constructors to set up object state upon creation.

Uploaded by

subsadult
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Lecture 2.2 - Class and Object

The document outlines the fundamental concepts of classes and objects in Java, including definitions, instance variables, methods, and constructors. It explains how classes serve as blueprints for objects, the process of instantiation, and the visibility of methods and variables. Additionally, it covers the initialization of objects and the use of constructors to set up object state upon creation.

Uploaded by

subsadult
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 23

Class And Object

Course Code: Course Title: Object Oriented Programming -


1(JAVA)

Dept. of Computer Science


Faculty of Science and Technology

Lecturer No: 2.2 Week No: 2 Semester: Summer 19-20


Lecturer: RIFATH MAHMUD
Lecture Outline

1. Class definition
2. Object definition
3. Defining a Class
4. Defining Instance Variables
5. Defining Instance Methods
6. Instance Methods Visibility
7. Instance Methods body
8. Returning value from a method
9. class as a type
10. Initializing object reference
11. Invoking instance method
12. Constructor
13. Converting a c++ code to java
Class and Object
Class definition

• Classes are templates or blueprints for Objects


• Data and methods are defined within Classes
• Classes must provide an implementation such that
objects created from those classes behave as those
defined in the Object model.
Class And Object
Definition of object

• An Object is the appearance of a class


• An object is an Instance of a class
• The process of creating an object is called
instantiation
• The attributes of an object are called instance
variables
• The methods of an object are called instance methods
• In Java, Objects are created using the new keyword:
Employee anEmployee = new Employee();
Defining a Class
• A class definition must have the following:
• The keyword "class" followed by the name of the class
• The class body

• Before the keyword "class" there is a optional modifier


"public"
• If a class is public, it must be defined within a file which is the same
name as the class with a ".java" extension.
• i.e. Classname.java
• eg. HelloWorld.java, Account.java, Ledger.java, Transaction.java
• Most classes are declared public

• The class body contains:


• Zero or more instance variables
• Zero or more methods
Defining Instance Variables
Instance variables are declared using the same syntax as
ordinary variables.
Variables can be prefixed with a visibility/access modifier

modifier type variable_name;

Variables can have one of 4 different visibilities:


public - the variable can be directly accessed from anywhere
private - the variable can only be directly accessed from within the
class
protected - the variable can be access directly from within the
class, within the package, or from within any subclass.
default (no modifier specified) - the variable can be accessed
directly from within the package
// We will discuss in details later.
Access Specifiers/modifiers
Defining Instance Methods
Method definitions include a method signature and a method body.

Methods signatures are defined with the following syntax:

modifier return_type method_name(type name, ...)

The return type can be:


a fundamental data type
an object reference
void (no return)
Parameters are optional
If the method takes no parameters, empty brackets are required ()
Multiple parameters are separated by commas
Parameters are defined by type and name
A parameter is a local variable whose scope is the method.
Defining Instance Methods Visibility
Methods have the same visibility modifiers as variables
public - the method can be invoked from anywhere
private - the method can only be invoked from within the class
protected - the method can be invoked directly from within the class, within the
package, or from within any subclass.
default (no modifier specified) - the method can be invoked directly from within
the package
// we will discuss in detail later.

If a method is part of the class's public interface (external view), the method
should be public

If a method is part of the class's internal implementation (ie, support method, etc),
it should be private.

Be careful using default or protected. Use only when justified.


Defining Instance Methods - Body
 A method's body contains all the statements to be executed as part of the method
The method body is contained within curly braces after the method definition:
Use {} placement and indentation to clearly show code structure

public class CalculationSheet


{
public void performCalculations()
{
//... method body ...
}

public void clearSheet()


{
}
//...Rest of the code...
}
Returning values from methods
A method which has a non-void return type MUST return a value
The return value's type must match the type defined in the method's
signature.
A void method can use a return statement (with no return value) to exit
the method.
The return value can be used the same as any other expression.

public class Car


{
private int currentGear;
private int currentRpms;

public int calculateSpeed()


{
return currentRpms * currentGear;
}
}
Classes as types
When a class is defined, the compiler view the class as a new type.

When a variable is declared, its type can be a primitive type or "Class"


type.
Any variable whose type is a class is an object reference.
The variable is a reference to an instance of the specified class.
The variables holds the address (in memory) of the object.

int x; Employee anEmployee;

Note: null means


0 null “refers to no
object”
null References
null means “refers to no object"

Object references can be compared to null to see if an object is


present or not.

null is the default value of an object reference before it is initialized

Employee anEmployee;

if (anEmployee == null){
//
}
Initializing Object References - new
To initialize an object reference, you must assign it the address of an object

The new operator creates a new instance and returns the address of the newly
created object
new allocates memory for the object
new also invokes a method on the object called a constructor
new returns the address of the memory allocated for the object.

Employee anEmployee;

anEmployee = new Employee();


Invoking Instance Methods
To invoke a method on an object, use the . (dot) operator

objectReference.methodName(parameters);

• If there is a return value, it can be used as an expression

Car aCar = new Car();

if ( aCar.calculateSpeed() > 110 )


{
System.out.println("You're Speeding!");
}
Passing Parameters to Methods
Method parameters are declared in the method's signature.

When a method invocation is made, any parameters included in the invocation are
passed to the method
All parameters are passed by value. i.e, a copy is made
The value of fundamental data types are copied
The value of object references (i.e, memory addresses) are copied

• Parameters become available within the method. They are not known outside the
method.

public float calculateInterestForMonth(float rate)


{
return lowBalanceForMonth * (rate/12.0);
}
Initializing Objects - Constructors
When an object is created, all instance variables are initialized to the default value
for their type
Fundamentals are 0, 0.0, '\000' or false
Object references are null

In order to put the object into a usable state, its instance variables should be
initialized to usable values
This could be accomplished by calling the various set methods
This is not always possible because it is not required that all instance variables have set
methods.

Java provides for another method of initializing objects

When an object is created, a constructor is invoked. The responsibility of the


constructor method is to initialize the object into a usable state.
Constructors

Constructors have the following characteristics


There is NO return type. NOT even void
The method name is the same name as the class name
Constructors can be overloaded
Constructors - Example
public class BankAccount
{
String ownersName;
int accountNumber;
float balance;

public BankAccount()
{
}
public BankAccount(int anAccountNumber)
{
accountNumber = anAccountNumber;
}

public BankAccount(int anAccountNumber, String aName)


{
accountNumber = anAccountNumber;
ownersName = aName;
}
}
Constructors - Example

When an object is created (using new) the compiler determines which


constructor is to be invoked by the parameters passed
Multiple constructors allows the class programmer to define many
different ways of creating an object.

public static void main(String[] args)


{
BankAccount anAccount = new BankAccount();
BankAccount anotherAccount = new BankAccount(12345);
BankAccount myAccount = new BankAccount(33423, "Craig");

}
Constructors

If no constructors are defined for a class, the compiler


automatically generates a default, no argument constructor
All instance variables are initialized to default values.

However, if any constructor is defined which takes


parameters, the compiler will NOT generate the default, no
argument constructor
If you still need one, you have to explicitly define one.
Books

1. Java Complete Reference, 7th Edition, By Herbert Schildt.

2. A Programmer's Guide to Java SE 8 Oracle Certified Associate, Khalid A. MughalRolf W.


Rasmussen

3. Java How to Program Java, 9th Edition, By Deitel and Deitel.

4. The Java Language Specification, By J. Gosling, B. Joy, G. Steele, G.Bracha and A.


Buckley

5. Introduction to Programming Using Java, 6th Edition, By David j. Eck

6. Head First Java, By Kathy Sierra and Bert Bates


References

1. 1. Java Complete Reference, 7th Edition, By Herbert Schildt.

2. A Programmer's Guide to Java SE 8 Oracle Certified Associate, Khalid A.


MughalRolf W. Rasmussen

2. The Java Tutorials. http://docs.oracle.com/javase/tutorial/

You might also like