Академический Документы
Профессиональный Документы
Культура Документы
1
Contents
2
Introduction
■ Java is a true OO language and therefore the
underlying structure of all Java programs is classes.
■ 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.
■ 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.
3
Classes
Circle
centre
radius
circumference()
area()
4
Classes
■ Add fields
public class Circle {
public double x, y; // centre coordinate
public double r; // radius of the circle
6
Adding Methods
7
Adding Methods to Class Circle
public class Circle {
}
}
8
Creating objects of a class
9
Creating objects of a class
aCircle = new Circle();
bCircle = new Circle() ;
bCircle = aCircle;
10
Creating objects of a class
aCircle = new Circle();
bCircle = new Circle() ;
bCircle = aCircle;
P Q P Q
11
Automatic garbage collection
Q
■ The object does not have a
reference and cannot be used in future.
13
Executing Methods in Object/Circle
double area;
aCircle.r = 1.0;
area = aCircle.area();
14
Using Circle Class
class Student{
int id;//field or data member or instance variable
String name;
15
class Student{
int id;
String name;
}
class TestStudent2{
public static void main(String args[]){
Student s1=new Student();
s1.id=101;
s1.name="Sonoo";
System.out.println(s1.id+" "+s1.name);//printing members
with a white space
}
}
16
class Student{
int rollno;
String name;
void insertRecord(int r, String n){
rollno=r;
name=n;
}
void displayInformation(){System.out.println(rollno+"
"+name);}
}
class TestStudent4{
public static void main(String args[]){
Student s1=new Student();
Student s2=new Student();
s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan");
s1.displayInformation();
s2.displayInformation();
}
}
17
class Calculation{
void fact(int n){
int fact=1;
for(int i=1;i<=n;i++){
fact=fact*i;
}
System.out.println("factorial is "+fact);
}
public static void main(String args[]){
new Calculation().fact(5);//calling method with anonymous
object
}
}
18
Summary
19