Object-Oriented Programming Handout 4.1 by Umair Javed, Exercises of Object Oriented Programming

This handout covers the basics of object-oriented programming (oop) including classes, objects, constructors, and access modifiers. It also includes examples and exercises for defining a student class.

Typology: Exercises

2011/2012

Uploaded on 07/13/2012

post_box
post_box 🇮🇳

4.7

(3)

113 documents

1 / 12

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Handout 4–1 Umair Javed
Programming - 2 BTE
Umair© 2006, All Rights Reserved - 1 - TA: Munawar Nadeem
Object Oriented Programming
OOP Vocabulary Review
Class
The class definition provides a template or blueprint, which describes the data (instance
variables) contained within, and the behavior (methods) common to all objects of a
certain kinds.
Data
The data is contained in variables defined within the class (often called instance
variables, data members, properties or attributes). The instance variables may be
primitives, such as int, float etc or they may be references to other objects. These can
only be accessible after instantiating an object.
Behavior
The behavior is controlled by methods defined within the class (often called member
methods).
Object
Object is the implementation of class. It is a software bundle of variables and methods.
Objects of same class will have its own and equal number of instance variables. Member
methods are invoked using objects.
In OOP terminology, objects are also called instance.
Classes vs. Objects
Remember, class is just a blueprint or an abstract concept or a definition. For example the
map of a building can be considered as a class. Objects on the other hand are the
implementation of class. The building itself can be considered as an object.
When you create a class you are describing how objects of that class look and how they
will behave. You don’t actually get anything until you create an object of that class and at
that point data storage is created and methods become available.
docsity.com
pf3
pf4
pf5
pf8
pf9
pfa

Partial preview of the text

Download Object-Oriented Programming Handout 4.1 by Umair Javed and more Exercises Object Oriented Programming in PDF only on Docsity!

Programming - 2 BTE

Umair© 2006, All Rights Reserved - 1 - TA: Munawar Nadeem

Object Oriented Programming

OOP Vocabulary Review

Class

The class definition provides a template or blueprint, which describes the data (instance variables) contained within, and the behavior (methods) common to all objects of a certain kinds.

Data

The data is contained in variables defined within the class (often called instance variables, data members , properties or attributes ). The instance variables may be primitives, such as int, float etc or they may be references to other objects. These can only be accessible after instantiating an object.

Behavior

The behavior is controlled by methods defined within the class (often called member methods ).

Object

Object is the implementation of class. It is a software bundle of variables and methods. Objects of same class will have its own and equal number of instance variables. Member methods are invoked using objects.

In OOP terminology, objects are also called instance.

Classes vs. Objects

Remember, class is just a blueprint or an abstract concept or a definition. For example the map of a building can be considered as a class. Objects on the other hand are the implementation of class. The building itself can be considered as an object.

When you create a class you are describing how objects of that class look and how they will behave. You don’t actually get anything until you create an object of that class and at that point data storage is created and methods become available.

Programming - 2 BTE

Umair© 2006, All Rights Reserved - 2 - TA: Munawar Nadeem

Constructor

Constructors are used to create objects from classes.

A constructor has the same name as the class with no return type. It is called when an object of the class is going to be created. The main purpose of writing constructor is initialization of instance variables

Unlike C++, Java does not provide any initialization list with constructor. You can initialize your variables inside the constructor. Example given at the end.

If you don’t provide constructor for class, the JVM will provide a default (zero argument) constructor and initialize the instance variables to default values as shown in the tables and object references to null.

Default values for primitive types

Primitives Default Valuea Boolean false Char ‘\uoooo’ (null) Byte (byte) Short (short) Int 0 Long 0 Float 0.0F Double 0.0d

Remember the same rule is not applied to local variables (variables declared inside any method), they must be initialized manually before they are used or otherwise compiler will indicate an error.

public void someMethod( ) { int x;

x++; // x is a local variable and must be explicitly initialized // so this statement produces compile time error }

Classes can have multiple constructors distinguished by different arguments (overloading) to meet requirements. The constructor that accepts parameters are often called parameterized constructor.

Programming - 2 BTE

Umair© 2006, All Rights Reserved - 4 - TA: Munawar Nadeem

Defining a Class

NAMING CONVENTIONS

While writing code in java, please use the following naming conventions. Remember it is not mandatory to follow these conventions but they are widely used across the world and its mandatory for you to use these conventions inside your course

o MyClass o myMethod o myVariable o MY_CONSTANT

Comparison with C++

The complete comparison between java and C++ made and discussed in detail in handout “Similarities and differences between C++ and Java”.

Some important points to consider when defining a class in java as you probably noticed from the above given skeleton are

  • There are no global variables or functions. Everything resides inside a class. Remember we wrote our main method inside a class. (For example, in HelloWorldApp program)
  • Specify access modifiers (public, private or protected ) for each member method or data members at every line.
  • There is no semicolon (;) at the end of class

inastance variables and symbolic constants

constructor – how to create and initialize objects

methods – how to manipulate those objects (may or may not include its own “driver”, i.e., main( ))

class Point {

private int xCord; private int yCord;

public Point (……) {……}

public void display (……) { ………. }

} //end of class

Programming - 2 BTE

Umair© 2006, All Rights Reserved - 5 - TA: Munawar Nadeem

  • All methods (functions) are written inline. There are no separate header and implementation files.

Access Modifiers

An access level determines whether other classes can use/access a particular instance variable or call a particular method. The Java programming language supports four access specifiers for instance variables and methods: private, protected, public, and, if left unspecified, package. The following table shows the access permitted by each specifier.

Access Levels

Specifier Class Package Subclass World Private (^) Y N N N Package Y Y N N Protected (^) Y Y Y N Public (^) Y Y Y Y

  • Private Only accessible within this class
  • Package Default access if no access modifier is provided. A method of variable with package access is accessible to all classes of the same package. We will discuss packages in more detail in the later handouts. For now you can think of a package as a directory.
  • Protected Generally, used for inheritance. Accessible only to the class itself and to its subclasses
  • public Accessible anywhere by anyone

Getters / Setters

As the access modifier used for instance variable is mostly private or protected, It is usual for a class to provide getter (accessors) & setters (mutators) methods for these instance variable with public access modifier.

Programming - 2 BTE

Umair© 2006, All Rights Reserved - 7 - TA: Munawar Nadeem

Task – Defining a Student class

The following example will illustrate how to write a class. We want to write a “Student” class that

  • should be able to store the following characteristics of student
    • Roll No
    • Name
  • Provide default, parameterized and copy constructors
    • Provide standard getters/setters for instance variables
      • Make sure, roll no has never assigned a negative value i.e. ensuring the correct state of the object
      • Provide print method capable of printing student object on console

Student Class Code

// File Student.java

/* Demonstrates the most basic features of a class. A student is defined by their name and rollNo. There are standard getter/setters for name and rollNo.

NOTE A well documented class should include an introductory comment like this. Don't get into all the details – just introduce the landscape. */

public class Student {

private String name; private int rollNo;

// Standard Setters public void setName (String name) { this.name = name; }

// Note the masking of class level variable rollNo public void setRollNo (int rollNo) { if (rollNo > 0) { this.rollNo = rollNo; }else { this.rollNo = 100; } }

// Standard Getters public String getName ( ) {

Programming - 2 BTE

Umair© 2006, All Rights Reserved - 8 - TA: Munawar Nadeem

return name; }

public int getRollNo ( ) { return rollNo; } // Default Constructor public Student() { name = “not set”; rollNo = 100; }

// parameterized Constructor for a new student public Student(String name, int rollNo) { setName(name); //call to setter of name setRollNo(rollNo); //call to setter of rollNo }

// Copy Constructor for a new student public Student(Student s) { name = s.name; rollNo = s.rollNo; }

// method used to display method on console

public void print () { System.out.print("Student name: " +name); System.out.println(", roll no: " +rollNo); }

} // end of class

Programming - 2 BTE

Umair© 2006, All Rights Reserved - 10 - TA: Munawar Nadeem

/*NOTE: public vs. private A statement like "b.rollNo = 10;" will not compile in a client of the Student class when rollNo is declared protected or private */

} //end of main } //end of class

Compile & Execute

Compile both classes using javac commad. Run Test class using java command.

Points to Remember Revisited

ƒ Recompile the class after making any changes ƒ Save your program before compilation ƒ Only run a class using java command that contains the main method because program executions always starts form main

Programming - 2 BTE

Umair© 2006, All Rights Reserved - 11 - TA: Munawar Nadeem

Exercise

Write a class in Java that represents a Bank Account. A bank account contains the following information

  • Name of Account (String)
  • ID of Account (String)
  • Balance (double)
  • Type of Account , Saving or Current (String)

Provide appropriate constructors and getter / setter methods for each of the attributes. Also define a test class. Create objects of the Account class inside the test class and use it