You are on page 1of 7

Lab No.

9
Classes, Objects, and
Methods

Object Oriented Programming using JAVA Lab Manual – Page 18|193


Lab No. 9: Classes, Objects, and Methods
Objective:
• Understanding the concept of Object-Oriented programming.
• Introducing classes and objects and differences between them.
• Understanding class members and their properties.
• Calling methods.
Scope:
In JAVA, programmers concentrate on creating their own user defined classes and objects. Each class
contains data and data members and methods to facilitate the user how to kept data encapsulated manner
for the protection from the unauthorized access.

Example 1: This program demonstrates a simple class implementation.

class circle1{
Public static void main(String[] a){

Object Oriented Programming using JAVA Lab Manual – Page 19|193


} }

Example 2: This program demonstrates the private member of a class can’t be accessed from the outside
of the class which reports compile-time error..

Object Oriented Programming using JAVA


Example 3: The following example shows the difference between static and non-static variables.
.

Object Oriented Programming using JAVA


Example 4: The following example shows how to add two numbers using method calling.

Example 5: Method returns integer that contains the sum of two numbers.

Object Oriented Programming using JAVA


Example 6: Demonstration of methods with BufferedReader class

Exercises:
Exercise 1:
Write a class Book with three data members BookId, Pages and Price. It also contains the follow-
ing member function:
• The get() method is used to input values
• The show() method is used to display values

Object Oriented Programming using JAVA


• The set() method is used to set the values of data members using parameters
• The getPrice() method is used to return the value of price

Exercise 2:
Create a class building that has the public member floors,area, and occupants and a method
areaperperson()respectively that display the area per person for building. In the main() meth-
od create two instance of building called house and office and display the area per person by di-
vision of area/occupants.

Homework:
1) Write a class Result that contains roll no, name and marks of three subjects. The marks
are stored in an array of integers. The class also contains the following member functions.
• The input() method is used to input values
• The show() method is used to display values
• The total() returns the total marks a student
• The avg() method returns the average marks of a student
2) Create a class rectangle. The class has attributes length and width each of
which defaults to 1. It has member function that calculates the perimeter and the area of
the rectangle. It has set() and get() functions for both length and width.
The set() function should verify that length and width are each floating point
numbers larger than 0.0 and less than 20.0.

Object Oriented Programming using JAVA

You might also like