Object Oriented Programming
(ECE 3202)
Chapter – Three
Class and Object
1
What is an Object &Class?
Object is an instance of a class. Class is a template or
blueprint from which objects are created. So object is the
instance(result) of a class.
Class is a template that define the type/ skeleton of object
An object has three characteristics:
state: represents data (value) of an object.
behavior: represents the behavior (functionality) of an
object such as corse registration, drop-course etc.
identity: Object identity is typically implemented via a
unique ID. The value of the ID is not visible to the external
user. But, it is used internally by the JVM to identify each
object uniquely.
2
Example
Example
object state behavior
student Id,name,dept Reg,add,drop etc
grade book grades mean, median
light on/off switch
Cont..
Class in Java
A class is a group of objects which have common properties. It
is a template or blueprint from which objects are created. It is a
logical entity. It can't be physical.
A class in Java can contain:
fields
methods
constructors
blocks
nested class and interface
Syntax to declare a class:
class <class_name>{
field;
method;
}
4
Student Example
An Object's state is stored in variables called fields
Fields are declared (and optionally initialized) inside
the braces of the class
Class student
{string name;
int id;
Void set_val( String n, int i)
{ name=n;
id=I;
}
}//endof class
5
Example 2-light switch
Light switch example with a field . . .
class LightSwitch {
boolean state = true;
6
Methods
An Object's behavior is defined by its methods
Methods, like fields, are written inside the braces of
the class
Methods can access the fields (the state) of their
object and can change them
7
Example 1-student
class Student{
int id;//field or data member or instance variable
String name;
public static void main(String args[]){
Student s1=new Student();//creating an object of Student
System.out.println(s1.id);
System.out.println(s1.name);
}
}
8
Example 2- Main Outside Class
class Student{
int id;
String name;
}
Public class TestStudent1{
public static void main(String args[]){
Student s1=new Student();
System.out.println(s1.id);
System.out.println(s1.name);
}
}
9
Constructing/create Objects
We use the new keyword to construct a new
instance of an Object
We can assign this instance to a variable with the
same type of the Object
student st1=new student();
Note: classes define new datatypes !
LightSwitch ls = new LightSwitch();
10
There are 3 ways to initialize object in java.
By reference variable
By method
By constructor
11
Example -1 Initialization through reference
class Student{
int id;
String name;
}
class TestStudent2{
public static void main(String args[]){
Student s1=new Student();
s1.id=101;
s1.name=“hawi";
System.out.println(s1.id+" "+s1.name);
}
}
12
Example 2 Initialization through method
class Student{
int id;
String name;
void insertRecord(int r, String n){
id=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();
}
}
13
Constructors
Constructors are special methods used to construct
an instance of a class
They have no return type
They must have the same name as the class name
They initialize the state of the Object
Call the constructor by preceding it with the new
keyword
14
Example 3 Initialization through constructor
class Student{
int id;
String name;
public Student (int i, String n,) {
id=i;
name=n;
}
void display(){System.out.println(id+" "+name+" ");}
}
public class TestEmployee {
public static void main(String[] args) {
Student e1=new Student(120,”Belay”);
Student e2=new Student (111,”dita”);
Employee e3=new Employee(112,”habtu”);
e1.display();
e2.display();
e3.display(); }
}
15
Light Switch Example
class LightSwitch {
boolean state = true; // field
boolean isOn() { // returns
return state; // the state
}
void switch() { // changes
state = !state; // the state
}
} 16
Example Using Light Switch
What does this main method print out?
LightSwitch ls = new LightSwitch();
System.out.println(ls.isOn);
ls.switch();
System.out.println(ls.isOn());
True
False
18
Constructor Vs methods
19
student Example
class student {
String name ;
int id ;
void setinfo(String n ,int a)
{
name = n;
id=a;
}
String getName() { return name; }
int getAge() { return age; }
}
20
Constructing studentObjects
To create an instance of the student class with a name of
“abebe" and an age of 22
It is also possible to set values fields during the creation
of objects using constructor .
student abebe = new student();
abebe.setinfo(“Abebe“,22);
21
student Constructor
class student{
String name;
int id;
public student(String n, int a) {
name = n;
id = a;
}
. .
}
Student st1=new student(“abebe”,3223);
Student st2=new student(“kassa”,124);
22
Type of constructor
1. Default constructor
The type of constructor define with out parameters
2. Parameterized constructor
The type of constructor which has one or more parameters or
argument
23
Default Constructor
When you do not write a constructor in a class, it
implicitly has a constructor with no arguments and an
empty body
Default constructor provides the default values to the
object like 0, null etc. depending on the type.
Result:
classevery class has a constructor
LightSwitch {
// Leaving out the constructor
// is the same as . . .
LightSwitch() {}
}
24
Example
A class can have multiple constructors
class LightSwitch {
boolean state;
LightSwitch() {
state = true;
}
LightSwitch(boolean o) {
state = o;
}
Void dislight(){system.out.println(state)
}
LightSwitch l1=new LightSwitch(false)
LightSwitch l2=new LightSwitch()
L1. dislight();
L2. dislight() 25
Java parameterized constructor
A constructor that have parameters is known as parameterized
constructor.
Parameterized constructor is used to provide different values to
the distinct objects
class Student4{
int id;
String name;
Student4(int i,String n){
id = i;
name = n;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student4 s1 = new Student4(111,“dita");
Student4 s2 = new Student4(222,“fasil");
s1.display();
s2.display(); } }
26
This Keyword
Instance can refer to itself with the keyword
this
class LightSwitch {
boolean on;
LightSwitch() {
this.on = true; //(same as
on=true;)
}
LightSwitch(boolean on) {
this.on = on;
}
}
27
this keyword
this keyword Used to differentiate instance variables from the
parameter variable
It also used to cascading constructor
28
Cascading Constructors
A constructor can call another constructor with
this(arguments)
class LightSwitch {
boolean on;
LightSwitch() {
this(true);
}
LightSwitch(boolean on) {
this.on = on;
}
}
29
Apple Example
class Apple {
String color;
double price;
Apple(String color, double price) {
this.color = color;
this.price = price;
}
Apple(String Color) {
this(color, 300);
}
String getColor() { return color; }
double getPrice() { return price; }
void setPrice(double p) { price = p; }
}
30
Apple Example
What will these lines print out?
Apple a = new Apple("red", 100.0);
System.out.println(a.getColor()); red
System.out.println(a.getPrice()); 100.0
a.setPrice(50.5);
System.out.println(a.getPrice()); 50.5
Apple b = new Apple(“Yellow”);
System.out.println(b.getColor()); green
System.out.println(b.getPrice()); 74.6
b.setPrice(a.getPrice());
System.out.println(b.getPrice()); 50.5
31
Access specifier
Private : can only access variables/methods
c with in the class
Public: variables can be accessible every where
Default (friendly) : can access variables within the same package
Protected : the same as default but accessible by sub class in other package.
private-protected can accessible same package & subclass in the same or other
package
32
Getter and setter
If the fields become private we must use getter and setter
methods to get and set the values of the fields
Eg:
class Test
{ Private int x;
void setx(int x)
{ this.x=x;}
Void getx()
{ return x;}
}
Test T1=new Test();
T1.x=10; (Error b/c variable x is not directly access the variables)
T1.setx(x);
System.out.println(“X=“+T1.getx())
33
static keyword
The static keyword in java is used for memory management
mainly. We can apply java static keyword with variables,
methods, blocks and nested class. The static keyword belongs to
the class than instance of the class.
34
1. Java static variable
If you declare any variable as static, it is known static variable.
The static variable can be used to refer the common property of
all objects (that is not unique for each object)
e.g. company name of employees, college name of students etc.
Static variable : are used when we want to have common to all
instance of a class similar to global variable in C++
The static variable gets memory only once in class area at the
time of class loading.
Advantage of static variable
It makes your program memory efficient (i.e it saves memory).
Ex: how many objects are created from the given class etc
Static int count=0;
Exercise : modify the above student example and count
the number of objects created from the student class
35
2. Static methods
A static method belongs to the class rather than object of a
class.
A static method can be invoked without the need for creating an
instance of a class.
static method can access static data member and can change the
value of it.
Methods declared as static have several restrictions:
They can only call other static methods.
They must only access static data.
They cannot refer to this or super in any way.
36
Example-static method
class Student{
int id;
String name;
static String campus = “Lideta";
static void change(){
campus = “ 4 killo";
}
Student(int r, String n){
id = r;
name = n;
}
void display (){System.out.println(id+" "+name+" "+ campus);}
public static void main(String args[]){
Student s1 = new Student (111,“desta");
Student s2 = new Student (222,“Dita");
Student.change();
Student s3 = new Student (333,“beti");
s1.display();
s2.display();
s3.display();
}
}
37
Example 2 -static method
class UseStatic {
int y ;
static int a = 3;
static int b=2;
static void meth(int x) {
System.out.println(a*b*x));
}
class test{
public static void main(String args[]) {
UseStatic.meth(10);
}}
38
Java static block
Is used to initialize the static data member.
It is executed before main method at the time of classloading.
Example of static block
class A2{
static{System.out.println("static block is invoked");}
public static void main(String args[]){
System.out.println("Hello main");
}
}
Output: static block is invoked Hello main
39
Overloading Constructors
Similar to method or function over loading . It is also possible to define more than
one constructor in one class
class Box {
double width, height, depth;
// constructor used when all dimensions specified
Box(double w, double h, double d) {
width = w; height = h; depth = d;
}
// constructor used when no dimensions specified
Box() {
width = -1; height = -1; depth = -1;
}
// constructor used when cube is created
Box(double len) {
width = height = depth = len;
}
40
Cont…
// compute and return volume
double volume() {
return width * height * depth;
}
}
class OverloadCons {
public static void main(String args[]) {
// create boxes using the various constructors
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
// get volume of second box
vol = mybox2.volume(); output
System.out.println("Volume of mybox2 is " + vol);
// get volume of cube
vol = mycube.volume(); Volume of mybox1 is 3000
System.out.println("Volume of mycube is " + vol); Volume of mybox2 is -1
}} Volume of mycube is 345
41
Using Object as a parameter
// Objects are passed by reference.
class Test {
int a, b;
Test(int i, int j) {
a = i;
b = j;
}
// pass an object
void meth(Test o) {
o.a *= 2;
o.b /= 2;
} output
}
class CallByRef { ob.a and ob.b before call:15 20
public static void main(String args[]) { ob.a and ob.b after call: 30 10
Test ob = new Test(15, 20);
System.out.println("ob.a and ob.b before call: " + ob.a + " " + ob.b);
ob.meth(ob);
System.out.println("ob.a and ob.b after call: " + ob.a + " " + ob.b);
}}
42
Returning object
class Test {
int a;
Test(int i) {
a = i;
}
Test incrByTen() {
Test temp = new Test(a+10);
return temp;
}
}
class RetOb { output
public static void main(String args[]) {
Test ob1 = new Test(2); ob1.a : 2
Test ob2; ob2.a : 12
ob2 = ob1.incrByTen();
System.out.println("ob1.a: " + ob1.a);
ob2.a after second increase: 22
System.out.println("ob2.a: " + ob2.a);
ob2 = ob2.incrByTen();
System.out.println("ob2.a after second increase: “ + ob2.a);
}
}
43
Garbage collection
The Java Virtual Machine (JVM) performs automatic garbage
collection to reclaim the memory occupied by objects that are
no longer in use.
which is responsible for retrieving the memory of objects that
are no longer used so it can be used for other objects.
For more detail read Deitel & Deitel book
44
Anonymous object
Anonymous simply means nameless. An object which has no
reference is known as anonymous object. It can be used at the
time of object creation only.
If you have to use an object only once, anonymous object is a
good approach. For example: new Calculation();
//anonymous object Calling method through reference:
Calculation c=new Calculation();
c.fact(5);
Calling method through anonymous object
new Calculation().fact(5);
45
Example 1- anonymous object in java.
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
}
}
46
Wrapper class in Java
Wrapper class in java provides the mechanism to convert
primitive into object and object into primitive.
The eight classes of java.lang package are known as wrapper
classes in java. The list of eight wrapper classes are given
below
47
Wrapper class Example: Primitive to Wrapper
public class WrapperExample1{
public static void main(String args[]){
//Converting int into Integer
int a=20;
Integer i=Integer.valueOf(a);//converting int into Integer
Integer j=a;//autoboxing, now compiler will write Integer.valueOf(a) internally
System.out.println(a+" "+i+" "+j);
}}
48
Wrapper class Example: Wrapper to Primitive
public class WrapperExample2{
public static void main(String args[]){
//Converting Integer to int
Integer a=new Integer(3);
int i=a.intValue();//converting Integer to int
int j=a;//
unboxing, now compiler will write a.intValue() internally
System.out.println(a+" "+i+" "+j);
}}
49
Java Naming conventions
Java naming convention is a rule to follow as you decide what
to name your identifiers such as class, package, variable,
constant, method etc.
By using standard Java naming conventions, you make your
code easier to read for yourself and for other programmers.
Readability of Java program is very important. It indicates that
less time is spent to figure out what the code does.
50
Thank You!!!
Q?
51