0% found this document useful (0 votes)
24 views76 pages

18CS653 Module 3

Uploaded by

bneelagund
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views76 pages

18CS653 Module 3

Uploaded by

bneelagund
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 76

PROGRAMMING IN JAVA

18CS653
MODULE-3
CLASSES,
METHODS,INHERITANCE
TOPICS
Chapter: 06 Introducing Classes

3.1 Class Fundamentals


3.1.1 The General Form of a Class
3.1.2 A Simple Class
3.2 Declaring Objects
3.2.1 A Closer Look at new
3.3 Assigning Object Reference Variables
3.4 Introducing Methods
3..4.1 Adding a Method to the Class
3.4.2 Returning a Value
3.4.3.Adding a Method That Takes Parameters
3.5 Constructors
3.5.1Parameterized Constructors
3.6 this Keyword
3.6.1 Instance Variable Hiding
3.7 Garbage Collection
3.8 The finalize( ) Method
3.9 A Stack Class
TOPICS
Chapter: 07 A Closer Look at Methods and Classes

3.10 Overloading Methods


3.10.1 Overloading Constructors
3.11 Using Objects as Parameters
3.12 A Closer Look at Argument Passing
3.13 Returning Objects
3.14 Recursion
3.15 Introducing Access Control
3.16 Understanding static
3.17 Introducing final
3.18 Arrays Revisited
3.19 Introducing Nested and Inner Classes
TOPICS
Chapter: 08 Inheritance
3.20 Inheritance Basics
3.20.1 Member Access and Inheritance
3.20.2 A Superclass Variable Can Reference a Subclass Object
3.21 Using super
3.21.1 Using super to Call Superclass Constructors
3.21.2 A Second Use for super to access members of super class
3.22 Creating a Multilevel Hierarchy
3.23 When Constructors Are Called
3.24 Method Overriding
3.25 Dynamic Method Dispatch
3.25.1 Why Overridden Methods?
3.25.2 Applying Method Overriding
3.26 Using Abstract Classes
3.27 Using final with Inheritance
3.27.1 Using final to Prevent Overriding
3.27.2 Using final to Prevent Inheritance
3.28 The Object Class
3.1 CLASS FUNDAMENTALS

Classes and Objects are the fundamentals of Object Oriented Programming.


Class in Java creates a new datatype . Once it is created we can use it to create
a object of that type.

Definition of class : class is a blue print or prototype or template from which


objects are created.
Definition of Object: Object is an instance of the class.

In general class contains the methods ( member functions) and variables


( data members ) .
3.1.1 GENERAL FORM OF CLASS
A simplified general form of a class definition is shown here:

class classname {
type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;

type methodname1(parameter-list) {
// body of method
}
type methodname2(parameter-list) {
// body of method
}
// ...
type methodnameN(parameter-list) {
// body of method
}
}
3.1.1 GENERAL FORM OF CLASS
Class: Class is defined using the keyword class

Instance Variables : Variables that are defined inside the class are called

Instance variables because each object of the class have their own variables.

Methods : Methods are also called as member functions and code is written

inside the methods. Methods can be defined with or without parameters.

 it is not necessary that all the methods should be defined as static and public

like the main method.

It is not necessary that class should have main method . We can define main

method only if that class is the starting point of the program.


3.1.2 SIMPLE CLASS
ASSIGNMENT
3.2 DECLARING OBJECT
When we create a class we just create a new data type.
Then we use this data type to create an object of that type.
In Java we can obtain the object in two steps
1. First we declare the variable of the class type
2. Second we acquire an actual, physical copy of the object and assign it to
that
variable. We can do this using the new operator.
The new operator dynamically allocates (that is, allocates at run time)
memory for an object and returns a reference to it.
Example to create an object for the class
Box mybox ; // b variable of type Box
mybox = new Box( ); // using new operator to allocate memory
3.2.1 A CLOSER LOOK AT NEW
The new operator dynamically allocates memory for an object.
It has this general form:
class-var = new classname( );
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. A constructor defines what
occurs when an object of a class is created.
3.3. ASSIGNING OBJECT REFERENCE VARIABLES
When an object is assigned it acts differently. The below example shows how
object reference variable is assigned.
Box b1 = new Box( );
Box b2 = b1; // object b1 is assigned to b2
Here both the objects b1 and b2 refer to the same object. The situation is
depicted below in the figure.
Although b1 and b2 both refer to the same object, they are not linked in any
other way.
For example, a subsequent assignment to b1 will simply unhook b1 from the
original object without affecting the object or affecting b2.
For example:
Box b1 = new Box();
Box b2 = b1;
// ...
b1 = null;
Here, b1 has been set to null, but b2 still points to the original object. Here
The situation is depicted below in the figure.
3.4 INTRODUCING METHOD
Method :A method in Java is a block of code that, when called, performs
specific actions mentioned in it.
Example, if you have written instructions to draw a circle in the method, it will
do that task.
 Methods can have parameters or arguments. They are also referred to as
functions.

The primary uses of methods in Java are:


It allows code reusability (define once and use multiple times)
You can break a complex program into smaller chunks of code
It increases code readability
General form of Method

type name(parameter-list) {
// body of method
}

Type : specifies the value that the method returns. It can be of any valid data
type.

Name : name specifies the name of the method. It can be any legal identifier
other than those already used by other items within the current scope.
Parameter-list: These are the arguments that are passed to the method which
reveive the values when the methd is called. Parameters are optional. If the
method
has no parameters, then the parameter list will be empty.
Body of the Method: contains the logic part of the program.
3.4.1 ADDING METHOD TO THE CLASS
The below example demonstrate how to add a method to the class.
3.4.1 ASSIGNMENT
3.4.2 RETURNING A VALUE
The below example demonstrate how to add a method to the class that returns
value.
3.4.3 ADDING METHOD TAKES PARAMETER
The below example demonstrate how to add a method to the class with
parameters.
3.5 CONSTRUCTOR
Definition: Constructor is a special member (method) of a class which is used to
initialize the state of an object. It provides the values to the data members at the
time of object creation that is why it is known as constructor.
Characteristics of constructors :
Constructor name is same as the name of the class.
Constructor cannot have any return type not even void
Constructors are called only once when the objects are created using new
keyword.
Constructor cannot be abstract, static, final and synchronized.
Java compiler provides default constructor if you do not have any constructor
in
the class.
 Constructor is called default constructor when it does not have any arguments.
EXAMPLE OF CONSTRUCTOR
3.5.1 PARAMETERIZED CONSTRUCTOR
Definition: Constructor with arguments are called parameterized constructor.
3.6 this KEYWORD
this can be used inside any method to refer to the current object. That is, this is
always a reference to the object on which the method was invoked.
3.6.1 INSTANCE VARIABLE HIDING
In Java, if there is a local variable in a method with the same name as the instance
variable, then the local variable hides the instance variable.
3.7 GARBAGE COLLECTION
In java, garbage means unreferenced objects.
Garbage Collection is process of reclaiming the runtime unused memory
automatically. In other words, it is a way to destroy the unused objects.
In order to destroy unused objects, we were using free() function in C language
and delete() in C++. But, in java it is performed automatically. So, java
provides better memory management.

Advantage of Garbage Collection


It makes java memory efficient because garbage collector removes the
unreferenced objects from heap memory.
It is automatically done by the garbage collector(a part of JVM) so we don't
need to make extra efforts.
Unrefrencing of objects is done in multiple ways as follows:
1. By anonymous object: Anonymous objects are those objects in Java which
are created without any reference variable. As a result, after creation, we have
no way to access the anonymous object.
new Student( );
In the above code, even though an object of Student class is created, it has no
reference variable and cannot be used after creation, but it acquires memory.
2. By nulling reference: When an object is referenced to null value, it is
considered an unreferenced object as it holds only null value.
Student s1 = new Student( );
s1 = null;
3. By assigning a reference to another object: When one object is assigned to
another, first object is of no use and can be considered as garbage.
Student s1 = new Student( );
Student s2 = new Student( );
s2 = s1;
3.8 FINALIZE METHOD
finalize() method in Java is used to release all the resources used by the object
before it is deleted/destroyed by the Garbage collector.
finalize is not a reserved keyword, it's a method.
Once the clean-up activity is done by the finalize() method, garbage collector
immediately destroys the Java object.
This method helps Garbage Collector to close all the resources used by the
object and helps JVM in-memory optimization.

The finalize( ) method has this general form:

protected void finalize( )


{
// finalization code here
}
3.9 STACK CLASS
Here is a class called Stack that implements a stack for integers:
Chapter -07 3.10 Overloading Methods

Method Overloading:

Definition: When a class have more than one method with same name and
different parameters then we say that the method is overloaded.

Method overloading is also known as Compile-time Polymorphism, Static


Polymorphism, or Early binding in Java.

Method overloading is one of the ways that Java supports polymorphism.

Overloaded method are invoked based on the arguments and the type of
arguments passed in the method call.
Overloading Methods
Example : Overloading Methods
Example : Overloading Methods
3.10.1 Constructor Overloading

Constructor Overloading:

Definition: Similar to Method overloading we can have more than one


constructor in the same class with different arguments. Then this process is
called constructor Overloading.

Why Constructor Overloading:


we know that constructor are used to initialize the object. Whenever we create
an object by a new keyword, JVM invokes the constructor and initializes values
in memory. Sometimes we want to initialize the objects in different ways and
perform different actions.
Example : Constructor Overloading
3.11 Using Objects as Parameters
In Java we can also pass object as argument to the methods. Below Example
demonstrate how to pass object as argument to the method.
3.12 A Closer Look at Passing Argument
In Java we can pass arguments to the methods in two different ways:

1. Call-by-value
2. Call-by-reference

Call-by-value: Call by Value means calling a method with a parameter as


value. Through this, the argument value is passed to the parameter.
In call by value, the modification done to the parameter passed does not reflect
in the caller's scope. That is changes made in the called methods will not
reflect/affect in the calling method.
Example: call-by-value
Call-by-reference: Call by Value means calling a method with a parameter as
object. Through this, the argument object is passed to the parameter.
In call by reference, the modification done to the parameter passed reflect in
the caller's scope. That is changes made in the called methods will
reflect/affect in the calling method.
3.13 Returning Object

Like any other data datatype, a method can returns object. For example, in the
following program, the makeTwice( ) method returns an object in which the value
of instance variable is two times than it is in the invoking object.
Example for returning the object from method
3.14 Recursion
Recursion in java is a process in which a method calls itself continuously untill
and unless some specific condition is met. A method in java that calls itself is
called recursive method.
It makes the code compact but complex to understand.

Syntax:
returntype methodname( )
{
//code to be executed
methodname(); //calling same method
}
Program to find factorial of a number using recursion
3.15 Introducing Access Control
In Java, access modifiers (Access Controls) are used to set the accessibility
(visibility) of classes, interfaces, variables, methods, constructors, data members,
and the setter methods.
For example,
class Animal
{
public void method1() {...}
private void method2() {...}
}

In the above example, we have declared 2 methods: method1( ) and method2( ).


Here,
method1 is public - This means it can be accessed by other classes.
method2 is private - This means it can not be accessed by other classes.
Access Control
The different types of Access Control supported by Java are:
 default
 private
 protected
 public

default Access Control: If we do not explicitly specify any access modifier for
classes, methods, variables, etc, then by default the default access modifier is
considered.
For example:
TOPICS
Chapter: 08 Inheritance
3.20 Inheritance Basics
3.20.1 Member Access and Inheritance
3.20.2 A Superclass Variable Can Reference a Subclass Object
3.21 Using super
3.21.1 Using super to Call Superclass Constructors
3.21.2 A Second Use for super to access members of super class
3.22 Creating a Multilevel Hierarchy
3.23 When Constructors Are Called
3.24 Method Overriding
3.25 Dynamic Method Dispatch
3.25.1 Why Overridden Methods?
3.25.2 Applying Method Overriding
3.26 Using Abstract Classes
3.27 Using final with Inheritance
3.27.1 Using final to Prevent Overriding
3.27.2 Using final to Prevent Inheritance
3.28 The Object Class
3.20 Inheritance Basics
Inheritance: Inheritance is a mechanism in which one object acquires all the
properties and behaviors of a parent object.
Inheritance allows us to create a new class from the existing class.
When we inherit from an existing class, we can reuse methods and fields of the
parent class and also we can add new methods and fields in current class also.

Parent class: Parent class is also known as super class or Base class.
Child class: Child class is also known as sub class or Derived class.

Syntax for Java Inheritance


class Subclass-name extends Superclass-name
{
//methods and fields
}
3.20.1 Member Access and Inheritance
Although the subclass can access all the variables and methods of the super class.
The subclass cannot access the private members of the super class.
Example:

In the above example the Animal class is having private variable called age.
Although Dog is a subclass it cannot access the private variable called age
3.20.2 Super class variable refer subclass Object
The super class reference variable can hold the sub class object actually, it is
widening in case of objects (Conversion of lower datatype to a higher datatype).
when the super class variable refer to the subclass object . Using the
super class variable we can access only the members of the super class. If we try
to access the members of the subclass then the compiler will give error.

In the below example a super class (Animal class) variable called a is referening
the sub class( Dog) object.
Animal a;
a = new Dog();

If we call a.bark() then the compiler will give the error …


3.21 Super Keyword

Super keyword in java is used to over come the confusion between the superclass
and subclass when there are same methods and variables in both the parent (super
) class and child(sub) class.

Super Keyword Usage:

Super keyword is used for two purpose:


1. To call the super class constructors
2. To call the members of the super class.
3.21.1 using super to call constructors of super class

A subclass can call a constructor defined by its superclass by use of the following
form of super:
super(arg-list);
Here, arg-list specifies any arguments needed by the constructor in the superclass.
super( ) must always be the first statement executed inside a subclass’
constructor.

The below example demonstrate how super is used to call the super class
constructor.
Example: using super to call constructors of super class
3.21.2 using super to access members of super class
super is used to access the members of the super class when the members name
are same in parent class/ super class and child class/ subclass.
Syntax to access the super class members:
super.member_name;

The example show how to access


The super class member.
class A contains variable i and
Class B contains variable i

super class members are accessed


as super.i
3.22 Creating Multilevel Hierarchy
Multilevel Hierarchy: In java it is possible to make use the subclass to be the
superclass of another class. Example consider the classes A,B and C . Where C is
the subclass of B and B is the subclass of A. Class C inherits all the traits of class
A and B. where as the class B inherits all the traits of class A..
Example of Multilevel Hierarchy
3.23 When constructors are called
constructors are called in order of derivation, from superclass to subclass. Further,
since super( ) must be the first statement executed in a subclass constructor, this

order is the same whether or not super( ) is used. If super( ) is not used, then the
default or parameterless constructor of each superclass will be executed.

The following program illustrates when constructors are executed:


The output from this program is shown here:
Inside A’s constructor
Inside B’s constructor
Inside C’s constructor
3.24 Method Overriding
Method Overriding: In a class hierarchy if the subclass has the same method
name with same signature type as in superclass then, the method in the subclass is
said to override the method in the subclass.

When an overridden method is called within the subclass object it always invoke
the method in the subclass. The method defined by the superclass will be hidden.

The below example demonstrate the method overriding.


We have the method called walk() in the class Person as well as Student. When
we create a object for class student and invoke the walk() method it will refer to
the walk method present in student class .
Example Method Overriding
3.25 Dynamic Dispatch Method
Dynamic Method Dispatch in Java is the process by which a call to an overridden
method is resolved at runtime (during the code execution). The concept of method
overriding is the way to attain runtime polymorphism in Java. During the code
execution, JVM decides which implementation of the same method should be
called.
3.25.1 Why Overridden Methods
Overridden methods allow Java to support run-time polymorphism.
superclass provides all elements that a subclass can use directly. It also defines
those methods that the derived class must implement on its own. This allows the
subclass the flexibility to define its own methods.
3.25.2 Applying Overridden Methods
Below example show the practical use of method overriding
Example: The following program creates a superclass called Figure that stores
the dimensions of a two-dimensional object. It also defines a method called
area( ) that computes the area of an object. The program derives two subclasses
from Figure. The first is Rectangle and the second is Triangle. Each of these
subclasses overrides area( ) so that it returns the area of a rectangle and a triangle,
respectively.
3.26 Using Abstract

Abstract class: If the class is declared with the keyword abstract then the class is
called abstract class. Abstract class will give the provision for the subclasses to
implements the methods in their own.
abstract class Shape
{
int color;
// An abstract function
abstract void draw();
}
3.26 Using Abstract

Abstract class: If the class is declared with the keyword abstract then the class is
called abstract class. Abstract class will give the provision for the subclasses to
implements the methods in their own.
abstract class Shape
{
int color;
// An abstract function
abstract void draw();
}
important observations about abstract classes are as follows:

An instance of an abstract class can not be created.


Constructors are allowed.
We can have an abstract class without any abstract method.
There can be a final method in abstract class but any abstract method in
class(abstract class) can not be declared as final or in simpler terms final method
can not be abstract itself as it will yield an error: “Illegal combination of
modifiers: abstract and final”
We can define static methods in an abstract class
We can use the abstract keyword for declaring top-level classes (Outer class)
as well as inner classes as abstract
If a class contains at least one abstract method then compulsory should
declare a class as abstract
If the Child class is unable to provide implementation to all abstract methods of
the Parent class then we should declare that Child class as abstract so that the
next level Child class should provide implementation to the remaining abstract
method
3.27 Using final with Inheritance

We can use the final keyword with Inheritance for two things.

Prevent Overriding: When we use the final to methods in superclass we cannot


override that method in the subclass.

Preventing Inheritance: When we use the final to a superclass we cannot inherit


the super class. That is we cannot create the subclass.
3.27.1 Using final to prevent Overriding
When a method in the super class is defined as final then we cannot override that
method in the subclass. The below example demonstrate how to prevent
overriding.
3.27.2 Using final to prevent Inheritance
When a super class is defined as final then we cannot extend it. The below

example demonstrate how to prevent Inheritance.


3.28 The Object Class
Object is a superclass of all other classes. This means that a reference variable of
type Object can refer to an object of any other class.
Object defines the following methods, which means that they are available in
every object.
THANK YOU

You might also like