






Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
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
1 / 12
This page cannot be seen from the preview
Don't miss anything!







Programming - 2 BTE
Umair© 2006, All Rights Reserved - 1 - TA: Munawar Nadeem
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.
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.
The behavior is controlled by methods defined within the class (often called member methods ).
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.
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
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
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
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
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
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
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
The following example will illustrate how to write a class. We want to write a “Student” class that
// 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 both classes using javac commad. Run Test class using java command.
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
Write a class in Java that represents a Bank Account. A bank account contains the following information
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