Classes and Objects in Java
Classes and Objects in Java
Classes and Objects in Java
1
Some OOP concepts:
Encapsulation
Abstraction
Information Hiding
2
Encapsulation : Wrapping up of data and methods into a single
unit is Encapsulation. In a class we combine data (variables )
and method that are operated on that data. (e.g. Class)
Circle
centre
radius
circumference()
area()
5
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{
[fields declaration]
[methods declaration]
}
7
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:
}
9
}
Declare the Circle class, have created a new data type – User
Defined Data Type
Can define variables (objects) of that type:
10
Class of Circle cont.
aCircle, bCircle will have reference to Circle object, not an
object itself.
aCircle bCircle
null null
12
Creating objects of a class
aCircle = new Circle();
bCircle = new Circle() ;
bCircle = aCircle;
13
Creating objects of a class
aCircle = new Circle();
bCircle = new Circle() ;
bCircle = aCircle;
P Q P Q
14
Automatic garbage collection
Q
The object does not have a reference and cannot be
used in future.
15
Accessing Object/Circle Data
Similar to C syntax for accessing data defined in a structure.
ObjectName.VariableName
ObjectName.MethodName(parameter-list)
double area;
aCircle.r = 1.0;
area = aCircle.area();
17
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);
}
}
java MyMain
Radius=5.0 Area=78.5
18 Radius=5.0 Circumference =31.400000000000002
Packages
The classes of the Java standard class library are organized into
packages
Package Purpose
Or you can import the class, and then use just the class name
import java.util.Scanner;
import java.lang.*;