Sunteți pe pagina 1din 12

LECTURE NOTES AND LAB HANDOUTS

OBJECT OREINTED PROGRAMMING (ITEC / SENG – 321 ) WEEK. 5

CLASS AND OBJECT


In Java, classes are composed of data and operations—or functions—that operate on the data. Objects of a class
are created using the class as a template, or guide. Think of the class as a generic description, and an object as a
specific item of that class. The identifier of the object is called the object reference. Creating an object of a class is
called instantiating an object, and the object is called an instance of the class.
The data associated with an object of a class are called instance variables, or fields, and can be variables and
constants of any primitive data type (byte, short, int, long, float, double, char, and boolean), or they can be objects
of a class.
The operations for a class, called methods, set the values of the data, retrieve the current values of the data, and
perform other class-related functions on the data. Invoking a method on an object is called calling the method.
In a well-designed class, only the class methods can change the data. Methods of other classes cannot directly
access the data. We say that the data are private to the class.

DEFINING CLASS

To define a class, we use the following syntax:

accessmodifier class ClassName


{
//class definition
}
Class names are noun and starts with capital letter. Inside the curly braces we define the data of the class, called
its fields/data/variable and the methods both called as members of the class.

INSTANCE VARIABLES
Instance variable of a class hold the data for each object of that class. Instance variable are properties of the objects.
Each object will get its own copy of the instance variable each of which be given a value appropriate to that object.
Instance variable may be defined with private access modifiers so that only methods the class can set or change
the value of instance variables. In this way we achieve the encapsulation the class provides a protective shell
around the data. Data type of an instance variable can be any of java’s primitive data types or class types.

Instance variables are defined using the following syntax:

accessmodifier datatype identifierList;

PROGRAM 1: A program that uses the Box class. To run Program save this file “BoxDemo.java”

class Box {
double width;
double height;
double depth;
}

class BoxDemo {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;

Course Instructor: Nazish Basir Page: 1/12


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES AND LAB HANDOUTS
OBJECT OREINTED PROGRAMMING (ITEC / SENG – 321 ) WEEK. 5

// assign values to mybox1's instance variables


mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;

// assign different values to mybox2's instance variables


mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;

// compute volume of first box


vol = mybox1.width * mybox1.height * mybox1.depth;
System.out.println("Volume is " + vol);

// compute volume of second box


vol = mybox2.width * mybox2.height * mybox2.depth;
System.out.println("Volume is " + vol);
}
}

DECLARING OBJECTS
Instantiating an object consists of defining an object reference—which will hold the address of the object in
memory—and calling a special method of the class called a constructor, which has the same name as the class.
The job of the constructor is to assign initial values to the data of the class. Syntax for declaring an object
reference:
ClassName objectReference;
objectReference = new ClassName(argument list);

Example:
Box mybox;
Declares mybox as a reference to an object of type Box. After this line executes, mybox contains the value null

mybox = new Box();


When an object is instantiated, the JVM allocates memory to the new object. The object reference is assigned an
address that the JVM uses to find that object in memory.

ASSIGNING OBJECT REFERENCE VARIABLES


Object reference variables act differently than you might expect when an assignment takes place. For example:

Box b1 = new Box();


Box b2 = b1;

The assignment of b1 to b2 did not allocate any memory or copy any part of the original object. It simply makes b2 refer
to the same object as does b1.

Course Instructor: Nazish Basir Page: 2/12


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES AND LAB HANDOUTS
OBJECT OREINTED PROGRAMMING (ITEC / SENG – 321 ) WEEK. 5

METHODS
Methods provide a functions for the class, typically method names are verbs. Access modifier for methods that
provide services to the clients will be public. Methods that provide services only to other methods of the class are
typically declared to be private. Return type of a method is the data type of the value that the method returns to
the caller. All objects of the class shares one copy of the class methods. If function returns the value it must contain
return statement in its body.

Methods have this syntax:

accessmodifier returntype methodName( parameter list )


{
//Method Body
}

Methods that have a return type other than void return a value to the calling routine usingthe following form of
the return statement:
return value;

CALLING METHODS
Once an object is instantiated, we can use the object by calling its methods. To call a method for an object of a
class, we use dot notation, as follows:

objectReference.methodName(argument list);

If you attempt to call a method using an object reference whose value is null, Java generates either a compiler error
or a run-time error called NullPointerException.

PROGRAM 2: This program includes a method inside the box class. Save this file “BoxDemo2.java”

class Box {
double width;
double height;
double depth;

// compute and return volume


double volume() {
return width * height * depth;
}
}

class BoxDemo2 {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;

// assign values to mybox1's instance variables


mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;

Course Instructor: Nazish Basir Page: 3/12


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES AND LAB HANDOUTS
OBJECT OREINTED PROGRAMMING (ITEC / SENG – 321 ) WEEK. 5

// assign different values to mybox2's instance variables


mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;

// get volume of first box


vol = mybox1.volume();
System.out.println("Volume is " + vol);

// get volume of second box


System.out.println("Volume is " + mybox2.volume());
}
}

PROGRAM 3: This program uses a parameterized method. Save this file “BoxDemo3.java”

class Box {
double width;
double height;
double depth;

// compute and return volume


double volume() { return width * height * depth; }

// sets dimensions of box


void setDim(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
}

class BoxDemo5 {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;

// initialize each box


mybox1.setDim(10, 20, 15);
mybox2.setDim(3, 6, 9);

// get volumes
vol = mybox1.volume();
System.out.println("Volume is " + vol);
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}

Course Instructor: Nazish Basir Page: 4/12


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES AND LAB HANDOUTS
OBJECT OREINTED PROGRAMMING (ITEC / SENG – 321 ) WEEK. 5

CONSTRUCTOR
Constructor is s special method that is called when an object is instantiated using the new keyboard. A class can
have several constructors. The jobs of the constructor is to initialize the variables of the objects. Constructor has
the same name as the class and has no return type not even void. Important to use public access modifier for
constructor so that application can instantiate the objects of the class. Constructor can either assign default values
to the instance variable or the constructor can accept initial values from the client through parameters when the
object is created. If you don’t write constructor the compiler provides a default constructor which is a constructor
that takes no arguments. This default constructor assign default initial value to the variable like int variable is be
set with default value of 0, double and float with 0.0 boolean with false and char with space and object reference
with null

The syntax for a constructor follows:


accessmodifier className( parameter list )
{
//Constructor Body
}

PROGRAM 4: 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; }
}

class BoxDemo {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;

// get volumes
vol = mybox1.volume();
System.out.println("Volume is " + vol);
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}

Course Instructor: Nazish Basir Page: 5/12


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES AND LAB HANDOUTS
OBJECT OREINTED PROGRAMMING (ITEC / SENG – 321 ) WEEK. 5

PROGRAM 5: 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; }
}

class BoxDemo {
public static void main(String args[]) {

// declare, allocate, and initialize Box objects


Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box(3, 6, 9);

double vol;

// get volume of first box


vol = mybox1.volume();
System.out.println("Volume is " + vol);

// get volume of second box


vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}

THE THIS KEYWORD


The this keyword in java can be used inside the Method or constructor of Class. It works as a reference to the
current Object, whose Method or constructor is being invoked. This keyword can be used to refer to any member
of the current object from within an instance Method or a constructor.
For example, here is another version of Box( ), which uses width, height, and depth for parameter names and
then uses this to access the instance variables by the same name:

Box(double width, double height, double depth) {


this.width = width;
this.height = height;
this.depth = depth;

Course Instructor: Nazish Basir Page: 6/12


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES AND LAB HANDOUTS
OBJECT OREINTED PROGRAMMING (ITEC / SENG – 321 ) WEEK. 5

PROGRAM 6:

class SimpleDate {
int day;
int month;
int year;

public SimpleDate() {
day = 1;
month = 1;
year = 1990;
}

void setDay(int d) {
if(d <= 0) {
System.out.println("Day Cannot be set to Zero");
day = 1;
}
else day = d;
}

void setMonth(int m) {
if(m <= 0) {
System.out.println("Month Cannot be set to Zero");
month = 1;
}
else month = m;
}

void setYear(int y) {
if(y <= 0) {
System.out.println("Year Cannot be set to Zero");
year = 1;
}
else year = y;
}

int getDay() { return day; }

int getMonth() { return month; }

int getYear() { return year; }

String printDate() {
return day+"/"+month+"/"+year;
}

void nextDay() { day++; }

Course Instructor: Nazish Basir Page: 7/12


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES AND LAB HANDOUTS
OBJECT OREINTED PROGRAMMING (ITEC / SENG – 321 ) WEEK. 5

public class DateClient {


public static void main(String[] args) {
SimpleDate bday = new SimpleDate();
System.out.println(bday.printDate());
bday.setDay(10);
bday.setMonth(7);
bday.setYear(1982);
System.out.println(bday.printDate());
bday.nextDay();
System.out.println(bday.printDate());
}
}

MATH CLASS
The Math class is also part of the java.lang package. The Math class provides static constants PI and E (the base of
the natural logarithm, i.e., log e = 1)and static methods to perform common mathematical calculations, such as
finding the maximum or minimum of two numbers, rounding values, and raising a number to a power.

Course Instructor: Nazish Basir Page: 8/12


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES AND LAB HANDOUTS
OBJECT OREINTED PROGRAMMING (ITEC / SENG – 321 ) WEEK. 5

PROGRAM 7:
public class MathConstants
{
public static void main( String[] args )
{
System.out.println( "The value of e is " + Math.E );
System.out.println( "The value of pi is " + Math.PI );

double d1 = Math.abs( 6.7 ); // d1 will be assigned 6.7


System.out.println( "\nThe absolute value of 6.7 is " + d1 );

double d2 = Math.abs( -6.7 ); // d2 will be assigned 6.7


System.out.println( "\nThe absolute value of -6.7 is " + d2 );

double d3 = Math.log( 5 );
System.out.println( "\nThe log of 5 is " + d2 );

double d4 = Math.sqrt( 9 );
System.out.println( "\nThe square root of 9 is " + d4 );

double fourCubed = Math.pow( 4, 3 );


System.out.println( "\n4 to the power 3 is " + fourCubed );

double bigNumber = Math.pow( 43.5, 3.4 );


System.out.println( "\n43.5 to the power 3.4 is " + bigNumber );
}
}

Course Instructor: Nazish Basir Page: 9/12


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES AND LAB HANDOUTS
OBJECT OREINTED PROGRAMMING (ITEC / SENG – 321 ) WEEK. 5

THE STRING CLASS


The String class can be used to create objects consisting of a sequence of characters. String constructors accept
String literals, String objects, or no argument, which creates an empty String. The length method returns the
number of characters in the String object. The toUpperCase and toLowerCase methods return a String in upper or
lower case. The charAt method extracts a character from a String, while the substring method extracts a String
from a String. The indexOf method searches a String for a character or substring.

Course Instructor: Nazish Basir Page: 10/12


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES AND LAB HANDOUTS
OBJECT OREINTED PROGRAMMING (ITEC / SENG – 321 ) WEEK. 5

PROGRAM 8:

public class StringDemo {


public static void main ( String[] args ){

String s1 = new String( "OOP in Java " );


System.out.println( "s1 is: " + s1 );

String s2 = "is not that difficult. ";


System.out.println( "s2 is: " + s2 );

String s3 = s1 + s2; // new String is s1, followed by s2

System.out.println( "s1 + s2 returns: " + s3 );


System.out.println( "s1 is still: " + s1 ); // s1 is unchanged
System.out.println( "s2 is still: " + s2 ); // s2 is unchanged

String greeting1 = "Hi"; // instantiate greeting1


System.out.println( "\nThe length of " + greeting1 + " is "
+ greeting1.length( ) );

String greeting2 = new String( "Hello" ); // instantiate greeting2

int len = greeting2.length( ); // len will be assigned 5

System.out.println( "The length of " + greeting2 + " is " + len );

String empty = new String( );


System.out.println( "The length of the empty String is "
+ empty.length( ) );

String greeting2Upper = greeting2.toUpperCase( );


System.out.println( );
System.out.println( greeting2 + " converted to upper case is "
+ greeting2Upper );

String invertedName = "Lincoln, Abraham";


int comma = invertedName.indexOf( ',' ); // find the comma

System.out.println( "\nThe index of " + ',' + " in "


+ invertedName + " is " + comma );

// extract all characters up to comma


String lastName = invertedName.substring( 0, comma );
System.out.println( "Dear Mr. " + lastName );
}
}

Course Instructor: Nazish Basir Page: 11/12


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES AND LAB HANDOUTS
OBJECT OREINTED PROGRAMMING (ITEC / SENG – 321 ) WEEK. 5

EXERCISE 1:
Write a class encapsulating the concept of a course grade, assuming a course grade has the following
attributes:
 course name
 letter grade.
Include a constructor, and include the following methods:
 A method to take input in course name and grade (restrict user to give wrong values of grade correct
grade value will be: “A, B, C, D and F”)
 A method to display course name and grade.

Finally write a client class to test all the methods in your class.

EXERCISE 2:
Write a program that reads a commercial website URL from a dialog box; you should expect that the URL starts
with www.. and ends with .com. Retrieve the name of the site and output it. For instance, if the user inputs
www.yahoo.com, you should output yahoo.

EXERCISE 3:
Write a program that reads a cellphone number from a dialog box; you should assume that the number is in this
format: +nn-nnnn-nnnnnnn (country code, provider code and number). You should output this same cellphone
number but without dashes and joining the country code with cellphone number and skipping first 0, that is:
+nnnnnnnnnnnn
For Example: if user gives +92-0333-2731234 you program should display: +923332731234

Course Instructor: Nazish Basir Page: 12/12


Institute of Information and Communication Technology, University of Sindh.

S-ar putea să vă placă și