You are on page 1of 37

Maharaja Agrasen Institute of

Technology
CIC-212
Java Programming
Lecture
Classes and Objects
Classes and Objects
A class consists of variables
called fields together with
functions called methods or
member functions that act on
those fields.
General Structure of a Class
Members of a class are:

• fields or variables
– a class or object's state or attributes
• methods
– a class or object's behaviour
• constructors
– to make objects
• each has access control
General Structure of a Class
Types of Members

• fields or variables
– instance unique values for each object
– class uses the static modifier
same value for all objects
• methods
– instance work with both instance
and static variables
– class uses static modifier
works with static variables
General Structure of a Class
Fields or Variables
 field or variable holds a single value
 is strongly typed: must be declared
 type specifies the kind of value and the variable's
behaviour
 int i = 123; // integer primitive
 Point pt = null; // object reference
 pt = new Point (x, y); // coordinates
pt has the value of the Point object's address, not
the x, y coordinates
Classes and Objects
A class is a collection of fields (data) and methods
(procedure or function) that operate on that data.

Circle

centre
radius

circumference()
area()
Classes and Objects
• 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
}
Classes and Objects
Adding Fields: Class Circle with fields

• Add fields

public class Circle {


public double x, y; // centre coordinate
public double r; // radius of the circle

• The fields (data) are also called the instance


variables.
Classes and Objects
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;
}
Classes and Objects
Adding Methods to Class Circle
public class Circle {

public double x, y; // centre of the circle


public double r; // radius of circle

//Methods to return circumference and area


public double circumference() {
return 2*3.14*r;
}
public double area() { Method Body

return 3.14 * r * r;
}
}
Classes and Objects
Data Abstraction
• Declare the Circle class, have created a new
data type – Data Abstraction

• Can define variables (objects) of that type:

Circle aCircle;
Circle bCircle;
Classes and Objects
Class of Circle cont.
• aCircle, bCircle simply refers to a Circle
object, not an object itself.

aCircle bCircle

null null

Points to nothing (Null Reference) Points to nothing (Null Reference)


Classes and Objects
Creating objects of a class
• Objects are created dynamically using the new
keyword.
• aCircle and bCircle refer to Circle objects

aCircle = new Circle() ; bCircle = new Circle() ;


Classes and Objects
Creating objects of a class
aCircle = new Circle();
bCircle = new Circle() ;

bCircle = aCircle;
Classes and Objects
Creating objects of a class
aCircle = new Circle();
bCircle = new Circle() ;

bCircle = aCircle;

Before Assignment Before Assignment

aCircle bCircle aCircle bCircle

P Q P Q
Classes and Objects
Automatic garbage collection
• The object
Q
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.
Classes and Objects
Accessing Object/Circle Data
• Similar to C syntax for accessing data defined
in a structure.
ObjectName.VariableName
ObjectName.MethodName(parameter-list)

Circle aCircle = new Circle();

aCircle.x = 2.0 // initialize center and radius


aCircle.y = 2.0
aCircle.r = 1.0
Classes and Objects
Executing Methods in Object/Circle
• Using Object Methods:
sent ‘message’ to aCircle

Circle aCircle = new Circle();

double area;
aCircle.r = 1.0;
area = aCircle.area();
Classes and Objects
Using Circle Class
// Circle.java: Contains both Circle class and its user class
//Add Circle class code here
class MyMain
{
public static void main(String args[])
{
Circle aCircle; // creating reference
aCircle = new Circle(); // creating object
aCircle.x = 10; // assigning value to data field
aCircle.y = 20;
aCircle.r = 5;
double area = aCircle.area(); // invoking method
double circumf = aCircle.circumference();
System.out.println("Radius="+aCircle.r+" Area="+area);
System.out.println("Radius="+aCircle.r+" Circumference ="+circumf);
}
}
[raj@mundroo]%: java MyMain
Radius=5.0 Area=78.5
Radius=5.0 Circumference =31.400000000000002
Constructors
• a special kind of method to construct an instance
of an object from a class template
• default constructor is ClassName()
– created if the class has no constructors
• instance fields are initialized to default values
automatically (see next slide)
• overloaded constructors: same name with
different parameter lists
• use of “this” to call another constructor
Constructors
Java automatically initializes class (static) and object
(instance) fields

Primitive Data Type Default Value


boolean false
int, etc. 0

Object Reference Type null


- not yet referring to an object
Constructors
Constructors
this keyword
Referencing the current object
To call another constructor
Constructors
Constructor initializes an object's instance fields
class MyClass {
int maximum;
int counter;
boolean isBelowMax = true; // override default

MyClass(int maximum) {
this.maximum = maximum;
}

MyClass() { this(100); } // calls this class's constructor

MyClass(int maximum, int counter) {


this.maximum = maximum; // assign local field value
this.counter = counter; // to this object's instance
isBelowMax = counter < maximum;
}
Method Overloading
• overloading is supported:
same method name, different parameter lists

• parameters passed by value, i.e. by copy


– primitive data types and object reference types
– copy of object reference is not a copy of the object

• type of primitive/object returned or void


Classes and Objects
Four Levels of Access to a Class or object's
members
private: accessible from within this class only
 should be standard practice on instance fields
to support OO encapsulation
default (if you don't specify):
accessible from any class in the package
protected: accessible from any subclass or any class in
the package
public: accessible from any class anywhere
Static keyword
When objects of its class are declared, no copy of a static
variable is made
 Instead, all instances of the class share the same static variable
When a member is declared static, it can be accessed before
any objects of its class are created, and without reference to any
object
The most common example of a static member is main().
 Outside of the class in which static methods are defined, static
methods and variables can be used independently of any object.
To do so, you need only specify the name of their class
followed by the .(dot) operator
ClassName.methodName()
Static keyword
Restrictions:

1. Static methods can only call other static methods.


2. They can only access static data.
3. They can not refer to ‘this’ or ‘super’ in any way.
Static Blocks
• Static block is a block of code prefixed by ‘static’ keyword
• Gets executed only once
• Used to initialize static variables
class A {
static int x;
static {
x = 10; static block
initializes
} x to 10

public static void main (String args[])


{
System.out.println (“ x value is : ”+ x);
}
Output : x value is : 10
}
Example Program : Static Block
class A {
static int x = 10;
static int y; Output
static void call( int p) { x value is : 10
System .out. println(“ x value is :”+x); y value is : 20
System .out .println(“ y value is :”+y); p value is : 30
System .out .println(“ p value is :”+p);
}
static {
System.out.println(“ static block initialized”);
y=x*2;
}
public static void main (String args[]) {
call(30);
}
}
Final keyword
A variable can be declared as final

Doing so prevents its contents from being modified

This means that you must initialize a final variable


when it is declared

Permits us to create typed constants

 In usage, final is similar to const in C / C++


Example final variables

Syntax
final type constName = value;

Example
final int FILE_NEW = 1;
final float PI = 3.141519;
Final Variables
Subsequent parts of the program may use the above
final variables FILE_NEW and PI

It is common coding convention to choose all uppercase


identifiers for final variables

Variables declared as final do not occupy memory on a


per-instance basis

Thus, a final variable is essentially a constant


Example program : final variables
Correct program Wrong program

class A { class B {
final int X = 10; final int X = 10;
public static void main (String args[]) public static void main(String args[]) {
{ X = 20;
System.out.println(“ X is “+X); System .out. println(“ X is “+X);
} }
} }

final variable
should not change
Other Uses Of final

The keyword final can also be applied to


methods,
Its meaning is substantially different than when it
is applied to variables
Varargs

 Newly implemented feature in Java 5.0


 Basic syntax
type … variableName
 Argument passed to a method is converted
into an array of the same-typed values
sum (10,20) sum(new int[] {10,20})
Varargs
Example
public static void main(String[] args)
{
System.out.println(“The sum is ” + sum(10,20,30));
}
public int sum (double … numbers)
{
int total = 0;
for (int i = 0; i < numbers.length; i++)
total += numbers[i];
return total;
} OUTPUT:
The sum is 60
Varargs
• Varargs is done with the … operator.

• Example. The following constructor


public Person (String name, String details… )

Can be called with many different invocations:

new Person (“Alexander ”);


new Person (“Alexander ”, “Bell ”);
new Person (“Alexander ”,”Graham”, “Bell ”);

You might also like