0% found this document useful (0 votes)
2 views94 pages

Aoop - Unit II

The document covers advanced object-oriented programming concepts in Java, including class fundamentals, object declaration, methods, constructors, and inheritance. It explains the use of instance variables, method overloading, and the 'this' keyword, along with examples demonstrating class creation, object instantiation, and volume calculation. Additionally, it discusses constructors, method overloading, and the nuances of passing and returning objects in Java.

Uploaded by

hi2bhavya
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)
2 views94 pages

Aoop - Unit II

The document covers advanced object-oriented programming concepts in Java, including class fundamentals, object declaration, methods, constructors, and inheritance. It explains the use of instance variables, method overloading, and the 'this' keyword, along with examples demonstrating class creation, object instantiation, and volume calculation. Additionally, it discusses constructors, method overloading, and the nuances of passing and returning objects in Java.

Uploaded by

hi2bhavya
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/ 94

21CSC206P - ADVANCED OBJECT ORIENTED AND

PROGRAMMING

UNIT – II OBJECT ORIENTED PROGRAMMING IN JAVA


UNIT - II

Class Fundamentals, Declaring Objects, Object Reference, Introduction to Methods,


Constructors, this Keyword, Method Overloading, Using Objects as Parameters.

Returning Objects, Recursion, Access Control, Static Members, Final Variables, Inner
Classes, Command Line Arguments, Variable Length Arguments.

Inheritance - Super Class, Sub Class, The Keyword super, protected Members, Calling
Order of Constructors

Method Overriding, the Object class, Abstract Classes and Methods, using final with
Inheritance.
DEFINING CLASSES IN JAVA
A class is a template for an object, and an object is an instance of a class. A class is declared by use of the class keyword.
Syntax:
class classname {
type instance-variable1;
type instance-variable2;
type instance-variableN;

type methodname1(parameter-list) {
// body of method
}
type methodnameN(parameter-list) {
// body of method
}
• The data, or variables, defined within a class are called instance variables.
• The code is contained within methods.
• 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.
• 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.
A Simple Class

class called Box that


defines three instance variables: width, height, and depth.

class Box
{
double width;
double height;
double depth;
}
The new data type is called Box. This name is used to declare objects of type Box. The class declaration
only creates a template. It does not create an actual object.

To create a Box object

Box mybox = new Box(); // create a Box object called mybox

mybox will be an instance of Box.


Example1: BoxDemo.java
class Box
{ double width;
double height;
double depth;
}
class BoxDemo {
public static void main(String args[])
{ Box mybox = new Box();
double vol;
// assign values to mybox's instance variables
mybox.width = 10;
mybox.height = 20;
mybox.depth = 15;
// compute volume of box
vol = mybox.width * mybox.height * mybox.depth;
System.out.println("Volume is " + vol);
}
}
Output:
Volume is 3000.0
Example1: BoxDemo.java
class Box // compute volume of box
{ vol = mybox.width * mybox.height *
double width; mybox.depth;
double height; System.out.println("Volume is " + vol);
double depth; }
} }
class BoxDemo
{
public static void main(String args[])
{ Output:
Box mybox = new Box(); Volume is 3000.0
double vol;
mybox.width = 10;
mybox.height = 20;
mybox.depth = 15;
Example 2
// This program declares two Box objects.
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;
// assign values to mybox1's instance variables
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
/* assign different values to mybox2's instance variables */
mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;
// compute volume of first box
vol = mybox1.width * mybox1.height * mybox1.depth;
System.out.println("Volume is " + vol);
// compute volume of second box
vol = mybox2.width * mybox2.height * mybox2.depth;
System.out.println("Volume is " + vol); }
}Output:
Volume is 3000.0
Volume is 162.0
Example 2
mybox2.height = 6;
// This program declares two Box objects. mybox2.depth = 9;
class Box
{ // compute volume of first box
double width; vol = mybox1.width * mybox1.height * mybox1.depth;
double height; System.out.println("Volume is " + vol);
double depth;
} // compute volume of second box
class BoxDemo2 vol = mybox2.width * mybox2.height * mybox2.depth;
{ System.out.println("Volume is " + vol); }
public static void main(String args[]) }
{
Box mybox1 = new Box();
Box mybox2 = new Box(); Output:
double vol; Volume is 3000.0
// assign values to mybox1's instance variables Volume is 162.0
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
/* assign different values to mybox2's instance variables */
mybox2.width = 3;
Declaring Objects
•The first line declares mybox as a reference to an object of type Box.
At this point, mybox does not yet refer to an actual object.

•The next line allocates an object and assigns a reference to it to


mybox. After the second line executes, we can use mybox as if it
were a Box object. But in reality, mybox simply holds, in essence,
the memory address of the actual Box object.
CONSTRUCTORS
Constructors are special member functions whose task is to initialize the objects of its class.
 It is a special member function, it has the same as the class name.
 Java constructors are invoked when their objects are created. It is named such because, it constructs the value, that is
provides data for the object and are used to initialize objects.
 Every class has a constructor when we don't explicitly declare a constructor for any java class the compiler creates a
default constructor for that class which does not have any return type.
 The constructor in Java cannot be abstract, static, final or synchronized and these modifiers are not allowed for the
constructor.

There are two types of constructors:


1. Default constructor (no-arg constructor)
2. Parameterized constructor
Default constructor (no-arg constructor)

A constructor having no parameter is known


as default constructor and no-arg constructor. class BoxDemo6 {
public static void main(String args[])
class Box {
{ double width; // declare, allocate, and initialize Box objects
double height;
double depth; Box mybox1 = new Box();
// This is the constructor for Box. Box mybox2 = new Box();
Box()
{ double vol;
width = 10; // get volume of first box vol = mybox1.volume();
height = 10; System.out.println("Volume is " + vol);
depth = 10; // get volume of second box vol = mybox2.volume();
} System.out.println("Volume is " + vol);
// compute and return volume }
double volume() }
{
return width * height * depth;} Output:
} Volume is 1000.0
Volume is 1000.0
Parameterized Constructors
A constructor which has a specific number of class BoxDemo7 {
parameters is called parameterized constructor. public static void main(String args[])
Parameterized constructor is used to provide {
Box mybox1 = new Box(10, 20, 15);
different values to the distinct objects.
Box mybox2 = new Box(3, 6, 9);
double vol;
Example:
vol = mybox1.volume();
class Box
System.out.println("Volume is " + vol);
{ double width; double height; double depth;
vol = mybox2.volume();
Box(double w, double h, double d)
System.out.println("Volume is " + vol);
{
}
width = w;
}
height = h;
depth = d;
}
Output:
double volume()
Volume is 3000.0
{
Volume is 162.0
return width * height * depth;
}
}
Overloading Constructors
Example {
class Box public static void main(String args[])
{ {
double width; double height; double depth; Box mybox1 = new Box(10, 20, 15);
Box(double w, double h, double d) Box mybox2 = new Box();
{ Box mycube = new Box(7); double vol;
width = w; height = h; depth = d;
} // get volume of first box vol = mybox1.volume();
Box() System.out.println("Volume of mybox1 is " + vol);
{
width = -1; // get volume of second box vol = mybox2.volume();
height = -1; System.out.println("Volume of mybox2 is " + vol);
depth = -1;
} // get volume of cube vol = mycube.volume();
Box(double len) System.out.println("Volume of mycube is " + vol);
{ }
width = height = depth = len; }
} Output:
double volume() Volume of mybox1 is 3000.0
{ Volume of mybox2 is -1.0
return width * height * depth; Volume of mycube is 343.0
}

class OverloadCons
METHODS
Syntax:
type name(parameter-list)
{
// body of method
}
• type specifies the type of data returned by the method. This can be any valid type, including class types
that you create.
• 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:
Syntax: return value;
METHODS
// This program includes a method inside the box class.
class Box { mybox1.volume();
double width; mybox2.volume();
double height; }
double depth; }
Output:
void volume() { Volume is 3000.0
System.out.print("Volume is "); Volume is 162.0
System.out.println(width * height * depth);
} The first line here invokes the volume( ) method on mybox1.
} That is, it calls volume( ) relative to the mybox1 object, using the
class BoxDemo3 { object’s name followed by the dot operator.
public static void main(String args[]) {
Box mybox1 = new Box(); Thus, the call to mybox1.volume( ) displays the volume of the
Box mybox2 = new Box(); box defined by mybox1, and the call to mybox2.volume( )
displays the volume of the box defined by mybox2. Each time
mybox1.width = 10; volume( ) is invoked, it displays the volume for the specified
mybox1.height = 20; box.
mybox1.depth = 15;

mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;
Method- Returning a Value
Example: // get volume of first box
class Box { vol = mybox1.volume();
double width; System.out.println("Volume is " + vol);
double height;
double depth; // get volume of second box
double volume() vol = mybox2.volume();
{ System.out.println("Volume is " + vol);
return width * height * depth; }
} }
} Output:
class BoxDemo4 { Volume is 3000
public static void main(String args[]) Volume is 162
{
Box mybox1 = new Box();
Box mybox2 = new Box(); There are two important things to understand about returning
double vol; values:
• The type of data returned by a method must be compatible
mybox1.width = 10; with the return type specified by the method.
mybox1.height = 20; • The variable receiving the value returned by a method (such
mybox1.depth = 15; as vol, in this case) must also be compatible
with the return type specified for the method.
mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;
Method That Takes Parameters

{
Example: Box mybox1 = new Box();
// This program uses a parameterized method. Box mybox2 = new Box();
class Box { double vol;
double width; // initialize each box
double height; mybox1.setDim(10, 20, 15);
double depth; mybox2.setDim(3, 6, 9);
// get volume of first box
// compute and return volume
double volume() { vol = mybox1.volume();
return width * height * depth; System.out.println("Volume is " + vol);
} // get volume of second box
vol = mybox2.volume();
// sets dimensions of box System.out.println("Volume is " + vol);
void setDim(double w, double h, double d) { }
width = w; }
height = h; Output:
depth = d; Volume is 3000
} Volume is 162
}
class BoxDemo5 {
public static void main(String args[])
The this Keyword

• this keyword is used to to refer to the object that invoked it. Student stud1 = new Student(01,"Tarun");
• this can be used inside any method to refer to Student stud2 = new Student(02,"Barun");
the current object.
• this is always a reference to the object on which stud1.display();
the method was invoked. stud2.display();
• this() can be used to invoke current class constructor. }
}
Example:
class Student
{
int id;
String name; Output:
student(int id, String name) 01 Tarun
{ 02 Barun
this.id = id;
this.name = name;
}
void display()
{
System.out.println(id+" "+name);
}
public static void main(String args[])
{
Overloading Methods
When two or more methods within the same class double test(double a) {
that have the same name, but their parameter declarations System.out.println("double a: " + a);
are different. The methods are said to be overloaded, and return a*a;
the process is referred to as method overloading. }
Method overloading is one of the ways }
that Java supports polymorphism. class Overload {
public static void main(String args[]) {
There are two ways to overload the method in java OverloadDemo ob = new OverloadDemo();
1. By changing number of arguments double result;
2. By changing the data type // call all versions of test()
ob.test();
Example: ob.test(10);
// Demonstrate method overloading. ob.test(10, 20);
class OverloadDemo { result = ob.test(123.25);
void test() { System.out.println("Result of ob.test(123.25): " + result);
System.out.println("No parameters"); }
} }
// Overload test for one integer parameter. Output:
void test(int a) { No parameters
System.out.println("a: " + a); 20
} a: 10
// Overload test for two integer parameters. a and b: 10 20
void test(int a, int b) { double a: 123.25
System.out.println("a and b: " + a + " " + b); Result of ob.test(123.25): 15190.5625
Passing and Returning Objects

 Although Java is strictly passed by value, the precise effect differs between whether
a primitive type or a reference type is passed. When we pass a primitive type to a
method, it is passed by value.
 But when we pass an object to a method, the situation changes dramatically, because
objects are passed by what is effectively call-by-reference.
 Java does this interesting thing that’s sort of a hybrid between pass-by-value and
pass-by-reference.
 While creating a variable of a class type, we only create 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 reflect the object used as an argument.

 Example
From the method side, a reference of type o with a name a is declared and it’s
initially assigned to null.
As we call the method equalTo, the reference ‘o’ will be assigned to the object which is
passed as an argument, i.e. ‘o’ will refer to ‘ob2’ as the following statement execute.
System.out.println("ob1 == ob2: " + ob1.equalTo(ob2));

Now as we can see, equalTo method is called on ‘ob1’ , and ‘o’ is referring to ‘ob2’. Since
values of ‘a’ and ‘b’ are same for both the references, so if(condition) is true, so boolean
true will be return.
• if(o.a == a && o.b == b)
• Again ‘o’ will reassign to ‘ob3’ as the following statement execute.
• System.out.println("ob1 == ob3: " + ob1.equalTo(ob3));
the equal To method is called on ‘ob1’ , and ‘o’ is referring to ‘ob3’. Since values
of ‘a’ and ‘b’ are not the same for both the references, so if(condition) is false, so
else block will execute, and false will be returned.
// Java Program to Demonstrate Objects Passing to Methods.
// Class
// Helper class
class ObjectPassDemo {
int a, b;
// Constructor
ObjectPassDemo(int i, int j)
{
a = i;
b = j;
}
// Method
boolean equalTo(ObjectPassDemo o)
{
// Returns true if o is equal to the invoking
// object notice an object is passed as an
// argument to method
return (o.a == a && o.b == b);
}}
// Main class
public class GFG {
// Main driver method
public static void main(String args[])
{
// Creating object of above class inside main()
ObjectPassDemo ob1 = new ObjectPassDemo(100, 22);
ObjectPassDemo ob2 = new ObjectPassDemo(100, 22);
ObjectPassDemo ob3 = new ObjectPassDemo(-1, -1);

// Checking whether object are equal as custom


// values
// above passed and printing corresponding boolean
// value
System.out.println("ob1 == ob2: “+ ob1.equalTo(ob2));
System.out.println("ob1 == ob3: “+ ob1.equalTo(ob3));
}
}

Output:
ob1 == ob2: true ob1 == ob3: false
Returning Objects

• In java, a method can return any type of data, including objects. For example, in the following program,
the incrByTen( ) method returns an object in which the value of an (an integer variable) is ten greater than it is in the
invoking object.
• // Java Program to Demonstrate Returning of Objects

// Class 1
class ObjectReturnDemo {
int a;

// Constructor
ObjectReturnDemo(int i) { a = i; }

// Method returns an object


ObjectReturnDemo incrByTen()
{
ObjectReturnDemo temp = new ObjectReturnDemo(a + 10);
return temp;
}
}
• In the recursive program, the solution to the base case is provided and the solution to the
bigger problem is expressed in terms of smaller problems.
int fact(int n)
{
if (n < = 1) // base case
return 1;
else
return n*fact(n-1);
}
• In the above example, the base case for n < = 1 is defined and the larger value of a
number can be solved by converting it to a smaller one till the base case is reached.
Working of Recursion
 The idea is to represent a problem in terms of one or more smaller sub-problems and add
base conditions that stop the recursion.
 For example, we compute factorial n if we know the factorial of (n-1).
 The base case for factorial would be n = 0. We return 1 when n = 0.
Java Recursion Programs

Factorial Using Recursion


 The classic example of recursion is the computation of the factorial of a number.
The factorial of a number N is the product of all the numbers between 1 and N. The
below-given code computes the factorial of the numbers: 3, 4, and 5.
 3= 3 *2*1 (6)
 4= 4*3*2*1 (24)
 5= 5*3*2*1 (120)
// Java Program to implement Driver Class
// Factorial using recursion class Recursion {
class GFG { // Main function
// recursive method public static void main(String[] args)

int fact(int n) {
GFG f = new GFG();
{
System.out.println("Factorial of 3 is “+ f.fact(3));
int result;
System.out.println("Factorial of 4 is “+ f.fact(4));
if (n == 1)
System.out.println("Factorial of 5 is “+ f.fact(5));
return 1;
}
result = fact(n - 1) * n;
}
return result;
}
} Factorial of 3 is 6 Factorial of 4 is 24 Factorial of 5 is 120

//
Direct or Indirect recursion

• A function fun is called direct recursive if it calls the same function fun. A function fun is called
indirect recursive if it calls another function say fun_new and fun_new calls fun directly or
indirectly.
• i) . Direct recursion:
• void directRecFun()
• { // Some code.... directRecFun();
• // Some code... }
• Ii) Indirect recursion:
• void indirectRecFun1()
• { // Some code... indirectRecFun2(); // Some code... }
• void indirectRecFun2()
• { // Some code... indirectRecFun1(); // Some code... }
Access Control
Access Control in Java refers to the mechanism used to restrict or allow access to
certain parts of a Java program, such as classes, methods, and variables.
Access control determines which classes and objects can access specific codes or data
within a program.
Access Control Modifiers in Java

Access control modifiers in Java are keywords that can be used to control access to classes, fields,
and methods.
Access control modifiers determine the level of access that other classes or objects have to a
particular class, field, or method.

1. Private Access Control Modifier in Java

The private access control modifier in Java is used to restrict access to a class member to only
within the same class.
This means that a private member cannot be accessed from outside of the class, including from
any subclass of the class.
This helps to promote encapsulation and information hiding in the class.
The syntax for using the private access control modifier in Java is as follows:

Explanation: In the above code snippet, we have declared a private instance variable called
myPrivateVar and a private method called myPrivateMethod().
These members can only be accessed from within the same class.
2. Default Access Control Modifier in Java

The default or package-private access control modifier in Java is used when no access modifier is
specified.
It makes the class member accessible only within the same package. This means that a default
member cannot be accessed from outside of the package, including from any subclass of the class,
if it is defined in a different package.
The syntax for using the default access control modifier in Java is as follows:

Explanation: In the above code snippet, we have declared a default


instance variable called myDefaultVar and a default method called
myDefaultMethod(). These members can be accessed from within the
same package only.
• Protected Access Control Modifier in Java
• The protected access control modifier in Java is used to provide access to a class
member within the same class, any subclass of the class, or any class within the same
package.
• This means that a protected member can be accessed from within the same class, any
subclass of the class, or any class within the same package, but cannot be accessed from
any class outside of the package, even if it is a subclass of the protected class.
• The syntax for using the protected access control modifier in Java is as follows:
• Explanation: In the above code snippet, we have declared a protected instance variable called
myProtectedVar and a protected method called myProtectedMethod(). These members can be accessed
from within the same class, any subclass of the class, or any class within the same package.
• Public Access Control Modifier in Java
• The public access control modifier in Java is used to provide unrestricted access to a class member from
any other class, including classes that are not in the same package.
• This means that a public member can be accessed from any other class in the program.
• The syntax for using the public access control modifier in Java is as follows:
• In the above code snippet, we have declared a public instance variable called
myPublicVar and a public method called myPublicMethod().
• These members can be accessed from any other class in the program.
• Best Practices for Using Access Control in Java
1. Use the most restrictive access control possible
2. Use public access control with caution
3. Use access control modifiers consistently
4. Avoid using default access control outside of a package
5. Document access control modifiers
Static Members

• In Java, static members are those which belongs to the class and you can access these
members without instantiating the class.
• The static keyword can be used with methods, fields, classes (inner/nested), blocks.
• Static Methods − You can create a static method by using the keyword static. Static
methods can access only static fields, methods. To access static methods there is no need
to instantiate the class, you can do it just using the class name as −
public class MyClass
{
public static void sample()
{
System.out.println("Hello");
}
public static void main(String args[])
{ MyClass.sample(); } }

Output:
Hello
Static Fields − You can create a static field by using the keyword static. The static fields have the
same value in all the instances of the class. These are created and initialized when the class is loaded
for the first time. Just like static methods you can access static fields using the class name (without
instantiation).

public class MyClass


{
public static int data = 20;
public static void main(String args[])
{
System.out.println(MyClass.data); }
}
O/P: 20
• Static Blocks − These are block of codes with a static keyword. In general, these
are used to initialize the static members. JVM executes static blocks before the
main method at the time of class loading.
public class MyClass
{
Static {
System.out.println("Hello this is a static block"); }
public static void main(String args[]){
System.out.println("This is main method"); } }
O/P:
Hello this is a static block
This is main method
Final variables in Java
• In Java, we can use final keyword with variables, methods, and classes. When the final keyword is
used with a variable of primitive data types such as int, float, etc), the value of the variable cannot
be changed.

// Java Program to illustrate Use of Final Keyword


// With Primitive Datatypes
class GFG {
public static void main(String args[])
{
// Final primitive variable
final int i = 10;
i = 30;
// Error will be generated above
}
}
Inner Class
• Java inner class or nested class is a class that is declared inside the class or interface.
• We use inner classes to logically group classes and interfaces in one place to be more
readable and maintainable.
• Additionally, it can access all the members of the outer class, including private data
members and methods.
Syntax
class Java_Outer_class{
//code
class Java_Inner_class{
//code
}
}
Types of Inner Classes
Command Line Arguments

• The java command-line argument is an argument i.e. passed at the time of running the
java program.
• The arguments passed from the console can be received in the java program and it can
be used as an input.
• So, it provides a convenient way to check the behavior of the program for the different
values.
• You can pass N (1,2,3 and so on) numbers of arguments from the command prompt
Simple example of command-line argument in java
class CommandLineExample{
public static void main(String args[]){
System.out.println("Your first argument is: "+args[0]);
}
}
• compile by > javac CommandLineExample.java
• run by > java CommandLineExample sonoo

Output: Your first argument is: sonoo

Example of command-line argument that prints all the values

class A{
public static void main(String args[]){
for(int i=0;i<args.length;i++)
System.out.println(args[i]);
} }
• compile by > javac A.java
• run by > java A sonoo jaiswal 1 3 abc

Output: sonoo jaiswal 1 3 abc


Variable Argument (Varargs)

• The varrags allows the method to accept zero or muliple arguments.


• Before varargs either we use overloaded method or take an array as the
method parameter but it was not considered good because it leads to the
maintenance problem.
• If we don't know how many argument we will have to pass in the method,
varargs is the better approach.

Syntax of varargs:

return_type method_name(data_type... variableName){}


class VarargsExample1{
static void display(String... values){
System.out.println("display method invoked ");
}
public static void main(String args[]){
display();//zero argument
display("my","name","is","varargs");//four arguments
} }
Output: display method invoked
display method invoked
INHERITANCE

• Inheritance is a mechanism wherein one class inherits the property of another.


• A class that is derived from another class is called a subclass (also a derived class, extended class, or child
class).
• The class from which the subclass is derived is called a superclass (also a base class or a parent class).
Advantages:

• Code Reusability: The code written in the Superclass is common to all subclasses. Child classes can
directly use the parent class code.

• Method Overriding: Method Overriding is achievable only through Inheritance. It is one of the ways by
which Java achieves Run Time Polymorphism.

• Abstraction: The concept of abstract where we do not have to provide all details is achieved through
inheritance. Abstraction only shows the functionality to the user.
}

INHERITANCE

• Syntax:
class Parent
{
//Data Members
//Methods
}
class Child extends Parent
{
//Data Members
//Methods
}
TYPES OF INHERITANCE
Single Inheritance

• When a class inherits only one another class, we call it


single inheritance or single level inheritance.
• Syntax:
class A
{
}
class B extends A
{
}
Multilevel Inheritance

• When three or more than three classes inherits in


same chain or level, we call it multilevel
inheritance. The number of classes in multilevel
inheritance is not limited to three classes, it can go up
to any number of classes in the same level or
inheritance chain.
• Syntax:
class A
{
}
class B extends A
{
}
class C extends B
{
}
Hierarchical Inheritance

• When two or more than two classes inherits a single class, we call it hierarchical inheritance. In java a class can
be inherited by any number of classes, so in hierarchical inheritance, there can be any number of child classes, it's
not limited to two classes only. The program below shows an example of hierarchical inheritance.
• Syntax:
class A
{
}
class B extends A
{
}
class C extends A
{
}
Hierarchical Inheritance
Multiple Inheritance

• When a class inherits the features from more than one parent, we call it multiple inheritance.
• Multiple inheritance in java is not supported using classes, which means a class can not extend more than one
class.
• Multiple inheritance in java is supported through interfaces only, which means a class can inherit the features
from more than one interfaces. Java allows a class to implement any number of interfaces. The program below
shows an example of multiple inheritance.
• Syntax:
interface A
{
}
interface B
{
}
class C implements A,B
{
}
Multiple Inheritance
Hybrid Inheritance

• Hybrid inheritance, as the name itself suggests, it is a mix of two or more


inheritance types.
• The hybrid inheritance is a mix of hierarchical and multiple inheritance
but it's not limited to that only, it may contain the mix of any other
inheritance types as well.
• If hybrid inheritance contains multiple inheritance, then it won't be
supported through classes, as java doesn't support multiple inheritance
using classes.
• It would be supported through interfaces only.
Super Keyword

• Super is a keyword that is used to call a function or method in the superclass.


• This will be defined inside the sub-class.
• Methods that are only public and protected can be called by using this keyword.
• In other words, Private methods and static methods cannot be called using this.
• The super keyword in java can also be used in order to call the constructors of the parent class.
• Syntax:
super.<<method-name>> or super([0 or more arguments]);
Super Keyword
To refer immediate parent class instance variable

• We can use super keyword to access the data member or field of parent class. This scenario occurs when a
derived class and base class has same data members.

Output:

Maximum Speed: 120


To invoke immediate parent class method

• This is used when we want to call parent


class method. So whenever a parent and child
class have same named methods then to
resolve ambiguity we use super keyword. In
other words, it is used if method is
overridden.

Output
This is student class
This is person class
super() can be used to invoke immediate parent class constructor

• super keyword can also be used to invoke the


parent class constructor. One more important
thing is that, ‘’super’ can call both parametric
as well as non parametric constructors
depending upon the situation.

Output
Person class Constructor
Student class Constructor
Protected Members

• A Java protected keyword is an access modifier. It can be assigned to variables, methods, constructors and
inner classes.

Key Points:
1. Accessing in the same class
2. Accessing in other classes of the same package
3. Accessing protected members of a class in its subclass in the same package
4. Accessing another class in a different package
5. Accessing in sub-class in a different package
Case 1: Accessing protected members in the same class
Case 2: Accessing protected members in other classes of the same package

We can access protected members of a class in another class that is present in the same package.
Case 3: Accessing protected members of a class in its subclass in the same package

We can access protected members of a class in its subclass if both are present in the same package.

class Sample
{
static protected String title = “JAVA";
protected int year = 2021;
protected void printYear()
{ Output
System.out.println("Its "+year+" !!");
} 2021
} Its 2021 !!
// Class 2 JAVA
public class Test extends Sample
{
public static void main(String[] args)
{
Sample sample = new Sample();
System.out.println(sample.year);
sample.printYear();
System.out.println(Sample.title);
}
}
Case 4: Accessing protected members in another class in a different package

We cannot access the protected members of a class in a class (non-subclass) that is present in a
different package.

package package2;
// Importing above package
// Package 1 import package1.Sample; Output:
package package1;
// Main class error: year has protected access in Sample
// Main class public class Test { System.out.println(sample.year);
public class Sample {
^
// Main driver method error: printYear() has protected access in Sample
static protected String title = “JAVA"; public static void main(String[] args) { sample.printYear();
protected int year = 2021;
^
Sample sample = new Sample(); error: title has protected access in Sample
// Protected method System.out.println(sample.year); System.out.println(Sample.title);
protected void printYear() { sample.printYear(); ^
System.out.println("Its "+year+" !!"); System.out.println(Sample.title);
} }
} }
Case 5: Accessing protected members in sub-class in a
different package
We can access protected members of a class in its subclass present in a different package. We will create
two classes. Sample class in package1 and Child class in package2. Child class extends Sample class.

package package2;

import package1.Sample;
package package1;
public class Child extends Sample
// Class {
public class Sample { void helper() Output
{
// Protected attributes System.out.println(year); 2021
static protected String title = “JAVA"; printYear(); Its 2021 !!
protected int year = 2021; System.out.println(Sample.title); JAVA
protected void printYear() }
{ public static void main(String[] args)
System.out.println("Its " + year + " !!"); {
} Child child = new Child();
} child.helper();
}
}
Calling Order of Constructors

Order of Execution of Constructors in Java Inheritance:

When an object of a class is instantiated, the constructors of its superclass and then its own
constructors are executed. This is because constructors of the superclass are responsible for
initializing the state of the superclass. The state of the superclass can be used by the subclass to
initialize its own state.
Order of Execution in Single Level Inheritance
Order of Execution in Multi Level Inheritance
Method Overriding in Java

• If subclass (child class) has the same method as declared in the parent class, it is known as method
overriding in Java.
• In other words, If a subclass provides the specific implementation of the method that has been declared
by one of its parent class, it is known as method overriding.
Usage of Java Method Overriding
• Method overriding is used to provide the specific implementation of a method which is already provided
by its superclass.
• Method overriding is used for runtime polymorphism
Rules for Java Method Overriding
• The method must have the same name as in the parent class
• The method must have the same parameter as in the parent class.
• There must be an IS-A relationship (inheritance).
Example of Java Method Overriding

Consider a scenario where Bank is a class that provides functionality to get the rate of interest.
However, the rate of interest varies according to banks. For example, SBI, ICICI and AXIS banks
could provide 8%, 7%, and 9% rate of interest.
Java Program to demonstrate the real scenario of Java
Method Overriding
//where three classes are overriding the method of a parent class.
//Creating a parent class.
class Bank{
int getRateOfInterest(){return 0;}
}
//Creating child classes.
class SBI extends Bank{
int getRateOfInterest(){return 8;}
}
class ICICI extends Bank{
int getRateOfInterest(){return 7;}
}
class AXIS extends Bank{
int getRateOfInterest(){return 9;}
}
Java Program to demonstrate the real scenario of Java
Method Overriding(Contd.,)

//Test class to create objects and call the methods


class Test2{
public static void main(String args[]){
SBI s=new SBI();
ICICI i=new ICICI();
AXIS a=new AXIS();
System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
}
}
Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9
Difference between method overloading and method overriding in
java

No. Method Overloading Method Overriding


1) Method overloading is used to increase the Method overriding is used to provide the
readability of the program. specific implementation of the method that is
already provided by its super class.

2) Method overloading is performed within Method overriding occurs in two classes that
class. have IS-A (inheritance) relationship.

3) In case of method overloading, parameter In case of method overriding, parameter must


must be different. be same.
4) Method overloading is the example Method overriding is the example of run time
of compile time polymorphism. polymorphism.
5) In java, method overloading can't be Return type must be same or covariant in
performed by changing return type of the method overriding.
method only. Return type can be same or
different in method overloading. But you
must have to change the parameter.
Object class in Java

The Object class is the parent class of all the classes in java by default. In other words, it is the topmost class
of java.

The Object class is beneficial if you want to refer any object whose type you don't know.

Notice that parent class reference variable can refer the child class object, know as upcasting.

Let's take an example, there is getObject() method that returns an object but it can be of any type like
Employee, Student etc., we can use Object class reference to refer that object.

Example:

Object obj=getObject();//we don't know what object will be returned from this method

The Object class provides some common behaviors to all the objects such as object can be compared, object can be cloned,
object can be notified etc.
Object class in Java(Contd.,)
Methods of Object class
Method Description
public final Class getClass() returns the Class class object of this object. The Class class can
further be used to get the metadata of this class.

public int hashCode() returns the hashcode number for this object.
public boolean equals(Object obj) compares the given object to this object.
protected Object clone() throws creates and returns the exact copy (clone) of this object.
CloneNotSupportedException
public String toString() returns the string representation of this object.
public final void notify() wakes up single thread, waiting on this object's monitor.

public final void notifyAll() wakes up all the threads, waiting on this object's monitor.

public final void wait(long timeout)throws causes the current thread to wait for the specified milliseconds,
InterruptedException until another thread notifies (invokes notify() or notifyAll() method).

public final void wait(long timeout,int nanos)throws causes the current thread to wait for the specified milliseconds and
InterruptedException nanoseconds, until another thread notifies (invokes notify() or
notifyAll() method).

public final void wait()throws InterruptedException causes the current thread to wait, until another thread notifies
(invokes notify() or notifyAll() method).

protected void finalize()throws Throwable is invoked by the garbage collector before object is being garbage
collected.
Abstract class in Java

Abstraction in Java
• Abstraction is a process of hiding the implementation details and showing only functionality to the user.

• Another way, it shows only essential things to the user and hides the internal details, for example, sending
SMS where you type the text and send the message. You don't know the internal processing about the
message delivery.

• Abstraction lets you focus on what the object does instead of how it does

• There are two ways to achieve abstraction in java

1. Abstract class (0 to 100%)


2. Interface (100%)
Abstract class in Java(Contd.,)

Abstract class in Java


A class which is declared as abstract is known as an abstract class. It can have abstract and non-abstract methods. It needs to be extended
and its method implemented. It cannot be instantiated.

Points to Remember
An abstract class must be declared with an abstract keyword.
It can have abstract and non-abstract methods.
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.

Example of abstract class


abstract class A{}

Example of abstract method


abstract void printStatus();//no method body and abstract
Example of Abstract Class

In this example, Shape is the abstract class, and its implementation is provided by the
Rectangle and Circle classes.

Mostly, we don't know about the implementation class (which is hidden to the end user), and
an object of the implementation class is provided by the factory method.

A factory method is a method that returns the instance of the class. We will learn about the
factory method later.

In this example, if you create the instance of Rectangle class, draw() method of Rectangle
class will be invoked.
Example of Abstract Class(Contd.,)

abstract class Shape{


abstract void draw();
}
//In real scenario, implementation is provided by others i.e. unknown by end user
class Rectangle extends Shape{
void draw(){System.out.println("drawing rectangle");}
}
class Circle1 extends Shape{
void draw(){System.out.println("drawing circle");}
}
//In real scenario, method is called by programmer or user
class TestAbstraction1{
public static void main(String args[]){
Shape s=new Circle1();//In a real scenario, object is provided through method, e.g., getShape() method
s.draw();
} Output :drawing circle
}
Example of an abstract class that has abstract and non-
abstract methods
abstract class Bike{
Bike(){System.out.println("bike is created");}
abstract void run();
void changeGear(){System.out.println("gear changed");}
}
//Creating a Child class which inherits Abstract class
class Honda extends Bike{
void run(){System.out.println("running safely..");}
}
//Creating a Test class which calls abstract and non-abstract methods
class TestAbstraction2{
public static void main(String args[]){ Output: bike is created
Bike obj = new Honda(); running safely . .
obj.run(); gear changed
obj.changeGear();
} }
Interface in Java

An interface in Java is a blueprint of a class. It has static constants and abstract methods.

The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods in the Java interface, not method body. It is
used to achieve abstraction and multiple inheritance in Java.

In other words, you can say that interfaces can have abstract methods and variables. It cannot have a method body.

Java Interface also represents the IS-A relationship.

It cannot be instantiated just like the abstract class.

Since Java 8, we can have default and static methods in an interface.

Since Java 9, we can have private methods in an interface.

Why use Java interface?


There are mainly three reasons to use interface. They are given below.

1. It is used to achieve abstraction.


2. By interface, we can support the functionality of multiple inheritance.
3. It can be used to achieve loose coupling.
How to declare an interface?

interface <interface_name>{
// declare constant fields
// declare methods that abstract
// by default.
}
The relationship between classes and interfaces
As shown in the figure given below, a class extends another class, an interface extends another interface, but a class implements an
interface.
Example of Interface

interface Bank{
float rateOfInterest();
}
class SBI implements Bank{
public float rateOfInterest(){return 9.15f;}
}
class PNB implements Bank{
public float rateOfInterest(){return 9.7f;}
}
class TestInterface2{
public static void main(String[] args){
Bank b=new SBI();
System.out.println("ROI: "+b.rateOfInterest());
}} Output: ROI:9.15
Multiple inheritance in Java by interface

If a class implements multiple interfaces, or an interface extends multiple interfaces, it is known as multiple
inheritance.
Example of Multiple Inheritance

interface Printable{
void print();
}
interface Showable{
void show();
}
class A7 implements Printable,Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}

public static void main(String args[]){


A7 obj = new A7();
obj.print();
obj.show();
}
}

You might also like