0% found this document useful (0 votes)
52 views19 pages

Module 2 - Notes - Chpter 6 & 7 - Introducing Classes, Methods and Classes

This document provides an overview of object-oriented programming concepts in Java, including classes, objects, methods, constructors, and more. It begins by defining a class as a template that describes common properties and behaviors of objects. It then discusses class fundamentals like declaring objects and assigning references. The document also covers method introduction and overloading, constructors, the this keyword, and garbage collection. Examples are provided to demonstrate general class structure, parameterized constructors, and overloading methods.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
52 views19 pages

Module 2 - Notes - Chpter 6 & 7 - Introducing Classes, Methods and Classes

This document provides an overview of object-oriented programming concepts in Java, including classes, objects, methods, constructors, and more. It begins by defining a class as a template that describes common properties and behaviors of objects. It then discusses class fundamentals like declaring objects and assigning references. The document also covers method introduction and overloading, constructors, the this keyword, and garbage collection. Examples are provided to demonstrate general class structure, parameterized constructors, and overloading methods.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 19

Module 2- Object Oriented Programming with JAVA (BCS306A)

CHAPTER 6: Introducing Classes


Introducing Classes: Class Fundamentals, Declaring Objects, Assigning Object Reference Variables, Introducing
Methods, Constructors, The this Keyword, Garbage Collection.

Class Fundamentals

A class in Java is a logical template to create objects that share common properties and methods. Hence,
all objects in a given class will have the same methods or properties.

In object-oriented programming, a class is a basic building block. It can be defined as template that
describes the data and behaviour associated with the data. A class template is used to create an object
(variable) of that class. Object can be used to access the member variables and methods of the class.

For example, an Employee class may contain all the employee details in the form of variables and methods.
If the class is instantiated i.e. if an object of the class is created, we can access all the methods or properties
of the class.

The General Form of a Class

Q Construct a Java program that demonstrates the general structure of a class, providing a brief
explanation of each component.

Java provides a reserved keyword class to define a class. The keyword must be followed by the class name.
Inside the class, we declare methods and variables.
In general, class declaration includes the following in the order as it appears:
1. Modifiers: A class can be public or has default access.
2. class keyword: The class keyword is used to create a class.
3. Class name: The name must begin with an initial letter (capitalized by convention).

The data, or variables, defined within a class are called instance variables. The code is contained within
methods. Collectively, the methods and variables defined within a class are called members of the class.
In most classes, the instance variables are acted upon and accessed by the methods defined for that class.
Thus, as a general rule, it is the methods that determine how a class’ data can be used. Variables defined
within a class are called instance variables because each instance of the class (that is, each object of the
class) contains its own copy of these variables. Thus, the data for one object is separate and unique from
the data for another.

Dept. of AIML, GMIT, Davangere


Module 2- Object Oriented Programming with JAVA (BCS306A)

A Sample Class definition with instance variables and member functions.

Dept. of AIML, GMIT, Davangere


Module 2- Object Oriented Programming with JAVA (BCS306A)

Output:

In the above class definition,


Instance variables are:

Methods are,

read() method reads the value for instance variables base and height through the keyboard, and Area_cal()
method computes the area of a Traingle.
one object are created t1 of class type Traingle, using the default constructor Traingle():

The new operator dynamically allocates memory for an object. It has this general form:

Here, class-var is a variable of the class type being created. The classname is the name of the class that is
being instantiated. The class name followed by parentheses specifies the constructor for the class.
Constructors
Java constructors or constructors in Java is a terminology used to construct something in our programs. A
constructor in Java is a special method that is used to initialize objects. The constructor is called when an
object of a class is created. It can be used to set initial values for object attributes.
In Java, a Constructor is a block of codes similar to the method. It is called when an instance of the class
is created. At the time of calling the constructor, memory for the object is allocated in the memory. It is a

Dept. of AIML, GMIT, Davangere


Module 2- Object Oriented Programming with JAVA (BCS306A)

special type of method that is used to initialize the object. Every time an object is created using the new()
keyword, at least one constructor is called.

Adding a Method That Takes Parameters and returning a value.


Q. Create a simple Java program that uses methods with parameters and briefly explain how it
works?
Information can be passed to methods as parameter. Parameters act as variables inside the method.
Parameters are specified after the method name, inside the parentheses. User can add as many parameters
as they want, Parameters are separated by a comma.
Following sample program gives the definition of a class Square, with method int read(int n).
 Instance variable is num.
 Method is int read(int n) – this method takes integer parameter n and returns integer, i.e. a square
of a number.

Output:

Parameterized Constructors
Q. Create a simple Java program that uses constructor with parameters and briefly explain how it
works?
Parameterized constructors in Java are used to initialization the instance variables. The parameterized
constructors require one or more arguments to be passed during the initialization of an object.
Java class creates a default constructor if the programmer hasn't defined any type of constructor in the
class. The parameterized constructor has to be defined explicitly by the programmer. The main aim to

Dept. of AIML, GMIT, Davangere


Module 2- Object Oriented Programming with JAVA (BCS306A)

create parameterized constructor is to initialize the objects with programmer-defined values for instance
variables. The values of members can be assigned during the process of initializing the object with the help
of parameterized constructors.

Output:

In the above program, Traingle(int b, int h) is parameterized constructor, which takes two parameters b
and h are used to initialize the instance variables base and height. And method Area_cal() calculates the
area of a triangle.

The this Keyword


Q. Explain this keyword in java
The this keyword refers to the current object in a method or constructor. The most common use of
the this keyword is to eliminate the confusion between class attributes (instance variables) and parameters
with the same name.
If a local variables have the same name as an instance variables, the local variables hide the instance
variables. In this situation this keyword is used eliminate the confusion between class attributes and
parameters with the same name.

Dept. of AIML, GMIT, Davangere


Module 2- Object Oriented Programming with JAVA (BCS306A)

Output:

In the above program, parameterized constructor is Traingle(int base, int height). Here the names of the
parameters are same as names of instance variables base and height, here this keyword is used to eliminate
the confusion between class attributes (instance variables) and parameters with the same name.

Garbage Collection
Q. Explain garbage collection in java
 In C and C++ garbage collection is handled manually.
 In Java Garbage collection is the automated process of deleting object that’s no longer needed or
used. This automatically frees up memory space.
 During the garbage collection process, the collector scans different parts of the heap, looking for
objects that are no longer in use. If an object no longer has any references to it from elsewhere in
the application, the garbage collector removes the object, freeing up memory in the heap. This
process continues until all unused objects are successfully reclaimed.

Dept. of AIML, GMIT, Davangere


Module 2- Object Oriented Programming with JAVA (BCS306A)

CHAPTER 7: Methods and Classes


Methods and Classes: Overloading Methods, Objects as Parameters, Argument Passing, Returning
Overloading Methods
Objects, Recursion, Access Control, Understanding static, Introducing final, Introducing Nested and
Inner Classes.

Overloading Methods
Q. Explain method overloading in java
In Java, it is possible to define two or more methods within the same class that share the same name, as
long as their parameter declarations are different. When this is the case, the methods are said to be
overloaded, and the process is referred to as method overloading. Method overloading is one of the ways
that Java supports polymorphism.
When an overloaded method is invoked, Java uses the type and/or number of arguments as its guide to
determine which version of the overloaded method to actually call. Thus, overloaded methods must differ
in the type and/or number of their parameters. While overloaded methods may have different return types,
the return type alone is insufficient to distinguish two versions of a method. When Java encounters a call
to an overloaded method, it simply executes the version of the method whose parameters match the
arguments used in the call.
Sample program on method overloading to add strings, integers and float values:

Dept. of AIML, GMIT, Davangere


Module 2- Object Oriented Programming with JAVA (BCS306A)

The above class definition contains overloaded method add(); three versions of add() method is used.
 void add(): method concatenates two strings s1 and s1 and prints them.
 int add(int a, int b): adds two integers a & b and returns the sum to the main() function
 void add(float f1, float f2): adds two floating integers f1 & f2 and prints the sum.
Second sample program on method overloading which computes the volume of a sphere, cylinder and
cuboid.

Dept. of AIML, GMIT, Davangere


Module 2- Object Oriented Programming with JAVA (BCS306A)

Output:

In the above program volume() method is overloaded method. Three versions of volume() method.
 volume(int r): Computes the volume of a sphere.
 volume(int h, int i)): Computes the volume of a cylinder.
 volume(): Computes the volume of a cuboid.

Overloading Constructors
Q. Explain method overloading in java
In Java, we can overload constructors like methods. The constructor overloading can be defined as the
concept of having more than one constructor with different parameters so that every constructor can perform
a different task.
Consider the following Java program, in which we have used three constructors in the class definition.

Dept. of AIML, GMIT, Davangere


Module 2- Object Oriented Programming with JAVA (BCS306A)

Output:

Area of rectangle= length*width


Area of circle =πr2
Area of Triangle=1/2bh
Another sample program on constructor overloading: three different versions of the same constructor is
used.
 OverloadCons(int l, int w): Computes the area of a rectangle
 OverloadCons(int radius): Computes the area of a circle
 OverloadCons(): Computes the area of a Triangle.

Dept. of AIML, GMIT, Davangere


Module 2- Object Oriented Programming with JAVA (BCS306A)

Output:

Using Objects as Parameters


Q. How do you use objects as parameters in Java? Provide a straightforward example.
Like primitive data types, objects can also be passed as parameters to methods in Java. When passing an
object as a parameter to a method, a reference to the object is passed rather than a copy of the object itself.
This means that any modifications made to the object within the method will have an impact on the original
object. Consider the following program demonstrating the object as parameters in Java:

Dept. of AIML, GMIT, Davangere


Module 2- Object Oriented Programming with JAVA (BCS306A)

Output:

Another sample program on passing Objects as Parameters

A Closer Look at Argument Passing


In general, there are two ways that a computer programming language can pass an argument to a subroutine.

 The first way is call-by-value. This approach copies the value of an argument into the formal
parameter of the subroutine. Therefore, changes made to the parameter of the subroutine have no
effect on the argument.

Dept. of AIML, GMIT, Davangere


Module 2- Object Oriented Programming with JAVA (BCS306A)

 The second way an argument can be passed is call-by-reference. In this approach, a reference to
an argument (not the value of the argument) is passed to the parameter. Inside the subroutine, this
reference is used to access the actual argument specified in the call. This means that changes made
to the parameter will affect the argument used to call the subroutine.
call-by-value in java: When primitive type passed to a method, it is passed by value. Thus, a copy of the
argument is made, and what occurs to the parameter that receives the argument has no effect outside the
method. For example, consider the following program: As you can see, the operations that occur inside
method( ) have no effect on the values of a=15 and b=20 used in the call; their values here did not change
to 30 and 10.

Output:

call-by-reference : When an object is passed to a method, the situation changes, because objects are passed
then it is call-by-reference. When we create a variable of a class type, we are only creating a reference to
an object. Thus, when we pass this reference to a method, the parameter that receives it will refer to the
same object as that referred to by the argument. This effectively means that objects act as if they are passed
to methods by use of call-by-reference. Changes to the object inside the method do affect the object used
as an argument. For example, consider the following program.

Dept. of AIML, GMIT, Davangere


Module 2- Object Oriented Programming with JAVA (BCS306A)

Output:

Returning Objects
Q How do you return an object in Java?
User defined methods can return a value of any data type like int, char, float, double etc., like that a method
can return object of class type.
Consider the sample program in which method Test1 add() returns an object of type Test1 to the main
function.

Dept. of AIML, GMIT, Davangere


Module 2- Object Oriented Programming with JAVA (BCS306A)

Recursion
Q. Explain Recursion in java
Java supports recursion. Recursion is the process of defining something in terms of itself. As it relates to
Java programming, recursion is the attribute that allows a method to call itself. A method that calls itself is
said to be recursive.

Output:

Introducing Access Control


Q. Explain access modifiers in Java?
The access modifiers in Java specifies the accessibility or scope of a field, method, constructor, or class.
We can change the access level of fields, constructors, methods, and class by applying the access modifier
on it.
There are four types of Java access modifiers:
1. Private: The access level of a private modifier is only within the class. It cannot be accessed from
outside the class.
2. Default: The access level of a default modifier is only within the package. It cannot be accessed
from outside the package. If you do not specify any access level, it will be the default.

Dept. of AIML, GMIT, Davangere


Module 2- Object Oriented Programming with JAVA (BCS306A)

3. Protected: The access level of a protected modifier is within the package and outside the package
through child class. If you do not make the child class, it cannot be accessed from outside the
package.
4. Public: The access level of a public modifier is everywhere. It can be accessed from within the
class, outside the class, within the package and outside the package.

Output:

Understanding static
Q. When do we use the "static" keyword in Java?
The static keyword in Java is mainly used for memory management. The static keyword in Java is used
to share the same variable or method of a given class. The users can apply static keywords with variables,
methods, blocks, and nested classes. The static keyword belongs to the class than an instance of the class.
The static keyword is used for a constant variable or a method that is the same for every instance of a
class.

Dept. of AIML, GMIT, Davangere


Module 2- Object Oriented Programming with JAVA (BCS306A)

 Normally, a class member must be accessed only in conjunction with an object of its class.
However, it is possible to create a member that can be used by itself, without reference to a specific
instance. To create such a member, precede its declaration with the keyword static. When a
member is declared static, it can be accessed before any objects of its class are created, and without
reference to any object. You can declare both methods and variables to be static. The most
common example of a static member is main( ). main( ) is declared as static because it must be
called before any objects exist.
 Instance variables declared as static are, essentially, global variables. When objects of its class
are declared, no copy of a static variable is made. Instead, all instances of the class share the same
static variable.
 Methods declared as static have several restrictions:
o They can only directly call other static methods.
o They can only directly access static data.
o They cannot refer to this or super in any way. (The keyword super relates to inheritance
and is described in the next chapter.)

Output:

Dept. of AIML, GMIT, Davangere


Module 2- Object Oriented Programming with JAVA (BCS306A)

Introducing final keyword


Q. Explain final keyword in java
The final keyword is a non-access modifier used for classes, attributes and methods, which makes them
non-changeable (impossible to inherit or override). The final keyword is useful when you want a variable
to always store the same value, like PI (3.14159...). The final keyword is called a "modifier".

Output:

Introducing Nested and Inner Classes


Q. Explain Nested and Inner Classes

 It is possible to define a class within another class; such classes are known as nested classes.

 The scope of a nested class is bounded by the scope of its enclosing class. Thus, if class B is defined
within class A, then B does not exist independently of A.

 A nested class has access to the members, including private members, of the class in which it is
nested. However, the enclosing class does not have access to the members of the nested class. A
nested class that is declared directly within its enclosing class scope is a member of its enclosing
class. It is also possible to declare a nested class that is local to a block.

 There are two types of nested classes: static and non-static.

 A static nested class is one that has the static modifier applied. Because it is static, it must access
the non-static members of its enclosing class through an object. That is, it cannot refer to non-static
members of its enclosing class directly. Because of this restriction, static nested classes are seldom
used.

 The most important type of nested class is the inner class. An inner class is a non-static nested
class. It has access to all of the variables and methods of its outer class and may refer to them directly

Dept. of AIML, GMIT, Davangere


Module 2- Object Oriented Programming with JAVA (BCS306A)

in the same way that other non-static members of the outer class do.
 The following program illustrates how to define and use an inner class. The class named Outer has
one instance variable named outer_x, one instance method named test( ), and defines one inner
class called Inner.

Output:

Dept. of AIML, GMIT, Davangere

You might also like