Chapter-3-Object and Class
Chapter-3-Object and Class
(ECE 3202)
Chapter – Three
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
2
Example
Example
Class student
{string name;
int id;
Void set_val( String n, int i)
{ name=n;
id=I;
}
}//endof class
5
Example 2-light switch
class LightSwitch {
6
Methods
7
Example 1-student
class Student{
int id;//field or data member or instance variable
String 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
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
14
Example 3 Initialization through constructor
class Student{
int id;
String name;
15
Light Switch Example
class LightSwitch {
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
21
student Constructor
class student{
String name;
int id;
. .
}
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
Result:
classevery class has a constructor
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
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
boolean on;
LightSwitch() {
this(true);
}
LightSwitch(boolean on) {
this.on = on;
}
}
29
Apple Example
class Apple {
String color;
double price;
30
Apple Example
31
Access specifier
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.
36
Example-static method
class Student{
int id;
String name;
static String campus = “Lideta";
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.
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…
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.
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
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
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