Chapter 2of 2

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 23

Classes and objects

1
Topics to be covered
• Contents;
§ Objects and Classes
§ Defining a class and objects
§ Instance variables, local variables and methods.
§ Access modifiers.
§ Exception handling.

2
Class and objects
• A class is a collection of object that have the same characteristics.
• A class is a template, blueprint that defines what an object’s, data fields and
methods will be.
• A class defines the properties and behaviors for objects.
• The behavior of an object (also known as its actions) is defined by methods.
• An object is an instance of a class. You can create many instances of a class.
Creating an instance is referred to as instantiation.

3
……..
• The following figure shows a class named Circle and its three objects.

4
……..
Instance variable and local variables
• Instance variable: is a variable declared or defined within the class.
• Local variable: is a variable that are defined within the methods and constructors
of the class.
class Employee{
Example. //This are instance variables
Int age;
String empname ;
//method definition
public void getName(String name)
{
//This is local variable
empname=name;
}
}

5
…......
• Assume we want to create A class called Student with three instance
variables(id, name, age) and with two methods.
public class Student
{ File name (Student.java)
String id;
String name;
int age;
public void setStudentInfo(String i, String n, int a)
{
id=i;
name=n;
age=a;
}
public void printInfo()
{
System.out.println(“ID:”+id);
System.out.println(“NAME:”+name);
System.out.println(“Age:”+age);
}}
6
……….
• The following sample program creates two Student objects, assigns the values of id,age & name
and displays the Student information:

public class TestStudent


{ File name: TestStudent.java
public static void main(String args[])
{
Student s1,s2;
s1=new Student();
s2=new Student();
//sets the student information
s1.setStudentInfo(“it01”, “Abebe”, 28);
s2.setStudentInfo(“it02”, “Kedir", 25);
//prints the first student information
s1.printInfo();
//prints the second student information
s2.printInfo();
}
}
7
…….
Note: Place all source files for a program in the same folder (directory).
• compile Student.java before compiling TestStudent.java
• An object’s data and methods can be accessed through the dot (.) operator via the object’s reference variable.

Java access Modifier


• determines access rights for the class and its members
• defines where the class and its members can be used.
• Default access modifier means we do not explicitly declare an access modifier.

8
Public VS Private
• Classes are usually declared to be public
• Methods that will be called by the client of the class are usually
declared to be public
• Methods that will be called only by other methods of the class are
usually declared to be private
• Private access modifier is the most restrictive access level.
• Classes and interface cannot be private.
• Private modifier is the main way that an object encapsulates itself
and hide data from the outside world.

9
Defining instance variables
Syntax:
accessModifier dataType identifier;
Example:
private string name;
public string id;

Defining methods
Syntax:
accessModifier returnType methodName( parameter list)
{
// method body
}
Example:
public string setName(string name)
{
//method body
}
10
To understand the effects of public and private, consider the following program:

// Public vs private access.


class MyClass {
private int pin; // private access
public String uname; // public access
int age; // default access
/* Methods to access pin. It is OK for a
member of a class to access a private member
of the same class.
*/
void setPin(int p) {
pin = p;
}
int getPin() {
return pin;
}
}

11
class AccessDemo {
public static void main(String args[]) {
MyClass ob = new MyClass();
/* Access to pin is allowed only through
its accessor methods. */
ob.setPin(111);
System.out.println("ob.pin is " + ob.getPin());
// You cannot access pin like this:
// ob.pin = 10; // Wrong! pin is private!
// These are OK because uname and age are public.
ob.uname = “meba”;
ob.age = 25;
}
}
Note
• Visibility modifiers can be used to specify the visibility of a class

12
Constructor
• A constructor initializes an object when it is created.
• Special methods that are called when an object is instantiated using the new
keyword.
• A class can have several constructors.
• Constructor does not have return type.
Syntax: public class name(parameter list)
{
//stmts;
}

13
Example:
/* Here, Box uses a constructor to initialize the dimensions of a box. */
class Box {
double width;
double height;
double depth;
// This is the constructor for Box.
Box()
{
System.out.println("Constructing Box");
width = 10;
height = 10;
depth = 10;
}
// compute and return volume
double volume()
{
return width * height * depth;
}
}

14
Continued……….
class BoxDemo
{
public static void main(String args[])
{
// declare, allocate, and initialize Box objects
Box mybox1 = new Box();
double vol;
// get volume of box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
}
}
When this program is run, it generates the following results:
Constructing Box
Volume is 1000.0

15
Constructor with parameter
/* Here, Box uses a parameterized constructor to initialize the dimensions of a box. */
class Box {
double width;
double height;
double depth;
// This is the constructor for Box.
Box(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}
// compute and return volume
double volume() {
return width * height * depth;
}
}

16
Continued….
class BoxTest {
public static void main(String args[])
{
// declare, allocate, and initialize Box objects
Box mybox1 = new Box(10, 20, 15);
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
}
}

Output

Volume is 3000.0

17
Exception handling
• An exception (or exceptional event) is a problem that arises during the execution o
f a program.
• When an Exception occurs the normal flow of the program is disrupted and
the program/Application terminates abnormally, which is not recommended, theref
ore these exceptions are to be handled.
• An exception can occur for many different reasons, below given are some scenario
s where exception occurs.
- A user has entered invalid data.
-A file that needs to be opened cannot be found.
- A network connection has been lost in the middle of communications
or the JVM has run out of memory.

18
Catching Exception
§ A method catches an exception using a combination of the try and catch keywords.
§ A try/catch block is placed around the code that might generate an exception.
§ Code within a try/catch block is referred to as protected code
§ the syntax for using try/catch looks like the following:
try {
//Protected code
}
catch(ExceptionName e1)
{
//Catch block
}
Example:
class Test {
public static void main(String args[])
{
int d, a;
try {
// monitor a block of code.
d = 0;
a = 42 / d;
System.out.println("This will not be printed."); 19
}
Continued…
catch (ArithmeticException e)
{
// catch divide-by-zero error
System.out.println("Division by zero is not allowed");
}
System.out.println("After catch statement.");
}
}
Output
Division by zero is not allowed.
After catch statement.

20
Example 2:
// File Name : ExcepTest.java
import java.io.*;
public class ExcepTest{
public static void main(String args[])
{
try{
int a[] = new int[2];
System.out.println("Access element three :" + a[3]);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Exception thrown :" + e);
}
System.out.println("Out of the block");
} }

Output
Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3
Out of the block

21
Finally block
§ The finally block follows a try block or a catch block.
§ A finally block of code always executes, irrespective of occurrence of an Exception.
§ Using a finally block allows you to run any clean up- type statements that you want to execute,
no matter what happens in the protected code.
§ A finally block appears at the end of the catch blocks and has the following syntax:
public class ExcepTest{
public static void main(String args[]) {
int a[] = new int[2];
try{
System.out.println("Access element three :" + a[3]);
} catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Exception thrown :" + e);
}
finally{
a[0] = 5;
System.out.println("First element value: " +a[0]);
System.out.println("The finally statement is executed");
} } }

22
23

You might also like