Lecture 3a: Classes and Objects in Java
Lecture 3a: Classes and Objects in Java
Contents
Introduce to classes and objects in Java. Understand how some of the OO concepts learnt so far are supported in Java.
Introduction
Java is a true OO language : anything we wish to represent in Java must be encapsulated in a class that defines the state and behaviour of the basic program components known as objects.
Classes create objects and objects use methods to communicate between them. They provide a convenient method for packaging a group of logically related data items and functions that work on them.
3
Introduction Ctd.
A class essentially serves as a template for an object and behaves like a basic data type int. It is therefore important to understand how the fields and methods are defined in a class and how they are used to build a Java program that incorporates the basic OO concepts such as encapsulation, inheritance, and polymorphism.
Classes
A class is a collection of fields (data) and methods (procedure or function) that operate on that data.
Circle
centre radius
circumference() area()
Classes
A class is a collection of fields (data) and methods (procedure or function) that operate on that data. The basic syntax for a class definition:
class ClassName [extends SuperClassName] { [fields declaration] [methods declaration]
Bare bone class no fields, no methods public class Circle { // my circle class }
6
Add fields
public class Circle { public double x, y; // centre coordinate public double r; // radius of the circle }
Adding Methods
A class with only data fields has no life. Objects created by such a class cannot respond to any messages. Methods are declared inside the body of the class but immediately after the declaration of data fields. The general form of a method declaration is:
type MethodName (parameter-list) { Method-body; }
8
Data Abstraction
Declare the Circle class, have created a new data type Data Abstraction
null
null
Objects are created dynamically using the new keyword. aCircle and bCircle refer to Circle objects
aCircle = new Circle() ; bCircle = new Circle() ;
12
bCircle = aCircle;
13
Before Assignment
aCircle bCircle
14
Q The object does not have a reference and cannot be used in future.
The object becomes a candidate for automatic garbage collection. Java automatically collects garbage periodically and releases the memory used to be used in the future.
15
Circle aCircle = new Circle(); aCircle.x = 2.0 // initialize center and radius aCircle.y = 2.0 aCircle.r = 1.0
16
Circle aCircle = new Circle(); double area; aCircle.r = 1.0; area = aCircle.area();
17
Summary
Classes, objects, and methods are the basic components used in Java programming. We have discussed:
to to to to
define a class create objects add data fields and methods to classes access data fields and methods to classes
19