MODULE 3
CLASSES,INHERITANCE
Class Fundamentals
➢Java is a true object oriented language and therefore the underlying
structure of all java programs is classes.
➢Class that defines the state and behavior of the basic program components
known as objects
➢class is a template for an object, and an object is an instance of a class.
template
class object
instance
The General Form of a Class
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
}
}
❑A class is declared by use of the class keyword
❑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.
Methods + variables = members of class
❑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.
A Simple Class
class Box {
double width;
double height;
double depth;
}
➢Here is a class called Box that defines three instance variables: width, height, and
depth.
➢class defines a new type of data. In this case, the new data type is called Box
➢You will use this name to declare objects of type Box
To actually create a Box object:
Box mybox = new Box(); // create a Box object called mybox
•mybox will be an instance of Box.
•every Box object will contain its own copies of the instance variables width, height,
and depth
•To access these variables, you will use the dot (.) operator.
•The dot operator links the name of the object with the name of an instance variable.
•For example, to assign the width variable of mybox the value 100,
Mybox . width = 100;
•This statement tells the compiler to assign the copy of width that is contained
within the mybox object the value of 100
class Box {
double width;
double height;
double depth;
}
// This class declares an object of type Box.
class BoxDemo {
public static void main(String args[]) {
Box mybox = new Box();
double vol;
// assign values to mybox's instance variables
[Link] = 10;
[Link] = 20;
[Link] = 15;
// compute volume of box
vol = [Link] * [Link] * [Link];
[Link]("Volume is " + vol);
}
}
To run this program, you must execute BoxDemo . class.
Volume is 3000.0
class Box {
double width;
double height;
double depth;
}
class BoxDemo2 {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
[Link] = 10;
[Link] = 20;
[Link] = 15;
instance variables */
[Link] = 3;
[Link] = 6;
[Link] = 9;
// compute volume of first box
vol = [Link] * [Link] * [Link];
[Link]("Volume is " + vol);
// compute volume of second box Output : Volume is 3000.0
vol = [Link] * [Link] * [Link]; Volume is 162.0
[Link]("Volume is " + vol);
}
Declaring Objects
obtaining objects of a class is a two-step process.
[Link] a variable of the class type. This variable does not define an object.
Instead, it is simply a variable that can refer to an object.
[Link], we must acquire an actual, physical copy of the object and assign it to that
variable. New operator will do this.
✓The new operator dynamically allocates (that is, allocates at run time) memory
for an object and returns a reference to it
✓This reference is, more or less, the address in memory of the object
allocated by new. This reference is then stored in the variable. Thus, in Java, all
class objects must be dynamically allocated.
Box mybox; // declare reference to object
mybox = new Box(); // allocate a Box object
Box mybox; // declare
reference to object
mybox = new Box(); // allocate a Box
object
Assigning Object Reference Variables
Box b1 = new Box();
Box b2 = b1;
▪It simply makes b2 refer to the same object as does b1. Thus, any changes
made to the object through b2 will affect the object to which b1 is referring, since they
are the same object.
Introducing Methods
This is the general form of a method:
type name(parameter-list) {
// body of method
}
•Here, type specifies the type of data returned by the method
•If the method does not return a value, its return type must be
void.
• The name of the method is specified by name.
•The parameter-list is a sequence of type and identifier pairs separated
by commas.
• Parameters are essentially variables that receive the value of the
arguments passed to the method when it is called.
• If the method has no parameters, then the parameter list will be empty.
•Methods that have a return type other than void return a value to the calling routine
using the following form of the return statement:
return value;
Here, value is the value returned
class BoxDemo3 {
class Box { public static void main(String args[]) {
double width; Box mybox1 = new Box();
double height; Box mybox2 = new Box();
double depth; // assign values to mybox1's instance
// display volume of a box variables
void volume() { [Link] = 10;
[Link]("Volume is "); [Link] = 20;
[Link](width * height * [Link] = 15;
depth); /* assign different values to mybox2's
} instance variables */
} [Link] = 3;
[Link] = 6;
[Link] = 9;
// display volume of first box
[Link]();
// display volume of second box
[Link]();
}
Volume is 3000.0 }
Volume is 162.0
Adding a Method That Takes Parameters
class Box {
class BoxDemo5 {
double width;
public static void main(String args[]) {
double height;
Box mybox1 = new Box();
double depth;
Box mybox2 = new Box();
// compute and return volume
double vol;
double volume() {
// initialize each box
return width * height * depth;
[Link](10, 20, 15);
}
[Link](3, 6, 9);
// sets dimensions of box
// get volume of first box
void setDim(double w, double h, double d)
vol = [Link]();
{
[Link]("Volume is " + vol);
width = w;
// get volume of second box
height = h;
vol = [Link]();
depth = d;
[Link]("Volume is " + vol);
}
}
}
}
Constructors
➢A constructor initializes an object immediately upon creation.
➢It has the same name as the class in which it resides and is syntactically
similar to a method.
➢ Once defined, the constructor is automatically called immediately after
the object is created, before the new operator completes.
➢Constructors look a little strange because they have no return type, not even void.
➢This is because the implicit return type of a class’ constructor is the class type itself
class Box { class BoxDemo6 {
double width; public static void main(String args[]) {
double height; // declare, allocate, and initialize Box
double depth; objects
// This is the constructor for Box. Box mybox1 = new Box();
Box() { Box mybox2 = new Box();
[Link]("Constructing Box"); double vol;
width = 10; // get volume of first box
height = 10; vol = [Link]();
depth = 10; [Link]("Volume is " + vol);
} // get volume of second box
// compute and return volume vol = [Link]();
double volume() { [Link]("Volume is " + vol);
return width * height * depth; }
} }
}
Output
Constructing Box
Constructing Box
Volume is 1000.0
Volume is 1000.0
Parameterized Constructors
class Box { class BoxDemo7 {
double width; public static void main(String args[]) {
double height; // declare, allocate, and initialize Box
double depth; objects
// This is the constructor for Box. Box mybox1 = new Box(10, 20, 15);
Box(double w, double h, double d) Box mybox2 = new Box(3, 6, 9);
{ double vol;
width = w; // get volume of first box
height = h; vol = [Link]();
depth = d; [Link]("Volume is " + vol);
} // get volume of second box
// compute and return volume vol = [Link]();
double volume() { [Link]("Volume is " + vol);
return width * height * depth; }
} }
} Output:
Volume is 3000.0
Volume is 162.0
Copy Constructors
Example
The this Keyword REVISEEE
❑Sometimes a method will need to refer to the object that invoked it. To allow this,
Java defines the 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.
❑You can use this anywhere a reference to an object of the current class’ type is
permitted.
Box(double w, double h, double d) {
this. width = w;
this. height = h;
this. depth = d;
}
Instance Variable Hiding
✓when a local variable has the same name as an instance variable, the local
variable hides the instance variable.
✓This is why width, height, and depth were not used as the names of the
parameters to the Box( ) constructor inside the Box class.
✓This lets you refer directly to the object, you can use it to resolve any name
space collisions that might occur between instance variables and local variables
// Use this to resolve name-space collisions.
Box(double width, double height, double
depth) {
this. width = width;
this. height = height;
this. depth = depth;
}
Garbage Collection
✓ when no references to an object exist, that object is assumed to be no longer
needed, and the memory occupied by the object can be reclaimed.
✓There is no explicit need to destroy objects as in C++.
✓Garbage collection only occurs sporadically (if at all) during the execution of
your program.
✓It will not occur simply because one or more objects exist that are no longer used,
and these objects are destroyed and their memory is released for later
“Reallocation”
The finalize( ) Method
Sometimes an object will need to perform some action when it is destroyed
▪For example, if an object is holding some non-Java resource such as a file handle
or character font, then you might want to make sure these resources are freed
before an object is destroyed.
▪To handle such situations, Java provides a mechanism called finalization.
▪ By using finalization you can define specific actions that will occur when an
object is just about to be reclaimed by the garbage collector.
▪To add a finalizer to a class, you simply define the finalize( ) method.
▪Inside the finalize( ) method, you will specify those actions that must be
performed before an object is destroyed.
✓The garbage collector runs periodically, checking for objects that are no longer
referenced by any running state or indirectly through other referenced objects.
The finalize( ) method has this general form:
protected void finalize( )
{
// finalization code here
}
▪Here, the keyword protected is a specifier that prevents access to finalize( ) by
code defined outside its class.
▪It is important to understand that finalize( ) is only called just prior to garbage
collection. It is not called when an object goes out-of-scope.
Overloading Methods
• 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.
• Java will employ its automatic type conversions only if
no exact match is found. (Overload 1)
• Method overloading supports polymorphism because
it is one way that Java implements
the “one interface, multiple methods” paradigm.
• For instance, in C, the function abs( ) returns the
absolute value of an integer, labs( ) returns the
absolute value of a long integer, and fabs( ) returns the
absolute value of a floating-point value.
• Since C does not support overloading, each function
has to have its own name, even though all three
functions do essentially the same thing. value method
can use the same name.
Example
// Java program to demonstrate working of method overloading in Java
public class Sum {
// Overloaded sum(). This sum takes two int parameters
public int sum(int x, int y) { return (x + y); }
// Overloaded sum(). This sum takes three int parameters
public int sum(int x, int y, int z)
{
return (x + y + z);
}
// Overloaded sum(). This sum takes two double
// parameters
public double sum(double x, double y)
{
return (x + y);
}
public static void main(String args[])
{
Sum s = new Sum();
[Link]([Link](10, 20));
[Link]([Link](10, 20, 30));
[Link]([Link](10.5, 20.5));
}
}
Overloading Constructors
• In addition to overloading normal methods,
you can also overload constructor methods.
• the equals( ) method inside Test compares
two objects for equality and returns the result.
• That is, it compares the invoking object with
the one that it is passed
Overloading Constructors example
public class Employee
{
String name; int id;
public Employee()
{
name = "Unknown";
id = 0;
}
public Employee(String empName, int empId)
{
name = empName;
id = empId;
}
public void display()
{
[Link]("Name: " + name + ", ID: " + id);
}
public static void main(String[] args)
{
Employee emp1 = new Employee(); // Default constructor
Employee emp2 = new Employee("John", 101); // Parameterized constructor
[Link]();
[Link]();
}
}
Using object as a parameter
• In Java, using an object as a parameter means
passing an instance of a class to a method.
This allows the method to interact with the
object's fields and methods. Here's an
example to illustrate this concept:
Example
class Person { class Main {
String name; int age; static void greetPerson(Person person)
Person(String name, int age) {
{ [Link]("Hello, " +
[Link] + "!");
[Link] = name;
}
[Link] = age;
public static void main(String[] args)
}
{
void displayDetails()
Person p1 = new Person("Alice", 25);
{ greetPerson(p1);
[Link]("Name: " + [Link]();
name + ", Age: " + age);
}}
}}
Pass-by-Reference Behaviour: In Java, objects are passed by reference. Any
changes made to the object inside the method will affect the original object
class Person
{
String name;
Person(String name)
{
[Link] = name;
}
}
public class Main {
static void changeName (Person person) {
[Link] = "Bob";
}
public static void main(String[] args) {
Person person = new Person("John");
changeName (person);
[Link]("Name after changeNameToBob: " +
[Link]);
}}
static void reassignPerson(Person person)
{
person = new Person("Bob");
// Assigns a new object to the local reference
}
public static void main(String[] args)
{
Person p1 = new Person("Alice", 25);
greetPerson(p1);
[Link]("Name : " + [Link]);
reassignPerson(person);
[Link]("Name after reassignPerson: " + [Link]);
}
Java is pass-by-value. When an object is passed as a parameter, the value of the
reference (i.e., the memory address) is copied.
Modifying the object's fields through the reference affects the original object.
Reassigning the reference itself does not affect the original reference outside the
method.
Returning Objects from Methods
class MyClass {
int value;
MyClass(int value) {
[Link] = value;
}}
public class ReturnObjectExample {
public static MyClass createObject(int value) {
return new MyClass(value); } public static void main(String[] args)
{
MyClass obj = createObject(10);
[Link]([Link]); // Output: 10
}}
Recursive Function
public class RecursionExample
returnType methodName(parameters)
{
{ public static int factorial(int n) {
if (baseCaseCondition) if (n == 0)
{ {
return baseCaseValue; return 1;
}
}
return n * factorial(n - 1);
return methodName(smallerProblem); }
} public static void main(String[]
args) {
int num = 5;
[Link]("Factorial of
" + num + " is: " +
factorial(num)); // Output: 120 }
}
Introducing Access Control
• Encapsulation links data with the code that
manipulates it.
• However, encapsulation provides another
important attribute: access control.
• Through encapsulation, control what parts of a
program can access the members of a class.
• Java’s access specifiers are public, private, and
protected.
• protected applies only when inheritance is
involved
• When a member of a class is modified by the
public specifier, then that member can be
accessed by any other code.
• When a member of a class is specified as
private, then that member can only be
accessed by other members of its class.
• When no access specifier is used, then by
default the member of a class is public within
its own package, but cannot be accessed
outside of its package.
static
• Normally, a class member must be accessed
only in conjunction with an object of its class.
• Using static a class member that will be used
independently of any object of that class.
• When a member is declared static, it can be
accessed before any objects of its class are
created, and without reference to any object.
• both methods and variables to be static.
• apply static keyword with variables, methods,
blocks and nested classes.
• The static variable can be used to refer to the
common property of all objects.
• The static variable gets memory only once in the
class area at the time of class loading.
• There are two main restrictions for the static
method. They are:
• The static method can not use non static data
member or call non-static method directly.
• this and super cannot be used in static context.
final
• A variable can be declared as final.
• Doing so prevents its contents from being
modified
• initialize a final variable when it is declared.
• Variables declared as final do not occupy
memory on a per-instance basis.
• Thus, a final variable is essentially a constant.
• Final k/w with variable, method and class
• If you make any variable as final, you cannot
change the value of final variable(It will be
constant).
• If you make any method as final, you cannot
override it.
• If you make any class as final, you cannot
extend it.
• final method is inherited but you cannot
override it
INHERITANCE
✓ The mechanism of deriving a new class from old class is called
inheritance.
✓ In java a class that is inherited is called Super Class.
✓ The class that does the inheriting is called Subclass.
✓ Subclass =instance variables + methods of super class + its own
unique elements.
✓ To inherit a class Extend keyword is used.
✓ General form: Class subclass-name extends super class
{
Body of class
}
simple inheritance Example
Class simple inheritance
Class A---------->Super class
{
{
Public static void main (string args[ ])
int i, j;
{ A superob = new A();
Void showij()
B subob = new B();
{
Superob.i=10;
[Link](“i and j:”+ i + ““+j);
Superob.j =20;
}}
[Link](“contents of superob;”);
Class B extends A
[Link]( );
{
Subob.i=7;
Int k; Subclass
Subob.j=8;
Void showk()
Subob.k=9;
{ [Link](“K:”+k);
[Link](“contents of subob”);
}
[Link]();
Void sum()
[Link]();
{
[Link](“sum of i,j,k in subob:”);
[Link](“i+j+k” +(i+j+k));
[Link]();
}
}
}
}
✓Subclass cannot access the members of superclass that have been
declared as private
Class A---------->Super class Class Access
{ {
int i; Public static void main(string args [ ])
Private int j; {
Void setij (int x,int y) B subob = new B( );
{ i= x; Subob. Setij (10,12);
j= y; [Link]();
}} System .[Link](“total is “ + subob .total);
Class B extends A }
{ }
Int total(); Subclass
Void sum( )
{
Total = i+ j; //error j is not accessible here
}
}
Using super to call superclass
constructor
Class Box weight extends Box------> superclass
{ subclass
Double weight;
Box weight(double w,double h,double d,double
m)
{
Super(w,h,d);
} calls super class constructor
}
Second use of super
✓Second form of super acts somewhat like “this”.
✓Except it always refer super class of subclass in which it is used
✓General form :super. Member.
✓Here Member can be either a method or instance variable.
✓Second form of super is most applicable to situations in which
member names of subclass hide members by same name in the super
class.
Example
Class A--------> Superclass
{ Class Use Super
int i; {
}
Class B extends A Public static void main(string args [ ])
{ Subclass {
int i; // this i hides the i in A B subob =new B(1,2);
B(int a, int b)
{ Subob. Show();
Super.i=a; }
i = B; }
}
Void show()
{
[Link](“I in super class:”
+super. i);
[Link](“I in subclass:” +i);
}
}
Creating Multilevel Hierarchy
A Super Class B And C
B Super class of C / Subclass Of A
C Subclass of A and B
✓ In this case C inherits all aspects Of B and A
✓. This Scenario of inheriting classes in multilevel hierarchy is know as Multilevel
Inheritance
Method Overriding
In a class heirarchy,when method in subclass has same name and type signature as
method in its super class, then the method in the subclass is said to override the method
in the super class.
Class A B(int a,int b,int c)
{ {
Int i,j; Super(a,b);
A( int a, int b) K=c;
{ }
i=a; Void show()
j=b; {
} [Link](“K:” +k);
Void show() }
{ }
[Link](“I and j:” + i + “ “ +j) Class override
} {
} Public static void main(string args[ ])
Class B extends A {
{ B subob=new B(1,2,3);
Int K; [Link]() );
}}
Example 2
Class A B(int a,int b,int c)
{ {
Int i,j; Super(a,b);
A(int a,int b) K=c;
{ }
i=a; Void show()
j=b; {
} Super. show(); //this call A 'show()
Void show() [Link](“K:” +k);
{ }}
[Link](“I and j:” + i + “ “ +j) Class override
} {
} Public static void main(string args[ ])
Class B extends A {
{ B subob=new B(1,2,3);
Int K; Subob. Show() );
}}
Using final with Inheritance
✓Two uses of final: •We know that java normally calls to
[Link] prevent overriding methods dynamically, at run time.
[Link] prevent inheritance. This is called Late binding.
✓Using final to prevent overriding: •Since final methods cannot be
overridden, a call to one can be
resolved at compile time. this is
• Methods declared as final cannot be overridden. called early binding
• Example: Class A
{
Final void meth( )
{
[Link](“this is a final method”);
}
}
Class B extends A
{
Void meth( ) //Error ! can’t override.
{
System .[Link](“illegal”);
}
Using final to prevent inhertitance
✓If the user wants to prevent a class being inherited then he should
precede the class declaration with final.
✓Declaring a class as final implicitly declares all of its methods as
final, too.
✓It is illegal to declare a class as both abstract and final since an
abstract class is incomplete by itself and relies upon its subclasses to
provide complete implementations.
Example
final class A
{
//…
}
Class B extends A //Error ! can’t subclass A
{
//…
}
It is illegal for B to inherit A since A is declared as final
Method Overloading
✓ Overloading is a concept where two or more methods within the same
class share the same name and their parameters declarations are different.
✓In this case the methods are said to be overloaded and this process is
referred to as Method overloading
✓Method Overloading is one of the ways that java implements
polymorphism.
✓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.
Example
Class overload demo double test( double a)
{ {
Void test() [Link](“double a: ” + a);
{ Return a*a;
}
[Link](“no parameters”);
}
}
Class overload
Void test( int a)
{
{ [Link](“a” +a);
Public static void main(string args[ ])
}
overload demo ob = new Overload demo();
double result;
Void test( int a ,int b)
[Link]();
{
[Link](10);
[Link](“a and b ” + a “ “ +b);
[Link](10,20);
}
result=[Link](123.25);
[Link](“result of [Link] (123.25):” +
result);
}
}
Overriding V/S Overloading
Overriding OVERLOADING
✓ Method name and type ✓ Only method name must
signature of super class be same in super class
and subclass must be and subclass but type
signature must be
same. different.
Abstract Classes
✓There are situation that a user want to define a super class that
declares the structure of given abstraction without providing a complete
implementation of every method.
✓That is user will only create a super class that only defines a
generalized form that will be shared by all of its subclasses, leaving it to
each subclass to fill in the details.
✓In such cases subclass must ensure some way to override all
necessary methods. Java’s solution to this problem is the abstract
method.
✓This is achieved by using abstract type modifier.
✓Syntax to declare an abstract method:
Abstract type name (parameter_list);
✓Any class that contains one or more abstract methods must
also be declared abstract(just use abstract keyword in front of
class keyword)
✓There can be no objects of an abstract class, that is an
abstract class cannot be directly instantiated with new
operator.
✓Any subclass of abstract class must either implement all of
the abstract methods in the superclass,or be itself declared
abstract.
Example
Abstract class A--->super class which is abstract class
{
Class Abstract Demo
Abstract void callme( ); //no implementation
{
Void callmetoo( )
Public static void main(string
{ args [ ]);
[Link](“this is a concrete method”); B b=new B( );
} [Link]( );
} [Link]( );
Class B extends A }
{ }
Void callme( ) //implementation is done in subclass
{
[Link](“B’s implementation of callme.”);
}
Method Overriding
• In a class hierarchy, when a method in a
subclass has the same name and type
signature as a method in its superclass, then
the method in the subclass is said to override
the method in the superclass.
• When an overridden method is called from
within a subclass, it will always refer to the
version of that method defined by the
subclass.
• Method overriding occurs only when the
names and the type signatures of the two
methods are identical. If they are not, then the
two methods are simply overloaded.
Dynamic Method Dispatch
• Runtime polymorphism or Dynamic Method
Dispatch is a process in which a call to an
overridden method is resolved at runtime
rather than compile-time.
• In this process, an overridden method is called
through the reference variable of a superclass.
The determination of the method to be called
is based on the object being referred to by the
reference variable.
• Overridden methods allow Java to support run-time polymorphism.
• Overridden methods are another way that Java implements the
“one interface, multiple methods” aspect of polymorphism.
• Thus, by combining inheritance with overridden methods, a
superclass can define the general form of the methods that will be
used by all of its subclasses.
• Dynamic, run-time polymorphism is one of the most powerful
mechanisms that object oriented design brings to bear on code
reuse and robustness.
• The ability of existing code libraries to call methods on instances of
new classes without recompiling while maintaining a clean abstract
interface is a profoundly powerful tool.
Method Overriding
• If subclass (child class) has the same method
as declared in the parent class, it is known
as method overriding in Java
• Method overriding is used for runtime
polymorphism
Using Abstract Classes
• A class which is declared with the abstract
keyword is known as an abstract class in Java. It
can have abstract and non-abstract methods
• It needs to be extended and its method
implemented. It cannot be instantiated.
• It can have constructors and static methods also.
• It can have final methods which will force the
subclass not to change the body of the method.
class Test {
protected int x,
protected float y;
String z;
}
class Main {
public static void main(String args[]) {
Test t = new Test();
[Link](t.x + " " + t.y + “” +t.z);
}
}
class main_class
{
public static void main(String args[])
{
int x = 9;
if (x == 9)
{
int x = 8;
[Link](x);
}
}
}
class SimpleStaticExample
{
void myMethod() {
[Link]("myMethod");
}
public static void main(String[] args)
{
myMethod();
}
}
class Demo{
void disp(int a, int b)
{ [Link]("Method A");
}
void disp(int a, double b, double c)
{ [Link]("Method B");
}
public static void main(String args[]){
Demo obj = new Demo();
[Link](100, 20.8); }
}