Ce diaporama a bien été signalé.
Nous utilisons votre profil LinkedIn et vos données d’activité pour vous proposer des publicités personnalisées et pertinentes. Vous pouvez changer vos préférences de publicités à tout moment.
Introduction To Java
Programming Language
Lecture No.11
Notes By Adil Aslam
My Email Address is : adilaslam5959@gmail.com
About Me
Introduction to Java Programming Language
Notes By Adil Aslam
i am Student of BSCS
My email address:
adilaslam595...
Introduction to Java Programming Language
Notes By Adil Aslam
Inheritance in Java
Inheritance in Java
• Inheritance in java is a mechanism in which one
object acquires all the properties and behaviors of
...
Inheritance in Java
• Inheritance represents the IS-A relationship, also
known as parent-child relationship.
• Why use Inh...
Inheritance in Java
Introduction to Java Programming Language
Notes By Adil Aslam
Inheritance in Java
• Important points
• In the inheritance the class which is give data
members and methods is known as b...
Inheritance in Java
No Term Definition
1 Inheritance
Inheritance is a process
where one object acquires
the properties of ...
Example – Inheritance
Introduction to Java Programming Language
Notes By Adil Aslam
Person
Teacher
DoctorStudent
Example – Inheritance
Introduction to Java Programming Language
Notes By Adil Aslam
Shape
Circle
TriangleLine
Example – “IS A” Relationship
Introduction to Java Programming Language
Notes By Adil Aslam
Person
name
age
gender
eat
wal...
Example – “IS A” Relationship
Introduction to Java Programming Language
Notes By Adil Aslam
Shape
color
coord
draw
rotate
...
Reuse with Inheritance
• Main purpose of inheritance is reuse
• We can easily add new classes by inheriting
from existing ...
Example Reuse
Introduction to Java Programming Language
Notes By Adil Aslam
Shape
color
coord
draw
rotate
setColor
Circle
...
Example Reuse-1
Introduction to Java Programming Language
Notes By Adil Aslam
Person
name
age
gender
eat
walk
Teacher
desi...
Example Reuse-2
Introduction to Java Programming Language
Notes By Adil Aslam
Person
name
age
gender
eat
walk
Teacher
desi...
Concepts Related with Inheritance
Generalization
Subtyping (extension)
Specialization (restriction)
Introduction to Jav...
Concepts Related with Inheritance
 Generalization
• In OO models, some classes may have common
characteristics
• We extra...
Example – Generalization
Introduction to Java Programming Language
Notes By Adil Aslam
Circle
color
vertices
radius
move
s...
Example – Generalization
Introduction to Java Programming Language
Notes By Adil Aslam
Shape
color
vertices
move
setColor
...
Example – Generalization
Introduction to Java Programming Language
Notes By Adil Aslam
Teacher
name
age
gender
designation...
Example – Generalization
Introduction to Java Programming Language
Notes By Adil Aslam
Person
name
age
gender
eat
walk
Tea...
Sub-typing & Specialization
• We want to add a new class to an existing
model
• Find an existing class that already
implem...
Sub-typing (Extension)
• Sub-typing means that derived class is
behaviourally compatible with the base class
• Behavioural...
Example –Sub-typing (Extension)
Introduction to Java Programming Language
Notes By Adil Aslam
Person
name
age
gender
eats
...
Example –Sub-typing (Extension)
Introduction to Java Programming Language
Notes By Adil Aslam
Shape
color
vertices
setColo...
Specialization (Restriction)
• Specialization means that derived class is
behaviourally incompatible with the base
class
•...
Example – Specialization (Restriction)
Introduction to Java Programming Language
Notes By Adil Aslam
Person
age : [0..100]...
Example – Specialization (Restriction)
Introduction to Java Programming Language
Notes By Adil Aslam
IntegerSet
…
NaturalS...
Inheritance in Java
• Inheritance in Java
• Inheritance in Java is done using
• extends – In case of Java class and abstra...
Inheritance in Java
• Syntax of Inheritance
• The extends keyword indicates that you are making
a new class that derives f...
Inheritance in Java
• extends Keyword
• extends is the keyword used to inherit the
properties of a class. Following is the...
Inheritance in Java
• IS-A Relationship with Example
• IS-A is a way of saying : This object is a type of that
object.
Int...
Inheritance in Java
• Conclusions from above Example :
• Vehicle is the superclass of TwoWheeler class.
• Vehicle is the s...
Inheritance in Java
• Conclusions from above Example :
• Vehicle is the superclass of TwoWheeler class.
• Vehicle is the s...
Inheritance in Java
• IS-A Relationship
• Based on the above example, in Object-Oriented
terms which is base Class and whi...
Inheritance in Java
• Based on the above example, in Object-Oriented terms,
the following are:
• Animal is the superclass ...
Inheritance in Java
• Please Note:
• In inheritance Parent Class and Child Class having
multiple names, List of the name a...
Simple Example of Inheritance
class Parent
{
public void p1() {
System.out.println("Parent method");
}
}
public class Chil...
Simple Example of Inheritance
class Parent
{
public void p1() {
System.out.println("Parent method");
}
}
public class Chil...
Simple Example of Inheritance
class Parent
{
public void p1() {
System.out.println("Parent method");
}
}
public class Chil...
Simple Example of Inheritance
class Parent
{
public void p1() {
System.out.println("Parent method");
}
}
public class Chil...
Simple Example of Inheritance
class Parent
{
public void p1() {
System.out.println("Parent method");
}
}
public class Chil...
Simple Example of Inheritance
class Parent
{
public void p1() {
System.out.println("Parent method");
}
}
public class Chil...
Simple Example of Inheritance
class Parent
{
public void p1() {
System.out.println("Parent method");
}
}
public class Chil...
Simple Example of Inheritance
class Parent
{
public void p1() {
System.out.println("Parent method");
}
}
public class Chil...
Simple Example of Inheritance
class Parent
{
public void p1() {
System.out.println("Parent method");
}
}
public class Chil...
Explanation of Previous Program
• When child class inherit the propertied of parent class
the child class look like this (...
Another example of Inheritance
class Parent
{
int id=11;
String name="Adil";
}
public class Child extends Parent {
public ...
Another example of Inheritance
class Parent
{
int id=11;
String name="Adil";
}
public class Child extends Parent {
public ...
Another example of Inheritance
class Parent
{
int id=11;
String name="Adil";
}
public class Child extends Parent {
public ...
Access Control and Inheritance
• A derived class can access all the non-private
members of its base class. Thus base-class...
Access Control and Inheritance
• The following rules for inherited methods are
enforced:
1. Methods declared public in a s...
Inheritance in Java
• Types of Inheritance
• Based on number of ways inheriting the feature of
base class into derived cla...
Types of Inheritance
Introduction to Java Programming Language
Notes By Adil Aslam
Types of Inheritance
• In java programming, multiple and hybrid
inheritance is supported through interface only. We
will l...
Types of Inheritance
• 1) Single Inheritance
• Single inheritance is easy to understand. When a
class extends another one ...
Single Inheritance Example
class A
{
……...
}
Class B extends A
{
……...
}
Introduction to Java Programming Language
Notes B...
Single Inheritance Example
class A
{
……...
}
Class B extends A
{
……...
}
Introduction to Java Programming Language
Notes B...
Single Inheritance Example
class A {
int data=10;
}
class B extends A {
public void display()
{
System.out.println("Data i...
Single Inheritance Example
class A {
int data=10;
}
class B extends A {
public void display()
{
System.out.println("Data i...
Single Inheritance Example
class A {
int data=10;
}
class B extends A {
public void display()
{
System.out.println("Data i...
Another Single Inheritance Example
class Faculty {
float salary=30000;
}
class Science extends Faculty {
float bonus=2000;...
Another Single Inheritance Example
class Faculty {
float salary=30000;
}
class Science extends Faculty {
float bonus=2000;...
Types of Inheritance
• 2) Multilevel Inheritance
• In Multilevel inheritances there exists single base
class, single deriv...
Multilevel Inheritance
• Here class C inherits class B and class B inherits class A
which means B is a parent class of C a...
Multilevel Inheritance
• Here class C inherits class B and class B inherits class A
which means B is a parent class of C a...
Multilevel Inheritance
• Class C can inherit the Members of both Class A and B Show
below :
Introduction to Java Programmi...
Multilevel Inheritance Example
class A {
……...
}
Class B extends A {
……...
}
Class C extends B {
……...
}
Introduction to J...
Multilevel Inheritance Example
class A {
int data=10;
}
class B extends A{
}
class C extends B {
public void display() {
S...
Multilevel Inheritance Example
class A {
int data=10;
}
class B extends A{
}
class C extends B {
public void display() {
S...
Another Multilevel Inheritance Example
class Faculty {
float total_sal=0, salary=1000;
}
class HRA extends Faculty {
float...
Another Multilevel Inheritance Example
class Faculty {
float total_sal=0, salary=1000;
}
class HRA extends Faculty {
float...
Another Multilevel Inheritance Example
class Faculty {
float total_sal=0, salary=1000;
}
class HRA extends Faculty {
float...
Types of Inheritance
• 3) Hierarchical Inheritance
• In this inheritance multiple classes inherits from
a single class i.e...
Types of Inheritance
• 3) Hierarchical Inheritance
Introduction to Java Programming Language
Notes By Adil Aslam
Class A
C...
Hierarchical Inheritance(Real time Example)
Introduction to Java Programming Language
Notes By Adil Aslam
Account
Saving C...
Hierarchical Inheritance Example
class A {
……...
}
Class B extends A {
……...
}
Class C extends A {
……...
}
Class D extends...
Hierarchical Inheritance Example
class A {
int data=10;
}
class B extends A{
}
class C extends A {
}
class D extends A {
p...
Hierarchical Inheritance Example
class A {
int data=10;
}
class B extends A{
}
class C extends A {
}
class D extends A {
p...
Another Hierarchical Inheritance Example
class A {
void methodA() {
System.out.println("Method of Class A"); }
}
class B e...
Another Hierarchical Inheritance Example
class A {
void methodA() {
System.out.println("Method of Class A"); }
}
class B e...
Types of Inheritance
• 4) Multiple Inheritance
• In java programming, multiple and hybrid
inheritance is not supported thr...
Multiple Inheritance
Here Class A, B and C are three Classes. The C Class
inherits A and B classes.in other words Class C ...
Multiple Inheritance
• Why multiple inheritance is not supported in java?
• Consider a scenario where A, B and C are three...
Multiple Inheritance Example
class A{
void msg(){
System.out.println("Hello"); }
}
class B{
void msg(){
System.out.println...
Types of Inheritance
• 5) Hybrid inheritance
• Any combination of previous three inheritance (single,
hierarchical and mul...
Hybrid Inheritance
• In simple terms you can say that Hybrid inheritance
is a combination of Single and Multiple inheritan...
Hybrid inheritance
Introduction to Java Programming Language
Notes By Adil Aslam
Important Points for Inheritance
• In java programming one derived class can extends only
one base class because java prog...
Important Points for Inheritance
• If we do not want to give the features of base class to
the derived class then the defi...
Inheritance in Java
• Advantage of inheritance
• If we develop any application using concept of
Inheritance than that appl...
Inheritance in Java
• Disadvantages of Inheritance
• Inheritance base class and child classes are tightly
coupled. Hence I...
Method Overriding in Java
Introduction to Java Programming Language
Notes By Adil Aslam
Method Overriding in Java
• Declaring a method in subclass which is already
present in parent class is known as method
ove...
Method Overriding in Java
• Declaring a method in subclass which is already
present in parent class is known as method
ove...
Method Overriding in Java
• Advantage of Java Method Overriding
• Method Overriding is used to provide specific
implementa...
Problem Without Method Overriding
class Vehicle{
void run() {
System.out.println("Vehicle is running");
}
}
class Bike ext...
Problem Without Method Overriding
class Vehicle{
void run() {
System.out.println("Vehicle is running");
}
}
class Bike ext...
Example of Method Overriding
class Vehicle{
void run(){
System.out.println("Vehicle is running");}
}
class Bike extends Ve...
Example of Method Overriding
class Vehicle{
void run(){
System.out.println("Vehicle is running");}
}
class Bike extends Ve...
Example of Method Overriding
class Vehicle{
void run(){
System.out.println("Vehicle is running");}
}
class Bike extends Ve...
Example of Method Overriding
class Vehicle{
void run(){
System.out.println("Vehicle is running");}
}
class Bike extends Ve...
Real Example of Java Method Overriding
• Consider a scenario, Bank is a class that provides
functionality to get rate of i...
Real Example of Java Method Overriding-1
class Bank{
int getInterest(){return 0;}
}
class SBI extends Bank{
int getInteres...
Real Example of Java Method Overriding-2
class Test{
public static void main(String args[]){
SBI s=new SBI();
ICICI i=new ...
Method Overriding (Same Argument List)
public class Base {
public int calculate(int num1,int num2) {
return num1+num2;
}
}...
Method Overriding (Same Argument List)
public class Base {
public int calculate(int num1,int num2) {
return num1+num2;
}
}...
Method Overriding (Same Argument List)
public class Base {
public int calculate(int num1,int num2) {
return num1+num2;
}
}...
Method Overriding (Same Argument List)
public class Base {
public int calculate(int num1,int num2) {
return num1+num2;
}
}...
Method Overriding in Dynamic Method Dispatch
• Dynamic method dispatch is a technique which
enables us to assign the base ...
Method Overriding in Dynamic Method Dispatch-1
class ABC{
public void disp()
{
System.out.println("disp() method of parent...
Method Overriding in Dynamic Method Dispatch-2
class Test extends ABC{
public void disp(){
System.out.println("disp() meth...
Method Overriding in Dynamic Method Dispatch-2
class Test extends ABC{
public void disp(){
System.out.println("disp() meth...
Explanation of Previous Program
• Note: In dynamic method dispatch the object can
call the overriding methods of child cla...
Method Overriding in Java
• Can we override static method?
• No, static method cannot be overridden. It can be
proved by r...
Rules for Method Overriding
• The argument list should be exactly the same as
that of the overridden method.
• The return ...
Rules for Method Overriding
• Instance methods can be overridden only if they
are inherited by the subclass.
• A method de...
Rules for Method Overriding
• A subclass within the same package as the instance's
superclass can override any superclass ...
Java Access Modifiers With Method Overriding
• Access level cannot be lowered down or restricted
than the overridden metho...
Java Access Modifiers With Method Overriding
Introduction to Java Programming Language
Notes By Adil Aslam
Access Level in...
Java Access Modifiers With Method Overriding
public class Base {
public int calculate(int num1,int num2) {
return num1+num...
Method Overriding
• Can we override java main method?
• No, because main is a static method.
• Overriding and constructor
...
Method Overriding
• A method declared static cannot be overridden but can be re-declared.
• Consider the following method ...
Difference between Overloading and Overriding
Overloading Overriding
Method overloading is used to
increase the readabilit...
Difference between Overloading and Overriding
Overloading Overriding
Access modifiers point of view no
restriction.
Access...
Difference between Overloading and Overriding
Introduction to Java Programming Language
Notes By Adil Aslam
Java Method Overloading Example
class OverloadingExample{
static int add(int a, int b)
{
return a+b;
}
static int add(int ...
Java Method Overriding Example
class Animal{
void eat(){
System.out.println(“Eating");
}
}
class Dog extends Animal{
void ...
super keyword in java
Introduction to Java Programming Language
Notes By Adil Aslam
super keyword in java
• Super keyword in java is a reference variable that is
used to refer parent class object. Super is ...
super keyword in java
• Usage of java super Keyword
• We can user super keyword by using three ways:
• Accessing Instance ...
super keyword in java
• Super at Variable Level:
• Whenever the derived class inherit base class data members
there is a p...
Program without using super keyword
class Employee {
float salary=10000;
}
class HR extends Employee
{
float salary=20000;...
Program without using super keyword
class Employee {
float salary=10000;
}
class HR extends Employee
{
float salary=20000;...
Program without using super keyword
class Employee {
float salary=10000;
}
class HR extends Employee
{
float salary=20000;...
Program using super keyword at Variable level
class Employee {
float salary=10000;
}
class HR extends Employee
{
float sal...
Program using super keyword at Variable level
class Employee {
float salary=10000;
}
class HR extends Employee
{
float sal...
Program using super keyword at Variable level
class Employee {
float salary=10000;
}
class HR extends Employee
{
float sal...
super keyword in java
• Super at Method Level
• The super keyword can also be used to invoke or
call parent class method. ...
Example of super keyword at Method level
class Student{
void message(){
System.out.println("Good Morning Sir"); }
}
class ...
Example of super keyword at Method level
class Student{
void message(){
System.out.println("Good Morning Sir"); }
}
class ...
Explanation of Previous Program
• In the previous example Student and Faculty both
classes have message() method if we cal...
Program where super is not Required
class Student{
void message(){
System.out.println("Good Morning Sir"); }
}
class Facul...
super keyword in java
• Super at Constructor Level
• The super keyword can also be used to invoke or
call the parent class...
Super at Constructor Level
• Super()
• Super() It is used for calling super class default
constructor from the context of ...
Super keyword used to call base class Constructor
class Employee{
Employee(){
System.out.println("Employee class Construct...
Super keyword used to call base class Constructor
class Employee{
Employee(){
System.out.println("Employee class Construct...
Explanation of Previous Program
• Note: super() is added in each class constructor
automatically by compiler.
Introduction...
Super keyword used to call base class Constructor
class Employee{
Employee(){
System.out.println("Employee class Construct...
Super at Constructor Level
• Super(...)
• Super(...) It is used for calling super class
parameterize constructor from the ...
class Employee{
int a;
Employee(int a){
this.a=a; }
public void getValue() {
System.out.println("Value is:"+a); }
}
class ...
class Employee{
int a;
Employee(int a){
this.a=a; }
public void getValue() {
System.out.println("Value is:"+a); }
}
class ...
• The following diagram use possibilities of using
super() and super(........)
Introduction to Java Programming Language
N...
super keyword in java
• Rule 1 and Rule 3
• Whenever the derived class constructor want to call
default constructor of bas...
final keyword in java
Introduction to Java Programming Language
Notes By Adil Aslam
Final Keyword In Java
• The final keyword in java is used to restrict the user.
The java final keyword can be used in many...
final variable
• final variables: If you use a variable as a final then
the value of variable is become constant. We
canno...
Example of final variable
class Test{
final int MAX_VALUE=99;
void myMethod(){
MAX_VALUE=101;
}
public static void main(St...
Final Keyword In Java
• Final at method level It makes a method final,
meaning that sub classes can not override this
meth...
Example of Final Keyword at Method Level
class Bike{
final void run(){
System.out.println("running");}
}
class Honda exten...
Example of Final Keyword at Method Level
class Bike{
final void run(){
System.out.println("running");}
}
class Honda exten...
Final Keyword In Java
• Final at class level It makes a class final, meaning
that the class can not be inheriting by other...
Example of final keyword at class level
final class Bike{}
class Honda extends Bike{
void run(){
System.out.println(“Runni...
Example of final keyword at class level
final class Bike{}
class Honda extends Bike{
void run(){
System.out.println(“Runni...
Final Keyword In Java
• Q) Is final method inherited?
• Ans) Yes, final method is inherited but we cannot
override it. For...
Final Keyword In Java
• blank or uninitialized final variable
• A final variable that is not initialized at the time of
de...
Final Keyword In Java
initialize blank final variable
Introduction to Java Programming Language
Notes By Adil Aslam
class ...
Final Keyword In Java
• What are the advantages of blank final variables?
• Blank final variables allow the Programmer to
...
Final Keyword In Java
• static blank final variable
• A static final variable that is not initialized at the
time of decla...
Final Keyword In Java
• final Parameter in Method
• If we declare any parameter as final, you cannot
change the value of i...
Some Important Points : final Keyword
• Final Keyword can be applied only on Method,
Class and Variable
• Final Variable m...
final Keyword
Introduction to Java Programming Language
Notes By Adil Aslam
Final Entity Description
Final Value Final Val...
instanceof operator in java
Introduction to Java Programming Language
Notes By Adil Aslam
Java Instanceof Operator
• The java instanceof operator is used to test
whether the object is an instance of the specified...
Example of Instanceof
class Test{
public static void main(String args[]){
Object t=0;
Test s=new Test();
System.out.printl...
Another Example of java instanceof Operator
class Animal{}
//Dog inherits Animal
class Dog extends Animal{
public static v...
IS-A Relationship Verification
class FourWheeler extends Vehicle{}
class TwoWheeler extends Vehicle{}
class Car extends Fo...
IS-A Relationship Verification
class FourWheeler extends Vehicle{}
class TwoWheeler extends Vehicle{}
class Car extends Fo...
Instanceof in Java with a Variable that value
null Value
• If we apply instanceof operator with a variable that
have null ...
Java Instanceof Operator
• The instanceof keyword can also be used to test if
an object is of a specified type.
• Example
...
Java Type Casting – Inheritance
• Converting one type of value to another is called
as Type Casting.
• Different Forms of ...
Java Type Casting – Inheritance
• Up Casting
• We can cast an instance of a child class to its parent
class. Casting an ob...
Java Type Casting – Inheritance
• Down Casting
• Casting an object of a parent class to its child class is
called downcast...
Java Type Casting – Inheritance
Introduction to Java Programming Language
Notes By Adil Aslam
Example of Downcasting with Instanceof Operator
class Parent { }
class Child extends Parent {
static void method(Parent a)...
Example of Downcasting with Instanceof Operator
class Parent { }
class Child extends Parent {
static void method(Parent a)...
Downcasting Without the use of Java Instanceof
class Parent { }
class Child extends Parent {
static void method(Parent a) ...
Java Garbage Collection
Introduction to Java Programming Language
Notes By Adil Aslam
Java Garbage Collection
• In java, garbage means unreferenced objects.
• Garbage Collection is process of reclaiming the
r...
Java Garbage Collection
• In Java destruction of object from memory is done
automatically by the JVM. When there is no
ref...
Java Garbage Collection
• Can the Garbage Collection be forced explicitly ?
• No, the Garbage Collection can not be forced...
Java Garbage Collection
• How can an object be unreferenced?
• There are many ways:
• By nulling the reference
• By assign...
Java Garbage Collection
• 2) By assigning a reference to another:
• 3) By anonymous object:
Introduction to Java Programmi...
Java Garbage Collection
• finalize() method
• We have seen that a constructor method is used to initialize
an object when ...
Java Garbage Collection
• finalize() method
• The finalize() method is invoked each time before the object
is garbage coll...
Java Garbage Collection
• gc() method
• gc() method is used to call garbage collector
explicitly. However gc() method does...
Example of garbage collection in java
public class Test{
public void finalize(){
System.out.println("Garbage Collected");
...
Java Garbage Collection
• Points to Note
• Every class inherits the finalize() method from
java.lang.Object.
• The finaliz...
Java Varargs Method
Introduction to Java Programming Language
Notes By Adil Aslam
Variable Argument or Varargs Methods
• The varrags allows the method to accept zero or
multiple arguments.
• Before vararg...
Variable Argument or Varargs Methods
• Variable arguments before Java 1.5
• Prior to Java 1.5 Java programmer mainly have ...
Variable Argument or Varargs Methods
• Advantage of Varargs:
• We don't have to provide overloaded methods so
less code.
•...
Variable Argument or Varargs Methods
• Example with one variable-length argument:
• A varargs method can have more than on...
Variable Argument or Varargs Methods
• Rules for varargs:
• While using the varargs, we must follow some rules
otherwise p...
Variable Argument or Varargs Methods
• A varargs method can have a maximum of one
variable-length argument.
Introduction t...
Variable Argument or Varargs Methods
• A varargs method can have a maximum of one
variable-length argument.
Introduction t...
Variable Argument or Varargs Methods
• The variable-length argument of a varargs method
must be the last argument in the a...
Program without Using Variable Argument-1
// Simple Program which Calculates Average of two, three and
four numbers
public...
Program without Using Variable Argument-2
public static void main(String[] args) {
//prints average of two numbers
System....
Program without Using Variable Argument-2
public static void main(String[] args) {
//prints average of two numbers
System....
Example of Varargs
public class Test{
static double average(int... a) {
int n = a.length; //Average Of 'n' numbers (Calcul...
Example of Varargs
public class Test{
static double average(int... a) {
int n = a.length; //Average Of 'n' numbers (Calcul...
Explanation of Previous Program
• It can be seen from the program that length is used
here to find the number of arguments...
Another Example of Varargs in java
class Test{
static void display(String... values){
for(String s:values){
System.out.pri...
Another Example of Varargs in java
class Test{
static void display(String... values){
for(String s:values){
System.out.pri...
Example of Varargs that is the Last Argument
class Test{
static void display(int id, String... values){
System.out.println...
Example of Varargs that is the Last Argument
class Test{
static void display(int id, String... values){
System.out.println...
Another Example
public class Test {
public static int max(int n1, int n2, int... num) {
// Initialize max to the maximum o...
Another Example
public class Test {
public static int max(int n1, int n2, int... num) {
// Initialize max to the maximum o...
Variable Argument or Varargs Methods
• VarArgs internally behave like array. The best
example for this is, we can replace ...
Variable Argument or Varargs Methods
• Even constructors can have VarArgs as an
argument.
Introduction to Java Programming...
Variable Argument in Constructor
public class Test{
public Test(Double... d){
int n = d.length;
double sum = 0;
for(Double...
Variable Argument in Constructor
public class Test{
public Test(Double... d){
int n = d.length;
double sum = 0;
for(Double...
Overloading Varargs Methods
• It is possible to overload a method that takes
varargs parameter.
Varargs method can be over...
Overloading Varargs Methods-1
public class Test{
// Method which has string vararg parameter
public void displayData(Strin...
Overloading Varargs Methods-1
public class Test{
// Method which has string vararg parameter
public void displayData(Strin...
Overloading Varargs Methods-2
public static void main(String[] args) {
Test obj = new Test();
// passing four string argum...
Overloading Varargs Methods-2
public static void main(String[] args) {
Test obj = new Test();
// passing four string argum...
Introduction To Java Programming Lecture No. 11
Introduction To Java Programming Lecture No. 11
Introduction To Java Programming Lecture No. 11
Introduction To Java Programming Lecture No. 11
Introduction To Java Programming Lecture No. 11
Introduction To Java Programming Lecture No. 11
Introduction To Java Programming Lecture No. 11
Introduction To Java Programming Lecture No. 11
Introduction To Java Programming Lecture No. 11
Introduction To Java Programming Lecture No. 11
Introduction To Java Programming Lecture No. 11
Introduction To Java Programming Lecture No. 11
Introduction To Java Programming Lecture No. 11
Introduction To Java Programming Lecture No. 11
Introduction To Java Programming Lecture No. 11
Prochain SlideShare
Chargement dans…5
×

Introduction To Java Programming Lecture No. 11

1 177 vues

Publié le

Inheritance in Java
Type of Inheritance in Java
Sub-typing & Specialization
Examples of Inheritance in Java
Method Overriding in Java
super keyword in java
Final Keyword In Java
Java Type Casting – Inheritance
Java Garbage Collection
Variable Argument or Varargs Methods

Publié dans : Formation
  • Soyez le premier à commenter

Introduction To Java Programming Lecture No. 11

  1. 1. Introduction To Java Programming Language Lecture No.11 Notes By Adil Aslam My Email Address is : adilaslam5959@gmail.com
  2. 2. About Me Introduction to Java Programming Language Notes By Adil Aslam i am Student of BSCS My email address: adilaslam5959@gmail.com
  3. 3. Introduction to Java Programming Language Notes By Adil Aslam Inheritance in Java
  4. 4. Inheritance in Java • Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of parent object. • When a Class extends another class it inherits all non-private members including fields and methods. Inheritance in Java can be best understood in terms of Parent and Child relationship, also known as Super class(Parent) and Sub class(child) in Java language. • Inheritance defines is-a relationship between a Super class and its Sub class. extends and implements keywords are used to describe inheritance in Java. Introduction to Java Programming Language Notes By Adil Aslam
  5. 5. Inheritance in Java • Inheritance represents the IS-A relationship, also known as parent-child relationship. • Why use Inheritance ? • For Method Overriding (used for Runtime Polymorphism). • It's main uses are to enable polymorphism and to be able to reuse code for different classes by putting it in a common super class • For code Re-usability Introduction to Java Programming Language Notes By Adil Aslam
  6. 6. Inheritance in Java Introduction to Java Programming Language Notes By Adil Aslam
  7. 7. Inheritance in Java • Important points • In the inheritance the class which is give data members and methods is known as base or super or parent class. • The class which is taking the data members and methods is known as sub or derived or child class. • The data members and methods of a class are known as features. • The concept of inheritance is also known as re- usability or extendable classes or sub classing or derivation. Introduction to Java Programming Language Notes By Adil Aslam
  8. 8. Inheritance in Java No Term Definition 1 Inheritance Inheritance is a process where one object acquires the properties of another object 2 Subclass Class which inherits the properties of another object is called as subclass 3 Superclass Class whose properties are inherited by subclass is called as superclass 4 Keywords Used extends and implements Introduction to Java Programming Language Notes By Adil Aslam
  9. 9. Example – Inheritance Introduction to Java Programming Language Notes By Adil Aslam Person Teacher DoctorStudent
  10. 10. Example – Inheritance Introduction to Java Programming Language Notes By Adil Aslam Shape Circle TriangleLine
  11. 11. Example – “IS A” Relationship Introduction to Java Programming Language Notes By Adil Aslam Person name age gender eat walk Teacher designation salary teach takeExam Student program studyYear study heldExam Doctor designation salary checkUp prescribe
  12. 12. Example – “IS A” Relationship Introduction to Java Programming Language Notes By Adil Aslam Shape color coord draw rotate setColor Circle radius draw computeArea Line length draw Triangle angle draw computeArea
  13. 13. Reuse with Inheritance • Main purpose of inheritance is reuse • We can easily add new classes by inheriting from existing classes • Select an existing class closer to the desired functionality • Create a new class and inherit it from the selected class • Add to and/or modify the inherited functionality Introduction to Java Programming Language Notes By Adil Aslam
  14. 14. Example Reuse Introduction to Java Programming Language Notes By Adil Aslam Shape color coord draw rotate setColor Circle radius draw computeArea Line length draw Triangle angle draw computeArea
  15. 15. Example Reuse-1 Introduction to Java Programming Language Notes By Adil Aslam Person name age gender eat walk Teacher designation salary teach takeExam Student program studyYear study heldExam Doctor designation salary checkUp prescribe
  16. 16. Example Reuse-2 Introduction to Java Programming Language Notes By Adil Aslam Person name age gender eat walk Teacher designation salary teach takeExam Student program studyYear study heldExam Doctor designation salary checkUp prescribe
  17. 17. Concepts Related with Inheritance Generalization Subtyping (extension) Specialization (restriction) Introduction to Java Programming Language Notes By Adil Aslam
  18. 18. Concepts Related with Inheritance  Generalization • In OO models, some classes may have common characteristics • We extract these features into a new class and inherit original classes from this new class • This concept is known as Generalization Introduction to Java Programming Language Notes By Adil Aslam
  19. 19. Example – Generalization Introduction to Java Programming Language Notes By Adil Aslam Circle color vertices radius move setColor computeArea Line color vertices length move setColor getLength Triangle color vertices angle move setColor computeArea
  20. 20. Example – Generalization Introduction to Java Programming Language Notes By Adil Aslam Shape color vertices move setColor Circle radius computeArea Line length getLength Triangle angle computeArea
  21. 21. Example – Generalization Introduction to Java Programming Language Notes By Adil Aslam Teacher name age gender designation salary teach takeExam eat walk Student name age gender program studyYear study heldExam eat walk Doctor name age gender designation salary checkUp prescribe eat walk
  22. 22. Example – Generalization Introduction to Java Programming Language Notes By Adil Aslam Person name age gender eat walk Teacher designation salary teach takeExam Student program studyYear study heldExam Doctor designation salary checkUp prescribe
  23. 23. Sub-typing & Specialization • We want to add a new class to an existing model • Find an existing class that already implements some of the desired state and behaviour • Inherit the new class from this class and add unique behaviour to the new class Introduction to Java Programming Language Notes By Adil Aslam
  24. 24. Sub-typing (Extension) • Sub-typing means that derived class is behaviourally compatible with the base class • Behaviourally compatible means that base class can be replaced by the derived class Introduction to Java Programming Language Notes By Adil Aslam
  25. 25. Example –Sub-typing (Extension) Introduction to Java Programming Language Notes By Adil Aslam Person name age gender eats walks Student program studyYear study takeExam
  26. 26. Example –Sub-typing (Extension) Introduction to Java Programming Language Notes By Adil Aslam Shape color vertices setColor move Circle radius computeCF computeArea
  27. 27. Specialization (Restriction) • Specialization means that derived class is behaviourally incompatible with the base class • Behaviourally incompatible means that base class can’t always be replaced by the derived class Introduction to Java Programming Language Notes By Adil Aslam
  28. 28. Example – Specialization (Restriction) Introduction to Java Programming Language Notes By Adil Aslam Person age : [0..100] … Adult age : [18..100] … setAge( a ) … setAge( a ) … age = a If age < 18 then error else age = a
  29. 29. Example – Specialization (Restriction) Introduction to Java Programming Language Notes By Adil Aslam IntegerSet … NaturalSet … add( elem ) … add( elem ) … add element to the set If elem < 1 then error else add element to the set
  30. 30. Inheritance in Java • Inheritance in Java • Inheritance in Java is done using • extends – In case of Java class and abstract class • implements – In case of Java interface. • What is inherited • In Java when a class is extended, sub-class inherits all the public, protected and default (Only if the sub-class is located in the same package as the super class) methods and fields of the super class. • What is not inherited • Private fields and methods of the super class are not inherited by the sub-class and can’t be accessed directly by the subclass. • Constructors of the super-class are not inherited. There is a concept of constructor chaining in Java which determines in what order constructors are called in case of inheritance. Introduction to Java Programming Language Notes By Adil Aslam
  31. 31. Inheritance in Java • Syntax of Inheritance • The extends keyword indicates that you are making a new class that derives from an existing class. Introduction to Java Programming Language Notes By Adil Aslam class Subclass-name extends Superclass-name { //methods and fields }
  32. 32. Inheritance in Java • extends Keyword • extends is the keyword used to inherit the properties of a class. Following is the syntax of extends keyword. Introduction to Java Programming Language Notes By Adil Aslam class Super { ..... ..... } class Sub extends Super { ..... ..... }
  33. 33. Inheritance in Java • IS-A Relationship with Example • IS-A is a way of saying : This object is a type of that object. Introduction to Java Programming Language Notes By Adil Aslam public class Vehicle{ } public class FourWheeler extends Vehicle{ } public class TwoWheeler extends Vehicle{ } public class Car extends FourWheeler{ }
  34. 34. Inheritance in Java • Conclusions from above Example : • Vehicle is the superclass of TwoWheeler class. • Vehicle is the superclass of FourWheeler class. • TwoWheeler and FourWheeler are subclasses of Vehicle class. • Car is the subclass of both FourWheeler and Vehicle classes. Introduction to Java Programming Language Notes By Adil Aslam public class Vehicle{ } public class FourWheeler extends Vehicle{ } public class TwoWheeler extends Vehicle{ } public class Car extends FourWheeler{ }
  35. 35. Inheritance in Java • Conclusions from above Example : • Vehicle is the superclass of TwoWheeler class. • Vehicle is the superclass of FourWheeler class. • TwoWheeler and FourWheeler are subclasses of Vehicle class. • Car is the subclass of both FourWheeler and Vehicle classes. Introduction to Java Programming Language Notes By Adil Aslam public class Vehicle{ } public class FourWheeler extends Vehicle{ } public class TwoWheeler extends Vehicle{ } public class Car extends FourWheeler{ } IS-A relationship of above example is: TwoWheeler IS-A Vehicle FourWheeler IS-A Vehicle Car IS-A FourWheeler Hence Car IS-A Vehicle
  36. 36. Inheritance in Java • IS-A Relationship • Based on the above example, in Object-Oriented terms which is base Class and which is Derived Class…??? Introduction to Java Programming Language Notes By Adil Aslam public class Animal { } public class Mammal extends Animal { } public class Reptile extends Animal { } public class Dog extends Mammal { }
  37. 37. Inheritance in Java • Based on the above example, in Object-Oriented terms, the following are: • Animal is the superclass of Mammal class. • Animal is the superclass of Reptile class. • Mammal and Reptile are subclasses of Animal class. • Dog is the subclass of both Mammal and Animal classes. • Now, if we consider the IS-A relationship, we can say: • Mammal IS-A Animal • Reptile IS-A Animal • Dog IS-A Mammal • Hence: Dog IS-A Animal as well • With the use of the extends keyword, the subclasses will be able to inherit all the properties of the superclass except for the private properties of the superclass. Introduction to Java Programming Language Notes By Adil Aslam
  38. 38. Inheritance in Java • Please Note: • In inheritance Parent Class and Child Class having multiple names, List of the name are below: • Parent Class = Base Class = Super Class • Child Class = Derived Class = Sub Class Introduction to Java Programming Language Notes By Adil Aslam
  39. 39. Simple Example of Inheritance class Parent { public void p1() { System.out.println("Parent method"); } } public class Child extends Parent { public void c1() { System.out.println("Child method"); } public static void main(String[] args) { Child cobj = new Child(); cobj.c1(); //Calling method of Child class cobj.p1(); //Calling method of Parent class } } Introduction to Java Programming Language Notes By Adil Aslam
  40. 40. Simple Example of Inheritance class Parent { public void p1() { System.out.println("Parent method"); } } public class Child extends Parent { public void c1() { System.out.println("Child method"); } public static void main(String[] args) { Child cobj = new Child(); cobj.c1(); //Calling method of Child class cobj.p1(); //Calling method of Parent class } } Introduction to Java Programming Language Notes By Adil Aslam Super Class/ Parent Class
  41. 41. Simple Example of Inheritance class Parent { public void p1() { System.out.println("Parent method"); } } public class Child extends Parent { public void c1() { System.out.println("Child method"); } public static void main(String[] args) { Child cobj = new Child(); cobj.c1(); //Calling method of Child class cobj.p1(); //Calling method of Parent class } } Introduction to Java Programming Language Notes By Adil Aslam Parent Class Method
  42. 42. Simple Example of Inheritance class Parent { public void p1() { System.out.println("Parent method"); } } public class Child extends Parent { public void c1() { System.out.println("Child method"); } public static void main(String[] args) { Child cobj = new Child(); cobj.c1(); //Calling method of Child class cobj.p1(); //Calling method of Parent class } } Introduction to Java Programming Language Notes By Adil Aslam Sub Class/ Child Class
  43. 43. Simple Example of Inheritance class Parent { public void p1() { System.out.println("Parent method"); } } public class Child extends Parent { public void c1() { System.out.println("Child method"); } public static void main(String[] args) { Child cobj = new Child(); cobj.c1(); //Calling method of Child class cobj.p1(); //Calling method of Parent class } } Introduction to Java Programming Language Notes By Adil Aslam Child Class Method
  44. 44. Simple Example of Inheritance class Parent { public void p1() { System.out.println("Parent method"); } } public class Child extends Parent { public void c1() { System.out.println("Child method"); } public static void main(String[] args) { Child cobj = new Child(); cobj.c1(); //Calling method of Child class cobj.p1(); //Calling method of Parent class } } Introduction to Java Programming Language Notes By Adil Aslam Child Class Inherit the Properties Of Parent Class
  45. 45. Simple Example of Inheritance class Parent { public void p1() { System.out.println("Parent method"); } } public class Child extends Parent { public void c1() { System.out.println("Child method"); } public static void main(String[] args) { Child cobj = new Child(); cobj.c1(); //Calling method of Child class cobj.p1(); //Calling method of Parent class } } Introduction to Java Programming Language Notes By Adil Aslam Creating An Object of Child Class
  46. 46. Simple Example of Inheritance class Parent { public void p1() { System.out.println("Parent method"); } } public class Child extends Parent { public void c1() { System.out.println("Child method"); } public static void main(String[] args) { Child cobj = new Child(); cobj.c1(); //Calling method of Child class cobj.p1(); //Calling method of Parent class } } Introduction to Java Programming Language Notes By Adil Aslam Calling Child Class and Parent Class Method Using Object Of Child Class
  47. 47. Simple Example of Inheritance class Parent { public void p1() { System.out.println("Parent method"); } } public class Child extends Parent { public void c1() { System.out.println("Child method"); } public static void main(String[] args) { Child cobj = new Child(); cobj.c1(); //Calling method of Child class cobj.p1(); //Calling method of Parent class } } Introduction to Java Programming Language Notes By Adil Aslam Output is: Child method Parent method
  48. 48. Explanation of Previous Program • When child class inherit the propertied of parent class the child class look like this (just for understanding) Introduction to Java Programming Language Notes By Adil Aslam public class Child extends Parent { public void c1() { System.out.println("Child method"); } public void p1() { System.out.println("Parent method"); } public static void main(String[] args) { Child cobj = new Child(); cobj.c1(); //Calling method of Child class cobj.p1(); //Calling method of Parent class } }
  49. 49. Another example of Inheritance class Parent { int id=11; String name="Adil"; } public class Child extends Parent { public void display() { System.out.println("ID is: "+id); System.out.println("Name is: "+name); } public static void main(String[] args) { Child obj = new Child(); obj.display(); } } Introduction to Java Programming Language Notes By Adil Aslam
  50. 50. Another example of Inheritance class Parent { int id=11; String name="Adil"; } public class Child extends Parent { public void display() { System.out.println("ID is: "+id); System.out.println("Name is: "+name); } public static void main(String[] args) { Child obj = new Child(); obj.display(); } } Introduction to Java Programming Language Notes By Adil Aslam Here in Child Class we Can Inherit Or Access the Properties of Parent Class
  51. 51. Another example of Inheritance class Parent { int id=11; String name="Adil"; } public class Child extends Parent { public void display() { System.out.println("ID is: "+id); System.out.println("Name is: "+name); } public static void main(String[] args) { Child obj = new Child(); obj.display(); } } Introduction to Java Programming Language Notes By Adil Aslam Here in Child Class we Can Inherit Or Access the Properties of Parent Class Output is: ID is: 11 Name is: Adil
  52. 52. Access Control and Inheritance • A derived class can access all the non-private members of its base class. Thus base-class members that should not be accessible to the members of derived classes should be declared private in the base class. Introduction to Java Programming Language Notes By Adil Aslam Access public protected private Same class yes yes yes Derived classes yes yes no Outside classes yes no no
  53. 53. Access Control and Inheritance • The following rules for inherited methods are enforced: 1. Methods declared public in a superclass also must be public in all subclasses. 2. Methods declared protected in a superclass must either be protected or public in subclasses; they cannot be private. 3. Methods declared private are not inherited at all, so there is no rule for them. Introduction to Java Programming Language Notes By Adil Aslam
  54. 54. Inheritance in Java • Types of Inheritance • Based on number of ways inheriting the feature of base class into derived class we have five types of inheritance; they are: • Single inheritance • Multiple inheritance • Hierarchical inheritance • Multilevel inheritance • Hybrid inheritance Introduction to Java Programming Language Notes By Adil Aslam
  55. 55. Types of Inheritance Introduction to Java Programming Language Notes By Adil Aslam
  56. 56. Types of Inheritance • In java programming, multiple and hybrid inheritance is supported through interface only. We will learn about interfaces later. Introduction to Java Programming Language Notes By Adil Aslam
  57. 57. Types of Inheritance • 1) Single Inheritance • Single inheritance is easy to understand. When a class extends another one class only then we call it a single inheritance. The below flow diagram shows that class B extends only one class which is A. Here A is a parent class of B and B would be a child class of A. Introduction to Java Programming Language Notes By Adil Aslam Class A Class B
  58. 58. Single Inheritance Example class A { ……... } Class B extends A { ……... } Introduction to Java Programming Language Notes By Adil Aslam
  59. 59. Single Inheritance Example class A { ……... } Class B extends A { ……... } Introduction to Java Programming Language Notes By Adil Aslam Parent Class Child Class Child Class B inherit the Properties of Parent Class A
  60. 60. Single Inheritance Example class A { int data=10; } class B extends A { public void display() { System.out.println("Data is:"+data); } public static void main(String args[]) { B obj = new B(); obj.display(); } } Introduction to Java Programming Language Notes By Adil Aslam
  61. 61. Single Inheritance Example class A { int data=10; } class B extends A { public void display() { System.out.println("Data is:"+data); } public static void main(String args[]) { B obj = new B(); obj.display(); } } Introduction to Java Programming Language Notes By Adil Aslam Child Class B inherit/Access the data field of Parent Class A
  62. 62. Single Inheritance Example class A { int data=10; } class B extends A { public void display() { System.out.println("Data is:"+data); } public static void main(String args[]) { B obj = new B(); obj.display(); } } Introduction to Java Programming Language Notes By Adil Aslam Child Class B inherit/Access the data field of Parent Class A Output is: Data is:10
  63. 63. Another Single Inheritance Example class Faculty { float salary=30000; } class Science extends Faculty { float bonus=2000; public static void main(String args[]) { Science obj=new Science(); System.out.println("Salary is:"+obj.salary); System.out.println("Bonus is:"+obj.bonus); } } Introduction to Java Programming Language Notes By Adil Aslam
  64. 64. Another Single Inheritance Example class Faculty { float salary=30000; } class Science extends Faculty { float bonus=2000; public static void main(String args[]) { Science obj=new Science(); System.out.println("Salary is:"+obj.salary); System.out.println("Bonus is:"+obj.bonus); } } Introduction to Java Programming Language Notes By Adil Aslam Output is: Salary is:30000.0 Bonus is:2000.0
  65. 65. Types of Inheritance • 2) Multilevel Inheritance • In Multilevel inheritances there exists single base class, single derived class and multiple intermediate base classes. • Single base class + single derived class + multiple intermediate base classes. • Intermediate base classes • An intermediate base class is one in one context with access derived class and in another context same class access base class. Introduction to Java Programming Language Notes By Adil Aslam
  66. 66. Multilevel Inheritance • Here class C inherits class B and class B inherits class A which means B is a parent class of C and A is a parent class of B. So in this case class C is implicitly inheriting the properties and method of class A along with B that’s what is called multilevel inheritance. Introduction to Java Programming Language Notes By Adil Aslam Class A Class B Class C
  67. 67. Multilevel Inheritance • Here class C inherits class B and class B inherits class A which means B is a parent class of C and A is a parent class of B. So in this case class C is implicitly inheriting the properties and method of class A along with B that’s what is called multilevel inheritance. Introduction to Java Programming Language Notes By Adil Aslam Class A Class B Class C Inherit the Properties Inherit the Properties
  68. 68. Multilevel Inheritance • Class C can inherit the Members of both Class A and B Show below : Introduction to Java Programming Language Notes By Adil Aslam Class C Member Class B Member Class A Member C Contains B Which Contains A
  69. 69. Multilevel Inheritance Example class A { ……... } Class B extends A { ……... } Class C extends B { ……... } Introduction to Java Programming Language Notes By Adil Aslam A is Parent Class of B B is Child Class of A and Parent Class of C C is Child Class of B
  70. 70. Multilevel Inheritance Example class A { int data=10; } class B extends A{ } class C extends B { public void display() { System.out.println("Data is:"+data); } public static void main(String args[]) { C obj = new C(); obj.display(); } } Introduction to Java Programming Language Notes By Adil Aslam Here Class B inherit the properties of Class A and Class C inherit the properties of Class B
  71. 71. Multilevel Inheritance Example class A { int data=10; } class B extends A{ } class C extends B { public void display() { System.out.println("Data is:"+data); } public static void main(String args[]) { C obj = new C(); obj.display(); } } Introduction to Java Programming Language Notes By Adil Aslam Output is: Data is:10
  72. 72. Another Multilevel Inheritance Example class Faculty { float total_sal=0, salary=1000; } class HRA extends Faculty { float hra=2000; } class DA extends HRA { float da=3000; } class Science extends DA { float bonus=4000; public static void main(String args[]) { Science obj=new Science(); obj.total_sal=obj.salary+obj.hra+obj.da+obj.bonus; System.out.println("Total Salary is:"+obj.total_sal); } Introduction to Java Programming Language Notes By Adil Aslam Here we can create an Object of Class “Science”
  73. 73. Another Multilevel Inheritance Example class Faculty { float total_sal=0, salary=1000; } class HRA extends Faculty { float hra=2000; } class DA extends HRA { float da=3000; } class Science extends DA { float bonus=4000; public static void main(String args[]) { Science obj=new Science(); obj.total_sal=obj.salary+obj.hra+obj.da+obj.bonus; System.out.println("Total Salary is:"+obj.total_sal); } Introduction to Java Programming Language Notes By Adil Aslam Here we can Access the Properties of Class “Faculty” , Class “HRA” and Class “DA” using the Object of Class “Science” Class C look Like This After inheritance float total_sal=0, salary=1000; float hra=2000; float da=3000; float bonus=4000;
  74. 74. Another Multilevel Inheritance Example class Faculty { float total_sal=0, salary=1000; } class HRA extends Faculty { float hra=2000; } class DA extends HRA { float da=3000; } class Science extends DA { float bonus=4000; public static void main(String args[]) { Science obj=new Science(); obj.total_sal=obj.salary+obj.hra+obj.da+obj.bonus; System.out.println("Total Salary is:"+obj.total_sal); } Introduction to Java Programming Language Notes By Adil Aslam Output is: Total Salary is:10000.0
  75. 75. Types of Inheritance • 3) Hierarchical Inheritance • In this inheritance multiple classes inherits from a single class i.e there is one super class and multiple sub classes. As we can see from the below diagram when a same class is having more than one sub class (or) more than one sub class has the same parent is called as Hierarchical Inheritance. Introduction to Java Programming Language Notes By Adil Aslam Class A Class B Class C Class D
  76. 76. Types of Inheritance • 3) Hierarchical Inheritance Introduction to Java Programming Language Notes By Adil Aslam Class A Class B Class C Class D Here Class A acts as the parent for sub classes Class B, Class C and Class D
  77. 77. Hierarchical Inheritance(Real time Example) Introduction to Java Programming Language Notes By Adil Aslam Account Saving CurrentFixed-Deposit Short LongMedium
  78. 78. Hierarchical Inheritance Example class A { ……... } Class B extends A { ……... } Class C extends A { ……... } Class D extends A { ……... } Introduction to Java Programming Language Notes By Adil Aslam A is a Parent Class of Class B, C and D B is Child Class of Class A C is Child Class of Class A D is Child Class of Class A
  79. 79. Hierarchical Inheritance Example class A { int data=10; } class B extends A{ } class C extends A { } class D extends A { public static void main(String args[]) { B obj1 = new B(); C obj2 = new C(); D obj3 = new D(); System.out.println("Data in Class B is: "+obj1.data); System.out.println("Data in Class C is: "+obj2.data); System.out.println("Data in Class D is: "+obj3.data); } } Introduction to Java Programming Language Notes By Adil Aslam
  80. 80. Hierarchical Inheritance Example class A { int data=10; } class B extends A{ } class C extends A { } class D extends A { public static void main(String args[]) { B obj1 = new B(); C obj2 = new C(); D obj3 = new D(); System.out.println("Data in Class B is: "+obj1.data); System.out.println("Data in Class C is: "+obj2.data); System.out.println("Data in Class D is: "+obj3.data); } } Introduction to Java Programming Language Notes By Adil Aslam Output is: Data in Class B is: 10 Data in Class C is: 10 Data in Class D is: 10
  81. 81. Another Hierarchical Inheritance Example class A { void methodA() { System.out.println("Method of Class A"); } } class B extends A{ } class C extends A{ } class D extends A { public static void main(String args[]) { B obj1 = new B(); C obj2 = new C(); D obj3 = new D(); obj1.methodA(); obj2.methodA(); obj3.methodA(); } } Introduction to Java Programming Language Notes By Adil Aslam
  82. 82. Another Hierarchical Inheritance Example class A { void methodA() { System.out.println("Method of Class A"); } } class B extends A{ } class C extends A{ } class D extends A { public static void main(String args[]) { B obj1 = new B(); C obj2 = new C(); D obj3 = new D(); obj1.methodA(); obj2.methodA(); obj3.methodA(); } } Introduction to Java Programming Language Notes By Adil Aslam Output is: Method of Class A Method of Class A Method of Class A
  83. 83. Types of Inheritance • 4) Multiple Inheritance • In java programming, multiple and hybrid inheritance is not supported through classes but supported through interface only. We will learn about interfaces later. • Q) Why multiple inheritance is not supported in java? • To reduce the complexity and simplify the language, multiple inheritance is not supported in java. Introduction to Java Programming Language Notes By Adil Aslam
  84. 84. Multiple Inheritance Here Class A, B and C are three Classes. The C Class inherits A and B classes.in other words Class C inherit the properties of both Class A and Class B. Introduction to Java Programming Language Notes By Adil Aslam Class A Class B Class C
  85. 85. Multiple Inheritance • Why multiple inheritance is not supported in java? • Consider a scenario where A, B and C are three classes. The C class inherits A and B classes. If A and B classes have same method and you call it from child class object, there will be ambiguity to call method of A or B class. • Since compile time errors are better than runtime errors, java renders compile time error if you inherit 2 classes. So whether you have same method or different, there will be compile time error now. Introduction to Java Programming Language Notes By Adil Aslam
  86. 86. Multiple Inheritance Example class A{ void msg(){ System.out.println("Hello"); } } class B{ void msg(){ System.out.println("Welcome");} } class C extends A,B{ //suppose if it were public static void main(String args[]){ C obj=new C(); obj.msg(); //Now which msg() method would be invoked? } } Introduction to Java Programming Language Notes By Adil Aslam
  87. 87. Types of Inheritance • 5) Hybrid inheritance • Any combination of previous three inheritance (single, hierarchical and multi level) is called as hybrid inheritance. Introduction to Java Programming Language Notes By Adil Aslam Class A Class B Class C Class D
  88. 88. Hybrid Inheritance • In simple terms you can say that Hybrid inheritance is a combination of Single and Multiple inheritance • A typical flow diagram would look like in the previous slide. • A hybrid inheritance can be achieved in the java in a same way as multiple inheritance can be!! Using interfaces. yes you heard it right. • By using interfaces we can have multiple as well as hybrid inheritance in Java. Introduction to Java Programming Language Notes By Adil Aslam
  89. 89. Hybrid inheritance Introduction to Java Programming Language Notes By Adil Aslam
  90. 90. Important Points for Inheritance • In java programming one derived class can extends only one base class because java programming does not support multiple inheritance through the concept of classes, but it can be supported through the concept of Interface. • Whenever we develop any inheritance application first create an object of bottom most derived class but not for top most base class. • When we create an object of bottom most derived class, first we get the memory space for the data members of top most base class, and then we get the memory space for data member of other bottom most derived class. • Bottom most derived class contains logical appearance for the data members of all top most base classes. Introduction to Java Programming Language Notes By Adil Aslam
  91. 91. Important Points for Inheritance • If we do not want to give the features of base class to the derived class then the definition of the base class must be preceded by final hence final base classes are not reusable or not inheritable. • If we are do not want to give some of the features of base class to derived class than such features of base class must be as private hence private features of base class are not inheritable or accessible in derived class. • An object of base class can contain details about features of same class but an object of base class never contains the details about special features of its derived class (this concept is known as scope of base class object). • For each and every class in java there exists an implicit predefined super class called java.lang.Object. because it providers garbage collection facilities to its sub classes for collecting un-used memory space and improved the performance of java application. Introduction to Java Programming Language Notes By Adil Aslam
  92. 92. Inheritance in Java • Advantage of inheritance • If we develop any application using concept of Inheritance than that application have following advantages, • Application development time is less. • Application take less memory. • Application execution time is less. • Application performance is enhance (improved). • Redundancy (repetition) of the code is reduced or minimized so that we get consistence results and less storage cost. Introduction to Java Programming Language Notes By Adil Aslam
  93. 93. Inheritance in Java • Disadvantages of Inheritance • Inheritance base class and child classes are tightly coupled. Hence If you change the code of parent class, it will get affects to the all the child classes. • In class hierarchy many data members remain unused and the memory allocated to them is not utilized. Hence affect performance of your program if you have not implemented inheritance correctly. Introduction to Java Programming Language Notes By Adil Aslam
  94. 94. Method Overriding in Java Introduction to Java Programming Language Notes By Adil Aslam
  95. 95. Method Overriding in Java • Declaring a method in subclass which is already present in parent class is known as method overriding. • In other words 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 subclass provides the specific implementation of the method that has been provided by one of its parent class, it is known as method overriding. Introduction to Java Programming Language Notes By Adil Aslam OR OR
  96. 96. Method Overriding in Java • Declaring a method in subclass which is already present in parent class is known as method overriding. • In other words 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 subclass provides the specific implementation of the method that has been provided by one of its parent class, it is known as method overriding. Introduction to Java Programming Language Notes By Adil Aslam OR OR Without Inheritance Method Overriding is not Possible
  97. 97. Method Overriding in Java • Advantage of Java Method Overriding • Method Overriding is used to provide specific implementation of a method that is already provided by its super class. • Method Overriding is used for Runtime Polymorphism • Rules for Method Overriding • method must have same name as in the parent class. • method must have same parameter as in the parent class. • must be IS-A relationship (inheritance). Introduction to Java Programming Language Notes By Adil Aslam
  98. 98. Problem Without Method Overriding class Vehicle{ void run() { System.out.println("Vehicle is running"); } } class Bike extends Vehicle{ public static void main(String args[]){ Bike obj = new Bike(); obj.run(); } } Introduction to Java Programming Language Notes By Adil Aslam Problem is that I have to provide a specific implementation of run() method in subclass that is why we use method overriding.
  99. 99. Problem Without Method Overriding class Vehicle{ void run() { System.out.println("Vehicle is running"); } } class Bike extends Vehicle{ public static void main(String args[]){ Bike obj = new Bike(); obj.run(); } } Introduction to Java Programming Language Notes By Adil Aslam Problem is that I have to provide a specific implementation of run() method in subclass that is why we use method overriding. Output is: Vehicle is running
  100. 100. Example of Method Overriding class Vehicle{ void run(){ System.out.println("Vehicle is running");} } class Bike extends Vehicle{ void run(){ System.out.println("Bike is running safely");} public static void main(String args[]){ Bike obj = new Bike(); obj.run(); } } Introduction to Java Programming Language Notes By Adil Aslam
  101. 101. Example of Method Overriding class Vehicle{ void run(){ System.out.println("Vehicle is running");} } class Bike extends Vehicle{ void run(){ System.out.println("Bike is running safely");} public static void main(String args[]){ Bike obj = new Bike(); obj.run(); } } Introduction to Java Programming Language Notes By Adil Aslam Method name are same
  102. 102. Example of Method Overriding class Vehicle{ void run(){ System.out.println("Vehicle is running");} } class Bike extends Vehicle{ void run(){ System.out.println("Bike is running safely");} public static void main(String args[]){ Bike obj = new Bike(); obj.run(); } } Introduction to Java Programming Language Notes By Adil Aslam In this example, we have defined the run method in the subclass as defined in the parent class but it has some specific implementation. The name and parameter of the method is same and there is IS-A relationship between the classes, so there is method overriding.
  103. 103. Example of Method Overriding class Vehicle{ void run(){ System.out.println("Vehicle is running");} } class Bike extends Vehicle{ void run(){ System.out.println("Bike is running safely");} public static void main(String args[]){ Bike obj = new Bike(); obj.run(); } } Introduction to Java Programming Language Notes By Adil Aslam Output is: Bike is running safely
  104. 104. Real Example of Java Method Overriding • Consider a scenario, Bank is a class that provides functionality to get rate of interest. But, rate of interest varies according to banks. For example, SBI, ICICI and AXIS banks could provide 8%, 7% and 9% rate of interest. Introduction to Java Programming Language Notes By Adil Aslam
  105. 105. Real Example of Java Method Overriding-1 class Bank{ int getInterest(){return 0;} } class SBI extends Bank{ int getInterest(){return 8;} } class ICICI extends Bank{ int getInterest(){return 7;} } class AXIS extends Bank{ int getInterest(){return 9;} } Introduction to Java Programming Language Notes By Adil Aslam
  106. 106. Real Example of Java Method Overriding-2 class Test{ 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.getInterest()); System.out.println("ICICI Rate of Interest: "+i.getInterest()); System.out.println("AXIS Rate of Interest: "+a.getInterest()); } } Introduction to Java Programming Language Notes By Adil Aslam Output is: SBI Rate of Interest: 8 ICICI Rate of Interest: 7 AXIS Rate of Interest: 9
  107. 107. Method Overriding (Same Argument List) public class Base { public int calculate(int num1,int num2) { return num1+num2; } } class Derived extends Base { public int calculate(int num1,int num2) { return num1*num2; } public static void main(String[] args) { Derived b1 = new Derived(); int result = b1.calculate(10, 10); System.out.println("Result : " + result); } } Introduction to Java Programming Language Notes By Adil Aslam
  108. 108. Method Overriding (Same Argument List) public class Base { public int calculate(int num1,int num2) { return num1+num2; } } class Derived extends Base { public int calculate(int num1,int num2) { return num1*num2; } public static void main(String[] args) { Derived b1 = new Derived(); int result = b1.calculate(10, 10); System.out.println("Result : " + result); } } Introduction to Java Programming Language Notes By Adil Aslam Both Methods Having same number of Parameters List
  109. 109. Method Overriding (Same Argument List) public class Base { public int calculate(int num1,int num2) { return num1+num2; } } class Derived extends Base { public int calculate(int num1,int num2) { return num1*num2; } public static void main(String[] args) { Derived b1 = new Derived(); int result = b1.calculate(10, 10); System.out.println("Result : " + result); } } Introduction to Java Programming Language Notes By Adil Aslam Both Methods Having same number of Parameters List Argument List is also same as Parameter List
  110. 110. Method Overriding (Same Argument List) public class Base { public int calculate(int num1,int num2) { return num1+num2; } } class Derived extends Base { public int calculate(int num1,int num2) { return num1*num2; } public static void main(String[] args) { Derived b1 = new Derived(); int result = b1.calculate(10, 10); System.out.println("Result : " + result); } } Introduction to Java Programming Language Notes By Adil Aslam Both Methods Having same number of Parameters List Argument List is also same as Parameter List Output is: Result : 100
  111. 111. Method Overriding in Dynamic Method Dispatch • Dynamic method dispatch is a technique which enables us to assign the base class reference to a child class object. • Let’s see an Example in next slide in which, that the base class reference is assigned to child class object. Introduction to Java Programming Language Notes By Adil Aslam
  112. 112. Method Overriding in Dynamic Method Dispatch-1 class ABC{ public void disp() { System.out.println("disp() method of parent class"); } public void abc() { System.out.println("abc() method of parent class"); } } Introduction to Java Programming Language Notes By Adil Aslam
  113. 113. Method Overriding in Dynamic Method Dispatch-2 class Test extends ABC{ public void disp(){ System.out.println("disp() method of Child class"); } public void xyz(){ System.out.println("xyz() method of Child class"); } public static void main( String args[]) { //Parent class reference to child class object ABC obj = new Test(); obj.disp(); obj.abc(); } } Introduction to Java Programming Language Notes By Adil Aslam
  114. 114. Method Overriding in Dynamic Method Dispatch-2 class Test extends ABC{ public void disp(){ System.out.println("disp() method of Child class"); } public void xyz(){ System.out.println("xyz() method of Child class"); } public static void main( String args[]) { //Parent class reference to child class object ABC obj = new Test(); obj.disp(); obj.abc(); } } Introduction to Java Programming Language Notes By Adil Aslam Output is: disp() method of Child class abc() method of parent class
  115. 115. Explanation of Previous Program • Note: In dynamic method dispatch the object can call the overriding methods of child class and all the non-overridden methods of base class but it cannot call the methods which are newly declared in the child class. In the above example the object obj was able to call the disp()(overriding method) and abc()(non-overridden method of base class). • However if you try to call the xyz() method (which has been newly declared in Test class) [obj.xyz()] then it would give compilation error with the following message: Introduction to Java Programming Language Notes By Adil Aslam Exception in thread "main" java.lang.Error: Unresolved compilation problem: The method xyz() is undefined for the type ABC
  116. 116. Method Overriding in Java • Can we override static method? • No, static method cannot be overridden. It can be proved by runtime polymorphism, so we will learn it later. • Why we cannot override static method? • Because static method is bound with class whereas instance method is bound with object. Static belongs to class area and instance belongs to heap area. • Can we override java main method? • No, because main is a static method. Introduction to Java Programming Language Notes By Adil Aslam
  117. 117. Rules for Method Overriding • The argument list should be exactly the same as that of the overridden method. • The return type should be the same or a subtype of the return type declared in the original overridden method in the superclass. • The access level cannot be more restrictive than the overridden method's access level. For example: If the superclass method is declared public then the overriding method in the sub class cannot be either private or protected. Introduction to Java Programming Language Notes By Adil Aslam
  118. 118. Rules for Method Overriding • Instance methods can be overridden only if they are inherited by the subclass. • A method declared final cannot be overridden. • A method declared static cannot be overridden but can be re-declared. • If a method cannot be inherited, then it cannot be overridden. Introduction to Java Programming Language Notes By Adil Aslam
  119. 119. Rules for Method Overriding • A subclass within the same package as the instance's superclass can override any superclass method that is not declared private or final. • A subclass in a different package can only override the non-final methods declared public or protected. • An overriding method can throw any uncheck exceptions, regardless of whether the overridden method throws exceptions or not. However, the overriding method should not throw checked exceptions that are new or broader than the ones declared by the overridden method. The overriding method can throw narrower or fewer exceptions than the overridden method. Introduction to Java Programming Language Notes By Adil Aslam
  120. 120. Java Access Modifiers With Method Overriding • Access level cannot be lowered down or restricted than the overridden method’s access level. • Suppose currently method in the Parent class is having the access level public then we cannot override the method with access level as private and protected. • In Next slide is the table which summarized the which are the allowed ways of modifing the access level of overriden method Introduction to Java Programming Language Notes By Adil Aslam
  121. 121. Java Access Modifiers With Method Overriding Introduction to Java Programming Language Notes By Adil Aslam Access Level in Parent Access Level in Child Allowed ? default default Allowed default public Allowed default protected Allowed default private Not Allowed public default Not Allowed public public Allowed public protected Not Allowed public private Not Allowed protected default Not Allowed protected public Allowed protected protected Allowed protected private Not Allowed
  122. 122. Java Access Modifiers With Method Overriding public class Base { public int calculate(int num1,int num2) { return num1+num2; } } class Derived extends Base { int calculate(int num1,int num2) { //Compiler Error return num1*num2; } public static void main(String[] args) { Derived b1 = new Derived(); int result = b1.calculate(10, 10); System.out.println("Result : " + result); } } Introduction to Java Programming Language Notes By Adil Aslam Compiler Error because in the parent class, Method has Access level public while we have made access level as default in the child class
  123. 123. Method Overriding • Can we override java main method? • No, because main is a static method. • Overriding and constructor • Constructors cannot be overridden. • Because constructors are not methods and a subclass’ constructor cannot have same name as a superclass’ one, so there’s nothing relates between constructors and overriding. Introduction to Java Programming Language Notes By Adil Aslam
  124. 124. Method Overriding • A method declared static cannot be overridden but can be re-declared. • Consider the following method declared inside the Parent Class: • Then child class cannot override static method from parent class but it can redeclare it just by changing the method body like this: • However we have to keep the method static in the child class, we cannot make it non-static in the child class, So following method declaration inside child class will throw error Introduction to Java Programming Language Notes By Adil Aslam public static int calculate(int num1,int num2) { return num1+num2; } public static int calculate(int num1,int num2) { return num1*num2; } public int calculate(int num1,int num2) { //without static return num1*num2; }
  125. 125. Difference between Overloading and Overriding Overloading Overriding Method overloading is used to increase the readability of the program. Method overriding is used to provide the specific implementation of the method that is already provided by its super class. Method overloading is performed within class. Method overriding occurs in two classes that have IS-A (inheritance) relationship. In case of method overloading, parameter must be different. In case of method overriding, parameter must be same. Method signature must be different. Method signature must be same. Private, static and final methods can be overloaded. Private, static and final methods can not be override. Introduction to Java Programming Language Notes By Adil Aslam
  126. 126. Difference between Overloading and Overriding Overloading Overriding Access modifiers point of view no restriction. Access modifiers point of view not reduced scope of Access modifiers but increased. Method overloading is the example of compile time polymorphism. Method overriding is the example of run time polymorphism. Overloading can be exhibited both are method and constructor level. Overriding can be exhibited only at method label. Overloading can be done at both static and non-static methods. Overriding can be done only at non- static method. For overloading methods return type may or may not be same. For overriding method return type should be same. Introduction to Java Programming Language Notes By Adil Aslam
  127. 127. Difference between Overloading and Overriding Introduction to Java Programming Language Notes By Adil Aslam
  128. 128. Java Method Overloading Example class OverloadingExample{ static int add(int a, int b) { return a+b; } static int add(int a, int b, int c) { return a+b+c; } } Introduction to Java Programming Language Notes By Adil Aslam
  129. 129. Java Method Overriding Example class Animal{ void eat(){ System.out.println(“Eating"); } } class Dog extends Animal{ void eat(){ System.out.println("Eating Bread"); } } Introduction to Java Programming Language Notes By Adil Aslam
  130. 130. super keyword in java Introduction to Java Programming Language Notes By Adil Aslam
  131. 131. super keyword in java • Super keyword in java is a reference variable that is used to refer parent class object. Super is an implicit keyword create by JVM and supply each and every java program for performing important role in three places. • At variable level • At method level • At constructor level • Need of super keyword: • Whenever the derived class is inherits the base class features, there is a possibility that base class features are similar to derived class features and JVM gets an ambiguity. In order to differentiate between base class features and derived class features must be preceded by super keyword. Introduction to Java Programming Language Notes By Adil Aslam
  132. 132. super keyword in java • Usage of java super Keyword • We can user super keyword by using three ways: • Accessing Instance Variable of Parent Class (Variable Level) • Accessing Parent Class Method (Method Level) • Accessing Parent Class Constructor (Constructor Level) Introduction to Java Programming Language Notes By Adil Aslam
  133. 133. super keyword in java • Super at Variable Level: • Whenever the derived class inherit base class data members there is a possibility that base class data member are similar to derived class data member and JVM gets an ambiguity. • In order to differentiate between the data member of base class and derived class, in the context of derived class the base class data members must be preceded by super keyword. • Syntax • if we are not writing super keyword before the base class data member name than it will be referred as current class data member name and base class data member are hidden in the context of derived class. Introduction to Java Programming Language Notes By Adil Aslam super.baseclass datamember name
  134. 134. Program without using super keyword class Employee { float salary=10000; } class HR extends Employee { float salary=20000; void display() { //print current class salary System.out.println("Salary is: "+salary); } public static void main(String[] args) { HR obj=new HR(); obj.display(); } } Introduction to Java Programming Language Notes By Adil Aslam
  135. 135. Program without using super keyword class Employee { float salary=10000; } class HR extends Employee { float salary=20000; void display() { //print current class salary System.out.println("Salary is: "+salary); } public static void main(String[] args) { HR obj=new HR(); obj.display(); } } Introduction to Java Programming Language Notes By Adil Aslam Both Instance Variables Having same Name
  136. 136. Program without using super keyword class Employee { float salary=10000; } class HR extends Employee { float salary=20000; void display() { //print current class salary System.out.println("Salary is: "+salary); } public static void main(String[] args) { HR obj=new HR(); obj.display(); } } Introduction to Java Programming Language Notes By Adil Aslam Output is: Salary is: 20000 In the this program in Employee and HR class salary is common properties of both class the instance of current or derived class is referred by instance by default but here we want to refer base class instance variable that is why we use super keyword to distinguish between parent or base class instance variable and current or derived class instance variable.
  137. 137. Program using super keyword at Variable level class Employee { float salary=10000; } class HR extends Employee { float salary=20000; void display() { //print base class salary System.out.println("Salary is: "+super.salary); } public static void main(String[] args) { HR obj=new HR(); obj.display(); } } Introduction to Java Programming Language Notes By Adil Aslam
  138. 138. Program using super keyword at Variable level class Employee { float salary=10000; } class HR extends Employee { float salary=20000; void display() { //print base class salary System.out.println("Salary is: "+super.salary); } public static void main(String[] args) { HR obj=new HR(); obj.display(); } } Introduction to Java Programming Language Notes By Adil Aslam Using Super Keyword Here
  139. 139. Program using super keyword at Variable level class Employee { float salary=10000; } class HR extends Employee { float salary=20000; void display() { //print base class salary System.out.println("Salary is: "+super.salary); } public static void main(String[] args) { HR obj=new HR(); obj.display(); } } Introduction to Java Programming Language Notes By Adil Aslam Output is: Salary is: 10000
  140. 140. super keyword in java • Super at Method Level • The super keyword can also be used to invoke or call parent class method. It should be use in case of method overriding. In other word super keyword use when base class method name and derived class method name have same name. • Syntax Introduction to Java Programming Language Notes By Adil Aslam Super.method-name();
  141. 141. Example of super keyword at Method level class Student{ void message(){ System.out.println("Good Morning Sir"); } } class Faculty extends Student{ void message(){ System.out.println("Good Morning Students"); } void display(){ message(); //will invoke or call current class message() method super.message(); //will invoke or call parent class message() method } public static void main(String args[]) { Faculty s=new Faculty(); s.display(); } } Introduction to Java Programming Language Notes By Adil Aslam
  142. 142. Example of super keyword at Method level class Student{ void message(){ System.out.println("Good Morning Sir"); } } class Faculty extends Student{ void message(){ System.out.println("Good Morning Students"); } void display(){ message(); //will invoke or call current class message() method super.message(); //will invoke or call parent class message() method } public static void main(String args[]) { Faculty s=new Faculty(); s.display(); } } Introduction to Java Programming Language Notes By Adil Aslam Output is: Good Morning Students Good Morning Sir
  143. 143. Explanation of Previous Program • In the previous example Student and Faculty both classes have message() method if we call message() method from Student class, it will call the message() method of Student class not of Person class because priority of local is high. • So by using super we can call Student class method in Faculty. • In case there is no method in subclass as parent, there is no need to use super. In the example given in next slide message() method is invoked from Student class but Student class does not have message() method, so we can directly call message() method. Introduction to Java Programming Language Notes By Adil Aslam
  144. 144. Program where super is not Required class Student{ void message(){ System.out.println("Good Morning Sir"); } } class Faculty extends Student{ void display(){ message(); } public static void main(String args[]) { Faculty s=new Faculty(); s.display(); } } Introduction to Java Programming Language Notes By Adil Aslam Output is: Good Morning Sir
  145. 145. super keyword in java • Super at Constructor Level • The super keyword can also be used to invoke or call the parent class constructor. Constructor are calling from bottom to top and executing from top to bottom. • To establish the connection between base class constructor and derived class constructors JVM provides two implicit methods they are: • Super() • Super(...) Introduction to Java Programming Language Notes By Adil Aslam
  146. 146. Super at Constructor Level • Super() • Super() It is used for calling super class default constructor from the context of derived class constructors. • Syntax Introduction to Java Programming Language Notes By Adil Aslam super();
  147. 147. Super keyword used to call base class Constructor class Employee{ Employee(){ System.out.println("Employee class Constructor"); } } class HR extends Employee{ HR(){ super(); //will invoke or call parent class constructor System.out.println("HR class Constructor"); } public static void main(String[] args){ HR obj=new HR(); } } Introduction to Java Programming Language Notes By Adil Aslam
  148. 148. Super keyword used to call base class Constructor class Employee{ Employee(){ System.out.println("Employee class Constructor"); } } class HR extends Employee{ HR(){ super(); //will invoke or call parent class constructor System.out.println("HR class Constructor"); } public static void main(String[] args){ HR obj=new HR(); } } Introduction to Java Programming Language Notes By Adil Aslam Output is: Employee class Constructor HR class Constructor
  149. 149. Explanation of Previous Program • Note: super() is added in each class constructor automatically by compiler. Introduction to Java Programming Language Notes By Adil Aslam class HR { } class HR { HR(); { super(); //First } } Compiler As we know well that default constructor is provided by compiler automatically but it also adds super() for the first statement. If you are creating your own constructor and we don't have either this() or super() as the first statement, compiler will provide super() as the first statement of the constructor.
  150. 150. Super keyword used to call base class Constructor class Employee{ Employee(){ System.out.println("Employee class Constructor"); } } class HR extends Employee{ HR(){ System.out.println("HR class Constructor"); super(); } public static void main(String[] args){ HR obj=new HR(); } } Introduction to Java Programming Language Notes By Adil Aslam Compiler Error Call to super Class Constructor must be first statement in Constructor
  151. 151. Super at Constructor Level • Super(...) • Super(...) It is used for calling super class parameterize constructor from the context of derived class constructor. • Syntax Introduction to Java Programming Language Notes By Adil Aslam super(Arguments_List);
  152. 152. class Employee{ int a; Employee(int a){ this.a=a; } public void getValue() { System.out.println("Value is:"+a); } } class HR extends Employee{ HR(int a){ super(a); //Invoking base class parameterized constructor } public static void main(String[] args){ HR obj=new HR(10); obj.getValue(); } } Introduction to Java Programming Language Notes By Adil Aslam
  153. 153. class Employee{ int a; Employee(int a){ this.a=a; } public void getValue() { System.out.println("Value is:"+a); } } class HR extends Employee{ HR(int a){ super(a); } public static void main(String[] args){ HR obj=new HR(10); obj.getValue(); } } Introduction to Java Programming Language Notes By Adil Aslam Output is: Value is:10 Constructor Parameters and Arguments List while calling the Constructor Must be Same
  154. 154. • The following diagram use possibilities of using super() and super(........) Introduction to Java Programming Language Notes By Adil Aslam
  155. 155. super keyword in java • Rule 1 and Rule 3 • Whenever the derived class constructor want to call default constructor of base class, in the context of derived class constructors we write super(). Which is optional to write because every base class constructor contains single form of default constructor? • Rule 2 and Rule 4 • Whenever the derived class constructor wants to call parameterized constructor of base class in the context of derived class constructor we must write super(...). which is mandatory to write because a base class may contain multiple forms of parameterized constructors. Introduction to Java Programming Language Notes By Adil Aslam
  156. 156. final keyword in java Introduction to Java Programming Language Notes By Adil Aslam
  157. 157. Final Keyword In Java • The final keyword in java is used to restrict the user. The java final keyword can be used in many context. • Final can be: • variable • method • class • The final keyword can be applied with the variables, a final variable that have no value it is called blank final variable or uninitialized final variable. It can be initialized in the constructor only. The blank final variable can be static also which will be initialized in the static block only. We will have detailed learning of these. Let's first learn the basics of final keyword. Introduction to Java Programming Language Notes By Adil Aslam
  158. 158. final variable • final variables: If you use a variable as a final then the value of variable is become constant. We cannot change the value of a final variable once it is initialized. • Syntax • Example Introduction to Java Programming Language Notes By Adil Aslam final data_type variable_name= Some_Value; final int data= 10;
  159. 159. Example of final variable class Test{ final int MAX_VALUE=99; void myMethod(){ MAX_VALUE=101; } public static void main(String args[]){ Test obj=new Test(); obj.myMethod(); } } Introduction to Java Programming Language Notes By Adil Aslam Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - cannot assign a value to final variable MAX_VALUE Compiler Error We got a compilation error in this program because we tried to change the value of a final variable “MAX_VALUE”.
  160. 160. Final Keyword In Java • Final at method level It makes a method final, meaning that sub classes can not override this method. The compiler checks and gives an error if you try to override the method. • When we want to restrict overriding, then make a method as a final. • Syntax Introduction to Java Programming Language Notes By Adil Aslam public final void fun() { ....... }
  161. 161. Example of Final Keyword at Method Level class Bike{ final void run(){ System.out.println("running");} } class Honda extends Bike{ void run(){ System.out.println("running safely with 100kmph"); } public static void main(String args[]){ Honda honda= new Honda(); honda.run(); } } Introduction to Java Programming Language Notes By Adil Aslam
  162. 162. Example of Final Keyword at Method Level class Bike{ final void run(){ System.out.println("running");} } class Honda extends Bike{ void run(){ System.out.println("running safely with 100kmph"); } public static void main(String args[]){ Honda honda= new Honda(); honda.run(); } } Introduction to Java Programming Language Notes By Adil Aslam Final Method cannot override it Output is: Compile Time Error
  163. 163. Final Keyword In Java • Final at class level It makes a class final, meaning that the class can not be inheriting by other classes. When we want to restrict inheritance then make class as a final. • Syntax Introduction to Java Programming Language Notes By Adil Aslam public final class A { ...... ...... } public class B extends A { // it gives an error, because we can not inherit final class }
  164. 164. Example of final keyword at class level final class Bike{} class Honda extends Bike{ void run(){ System.out.println(“Running"); } public static void main(String args[]){ Honda1 honda= new Honda(); honda.run(); } } Introduction to Java Programming Language Notes By Adil Aslam
  165. 165. Example of final keyword at class level final class Bike{} class Honda extends Bike{ void run(){ System.out.println(“Running"); } public static void main(String args[]){ Honda honda= new Honda(); honda.run(); } } Introduction to Java Programming Language Notes By Adil Aslam If a class is final, then we cannot extend it. Compiler Error
  166. 166. Final Keyword In Java • Q) Is final method inherited? • Ans) Yes, final method is inherited but we cannot override it. For Example: Introduction to Java Programming Language Notes By Adil Aslam class Bike{ final void run(){ System.out.println("running...");} } class Honda extends Bike{ public static void main(String args[]){ new Honda().run(); } } Output is: running...
  167. 167. Final Keyword In Java • blank or uninitialized final variable • A final variable that is not initialized at the time of declaration is known as blank final variable. • If you want to create a variable that is initialized at the time of creating object and once initialized may not be changed, it is useful. For example PAN CARD number of an employee. • It can be initialized only in constructor. • Example of blank final variable Introduction to Java Programming Language Notes By Adil Aslam class Student{ int id; String name; final String PAN_CARD_NUMBER; ... }
  168. 168. Final Keyword In Java initialize blank final variable Introduction to Java Programming Language Notes By Adil Aslam class Bike{ final int speedlimit; //blank final variable Bike(){ speedlimit=50; System.out.println(speedlimit); } public static void main(String args[]){ new Bike(); } } Output is: 50
  169. 169. Final Keyword In Java • What are the advantages of blank final variables? • Blank final variables allow the Programmer to make immutable data types. That is, final blank variables allow the class to declare immutable fields which are initialized at runtime by passing arguments to a constructor. Once assigned, the value cannot be changed accidentally. • Can we declare a constructor final? • No, it is not possible. Introduction to Java Programming Language Notes By Adil Aslam
  170. 170. Final Keyword In Java • static blank final variable • A static final variable that is not initialized at the time of declaration is known as static blank final variable. It can be initialized only in static block. Introduction to Java Programming Language Notes By Adil Aslam class A{ static final int data; //static blank final variable static{ data=50;} public static void main(String args[]){ System.out.println(A.data); } } Output is: 50
  171. 171. Final Keyword In Java • final Parameter in Method • If we declare any parameter as final, you cannot change the value of it. Introduction to Java Programming Language Notes By Adil Aslam class Bike{ int cube(final int n){ n=n+2; //can't be changed as n is final n*n*n; } public static void main(String args[]){ Bike b=new Bike(); b.cube(5); } } Output is: Compile Time Error
  172. 172. Some Important Points : final Keyword • Final Keyword can be applied only on Method, Class and Variable • Final Variable must be initialized at the time of declaration or inside constructor • Re-Assigning Value is not allowed for final member variable • Local Final Variable should be initialized during the time of declaration • Final and Finally both are different. Finally keyword is used on Exception handling in Java Introduction to Java Programming Language Notes By Adil Aslam
  173. 173. final Keyword Introduction to Java Programming Language Notes By Adil Aslam Final Entity Description Final Value Final Value cannot be modified Final Method Final Method cannot be overriden Final Class Final Class cannot be inherited
  174. 174. instanceof operator in java Introduction to Java Programming Language Notes By Adil Aslam
  175. 175. Java Instanceof Operator • The java instanceof operator is used to test whether the object is an instance of the specified type (class or subclass or interface). • The instanceof in java is also known as type comparison operator because it compares the instance with type. It returns either true or false. • If we apply the instanceof operator with any variable that has null value, it returns false. Introduction to Java Programming Language Notes By Adil Aslam
  176. 176. Example of Instanceof class Test{ public static void main(String args[]){ Object t=0; Test s=new Test(); System.out.println(s instanceof Test); //true System.out.println(t instanceof Test); //false } } Introduction to Java Programming Language Notes By Adil Aslam Output is: true false
  177. 177. Another Example of java instanceof Operator class Animal{} //Dog inherits Animal class Dog extends Animal{ public static void main(String args[]){ Animal n=new Animal(); Dog d=new Dog(); System.out.println(d instanceof Animal); //true System.out.println(n instanceof Animal); //true } } Introduction to Java Programming Language Notes By Adil Aslam Output is: true true
  178. 178. IS-A Relationship Verification class FourWheeler extends Vehicle{} class TwoWheeler extends Vehicle{} class Car extends FourWheeler{} public class Vehicle { public static void main( String[] args ) { FourWheeler v1 = new FourWheeler(); TwoWheeler v2 = new TwoWheeler(); Car v3 = new Car(); System.out.println(v1 instanceof Vehicle); System.out.println(v2 instanceof Vehicle); System.out.println(v3 instanceof Vehicle); System.out.println(v3 instanceof FourWheeler); } } Introduction to Java Programming Language Notes By Adil Aslam
  179. 179. IS-A Relationship Verification class FourWheeler extends Vehicle{} class TwoWheeler extends Vehicle{} class Car extends FourWheeler{} public class Vehicle { public static void main( String[] args ) { FourWheeler v1 = new FourWheeler(); TwoWheeler v2 = new TwoWheeler(); Car v3 = new Car(); System.out.println(v1 instanceof Vehicle); System.out.println(v2 instanceof Vehicle); System.out.println(v3 instanceof Vehicle); System.out.println(v3 instanceof FourWheeler); } } Introduction to Java Programming Language Notes By Adil Aslam Output is: true true true true
  180. 180. Instanceof in Java with a Variable that value null Value • If we apply instanceof operator with a variable that have null value, it returns false. Let's see the example given below where we apply instanceof operator with the variable that have null value. Introduction to Java Programming Language Notes By Adil Aslam class Vehicle{ public static void main(String args[]){ Vehicle v=new Vehicle(); Vehicle d=null; System.out.println(v instanceof Vehicle); //true System.out.println(d instanceof Vehicle); //false } } Output is: true false
  181. 181. Java Instanceof Operator • The instanceof keyword can also be used to test if an object is of a specified type. • Example Introduction to Java Programming Language Notes By Adil Aslam if (objectReference instanceof type) public class Test { public static void main(String[] a) { String s = "Hello"; if (s instanceof java.lang.String) { System.out.println("is a String"); } } } Output is: is a String
  182. 182. Java Type Casting – Inheritance • Converting one type of value to another is called as Type Casting. • Different Forms of Type Casting : Introduction to Java Programming Language Notes By Adil Aslam
  183. 183. Java Type Casting – Inheritance • Up Casting • We can cast an instance of a child class to its parent class. Casting an object of child class to a parent class is called upcasting. • Consider the following example, Assuming that TwoWheeler is a subclass of Vehicle. Introduction to Java Programming Language Notes By Adil Aslam Vehicle v2 = new TwoWheeler();
  184. 184. Java Type Casting – Inheritance • Down Casting • Casting an object of a parent class to its child class is called downcasting. • If we perform it directly, compiler gives Compilation error. • If we perform it by typecasting, ClassCastException is thrown at runtime. But if we use instanceof operator, downcasting is possible. • Consider the following example, Assuming that TwoWheeler is a subclass of Vehicle. Following is an example of the down casting : Introduction to Java Programming Language Notes By Adil Aslam TwoWheeler v3 = new Vehicle(); //Compilation error TwoWheeler v3 = (TwoWheeler) new Vehicle(); //Compiles successfully but ClassCastException is thrown at runtime
  185. 185. Java Type Casting – Inheritance Introduction to Java Programming Language Notes By Adil Aslam
  186. 186. Example of Downcasting with Instanceof Operator class Parent { } class Child extends Parent { static void method(Parent a) { if(a instanceof Child){ Child d=(Child)a; //downcasting System.out.println("Successfully Casting"); } } public static void main (String [] args) { Parent a=new Child(); Child.method(a); } } Introduction to Java Programming Language Notes By Adil Aslam
  187. 187. Example of Downcasting with Instanceof Operator class Parent { } class Child extends Parent { static void method(Parent a) { if(a instanceof Child){ Child d=(Child)a; //downcasting System.out.println("Successfully Casting"); } } public static void main (String [] args) { Parent a=new Child(); Child.method(a); } } Introduction to Java Programming Language Notes By Adil Aslam Output is: Successfully Casting
  188. 188. Downcasting Without the use of Java Instanceof class Parent { } class Child extends Parent { static void method(Parent a) { Child d=(Child)a; //downcasting System.out.println("Downcasting Done!"); } public static void main (String [] args) { Parent a=new Child(); Child.method(a); } } Introduction to Java Programming Language Notes By Adil Aslam Output is: Downcasting Done!//Now ClassCastException but not in case of instanceof operator
  189. 189. Java Garbage Collection Introduction to Java Programming Language Notes By Adil Aslam
  190. 190. Java 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. • To do so, 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. Introduction to Java Programming Language Notes By Adil Aslam
  191. 191. Java Garbage Collection • In Java destruction of object from memory is done automatically by the JVM. When there is no reference to an object, then that object is assumed to be no longer needed and the memory occupied by the object are released. This technique is called Garbage Collection. Introduction to Java Programming Language Notes By Adil Aslam Heap Object No Reference Left Heap Object dumped
  192. 192. Java Garbage Collection • Can the Garbage Collection be forced explicitly ? • No, the Garbage Collection can not be forced explicitly. We may request JVM for garbage collection by calling System.gc() method. But This does not guarantee that JVM will perform the garbage collection. • Advantages of Garbage Collection • Programmer doesn't need to worry about dereferencing an object. • It is done automatically by JVM. • Increases memory efficiency and decreases the chances for memory leak. Introduction to Java Programming Language Notes By Adil Aslam
  193. 193. Java Garbage Collection • How can an object be unreferenced? • There are many ways: • By nulling the reference • By assigning a reference to another • By anonymous object etc. • 1) By nulling a reference: Introduction to Java Programming Language Notes By Adil Aslam Student s=new Student(); //Assign null to object s=null;
  194. 194. Java Garbage Collection • 2) By assigning a reference to another: • 3) By anonymous object: Introduction to Java Programming Language Notes By Adil Aslam Student s1=new Student(); Student s2=new Student(); s1=s2; //now the first object referred by e1 is available for garbage collection new Student();
  195. 195. Java Garbage Collection • finalize() method • We have seen that a constructor method is used to initialize an object when it is declare. This process is known as initialization. • Similarly, Java support a concept called finalization, which is just opposite to initialization. We know that Java run-time is an automatic garbage collection system. It automatically frees up the memory resources used by the objects. But objects may hold other non-object resources such as file descriptors or windows system fonts. The garbage collector cannot free these resources. In order to free these resources we must use finalizer method. This is similar to destructors in C++. • The finalizer method is simply finalizer() and can be added to any class. Java call that method whenever it is about to reclaim the space for that object. The finalizer method should explicitly define the task to be performed. Introduction to Java Programming Language Notes By Adil Aslam
  196. 196. Java Garbage Collection • finalize() method • The finalize() method is invoked each time before the object is garbage collected. This method can be used to perform cleanup processing. This method is defined in Object class as: • The Garbage collector of JVM collects only those objects that are created by new keyword. So if you have created any object without new, you can use finalize method to perform cleanup processing (destroying remaining objects). • finalize() method is defined in java.lang.Object class, therefore it is available to all the classes. • finalize() method is declare as protected inside Object class. Introduction to Java Programming Language Notes By Adil Aslam protected void finalize() { }
  197. 197. Java Garbage Collection • gc() method • gc() method is used to call garbage collector explicitly. However gc() method does not guarantee that JVM will perform the garbage collection. • It only request the JVM for garbage collection. • This method is present in System and Runtime class. Introduction to Java Programming Language Notes By Adil Aslam public static void gc() { }
  198. 198. Example of garbage collection in java public class Test{ public void finalize(){ System.out.println("Garbage Collected"); } public static void main(String args[]){ Test g1=new Test(); Test g2=new Test(); g1=null; g2=null; System.gc(); } } Introduction to Java Programming Language Notes By Adil Aslam Output is: Garbage Collected Garbage Collected
  199. 199. Java Garbage Collection • Points to Note • Every class inherits the finalize() method from java.lang.Object. • The finalize method is called by the garbage collector when it determines no more references to the object exist • The finalize method of class Object performs no special action; it simply returns normally. Subclasses of Object may override this definition. • If overriding finalize() it is a good programming practice to use a try-catch-finally statement and to always call super.finalize() as there is no concept of finalizer chaining. • The finalize method is never invoked more than once by a Java virtual machine for any given object. Introduction to Java Programming Language Notes By Adil Aslam
  200. 200. Java Varargs Method Introduction to Java Programming Language Notes By Adil Aslam
  201. 201. Variable Argument or Varargs Methods • The varrags allows the method to accept zero or multiple 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. • Variable arguments or varargs were added in Java 1.5. Introduction to Java Programming Language Notes By Adil Aslam
  202. 202. Variable Argument or Varargs Methods • Variable arguments before Java 1.5 • Prior to Java 1.5 Java programmer mainly have two choices to : • 1. Either overload the method. • 2. Or can take an array or Collection and pass the no of argument wrapped in array or Collection like List, Set or Map. • But the problem with this is to if he is overloading the method and he don’t know about how many arguments he has to handle how many method will be created in the code i.e the code will become clumsy or if he has not created sufficient method then again the codes need to be modified and complied so it’s become repetitive task which is not a good programming practice and requires more maintenance . Introduction to Java Programming Language Notes By Adil Aslam
  203. 203. Variable Argument or Varargs Methods • Advantage of Varargs: • We don't have to provide overloaded methods so less code. • Syntax of varargs: • The varargs uses ellipsis i.e. three dots after the data type. Syntax is as follows: • Ellipse can be used once in method parameter list. Introduction to Java Programming Language Notes By Adil Aslam return_type method_name(data_type... variableName) { //Statements }
  204. 204. Variable Argument or Varargs Methods • Example with one variable-length argument: • A varargs method can have more than one argument. The following code shows that aMethod() accepts three arguments, one of which is a variable-length argument: Introduction to Java Programming Language Notes By Adil Aslam public static int max(int... num) { } public static int aMethod(String str, double d1, long...num) { }
  205. 205. Variable Argument or Varargs Methods • Rules for varargs: • While using the varargs, we must follow some rules otherwise program code won't compile. The rules are as follows: • 1) A varargs method can have a maximum of one variable-length argument. • 2) The variable-length argument of a varargs method must be the last argument in the argument list. Introduction to Java Programming Language Notes By Adil Aslam
  206. 206. Variable Argument or Varargs Methods • A varargs method can have a maximum of one variable-length argument. Introduction to Java Programming Language Notes By Adil Aslam void aMethod(String... a, int... b) { //Compile time error } void aMethod(String... a) { //OK }
  207. 207. Variable Argument or Varargs Methods • A varargs method can have a maximum of one variable-length argument. Introduction to Java Programming Language Notes By Adil Aslam void aMethod(String... a, int... b) { //Compile time error } void aMethod(String... a) { //OK } Here two Variable Arguments Here one Variable Argument
  208. 208. Variable Argument or Varargs Methods • The variable-length argument of a varargs method must be the last argument in the argument list. • Correct Declaration: Introduction to Java Programming Language Notes By Adil Aslam void method(int... a, String b){ //Compile time error } void method(String b, int... a){ //OK }
  209. 209. Program without Using Variable Argument-1 // Simple Program which Calculates Average of two, three and four numbers public class Test{ static double average(int a, int b) { //Average Of two numbers return (a + b)/2; } static double average(int a, int b, int c) { //Average of three numbers return (a + b + c)/3; } static double average(int a, int b, int c, int d) { //Average of four numbers return (a + b + c +d)/4; } Introduction to Java Programming Language Notes By Adil Aslam
  210. 210. Program without Using Variable Argument-2 public static void main(String[] args) { //prints average of two numbers System.out.println(average(10, 20)); //prints average of three numbers System.out.println(average(10, 20, 30)); //prints average of four numbers System.out.println(average(10, 20, 30, 40)); } } Introduction to Java Programming Language Notes By Adil Aslam Output is: 15.0 20.0 25.0
  211. 211. Program without Using Variable Argument-2 public static void main(String[] args) { //prints average of two numbers System.out.println(average(10, 20)); //prints average of three numbers System.out.println(average(10, 20, 30)); //prints average of four numbers System.out.println(average(10, 20, 30, 40)); } } Introduction to Java Programming Language Notes By Adil Aslam What if user wants to calculate average of ‘n‘ numbers. The solution for this question is Varargs or Variable Argument Method.
  212. 212. Example of Varargs public class Test{ static double average(int... a) { int n = a.length; //Average Of 'n' numbers (Calculate length) int sumOfNumbers = 0; //Calculating sum of numbers for(int i : a) { //for each loop sumOfNumbers = sumOfNumbers + i; } return (sumOfNumbers/n); } public static void main(String[] args){ System.out.println(average(10, 20, 30, 40)); System.out.println(average(10, 20, 30, 40, 50, 60)); System.out.println(average(10, 20, 30, 40, 50, 60, 70, 80)); } } Introduction to Java Programming Language Notes By Adil Aslam
  213. 213. Example of Varargs public class Test{ static double average(int... a) { int n = a.length; //Average Of 'n' numbers (Calculate length) int sumOfNumbers = 0; //Calculating sum of numbers for(int i : a) { //for each loop sumOfNumbers = sumOfNumbers + i; } return (sumOfNumbers/n); } public static void main(String[] args){ System.out.println(average(10, 20, 30, 40)); System.out.println(average(10, 20, 30, 40, 50, 60)); System.out.println(average(10, 20, 30, 40, 50, 60, 70, 80)); } } Introduction to Java Programming Language Notes By Adil Aslam Output is: 25.0 35.0 45.0
  214. 214. Explanation of Previous Program • It can be seen from the program that length is used here to find the number of arguments passed to the method. It is possible because varargs are implicitly passed as an array. Whatever arguments are passed as varargs are stored in an array which is referred by the name given to varargs. In this program array name is “a”. • Also note that method is called with different number of argument, first call with four arguments, then six arguments and then with eight arguments. All these calls are handled by the same method which takes varargs. Introduction to Java Programming Language Notes By Adil Aslam
  215. 215. Another Example of Varargs in java class Test{ static void display(String... values){ for(String s:values){ System.out.print(" "+s); } System.out.println(); } public static void main(String args[]){ //one argument display("Hello World"); //four arguments display("My","Name","is","Adil"); } } Introduction to Java Programming Language Notes By Adil Aslam
  216. 216. Another Example of Varargs in java class Test{ static void display(String... values){ for(String s:values){ System.out.print(" "+s); } System.out.println(); } public static void main(String args[]){ //one argument display("Hello World"); //four arguments display("My","Name","is","Adil"); } } Introduction to Java Programming Language Notes By Adil Aslam Output is: Hello World My Name is Adil String type variable Argument
  217. 217. Example of Varargs that is the Last Argument class Test{ static void display(int id, String... values){ System.out.println("ID is: "+id); for(String s:values){ System.out.print(s+" "); } System.out.println(); } public static void main(String args[]){ display(11,"My","Name","is","Adil"); display(22,"Name","is","Hina"); } } Introduction to Java Programming Language Notes By Adil Aslam
  218. 218. Example of Varargs that is the Last Argument class Test{ static void display(int id, String... values){ System.out.println("ID is: "+id); for(String s:values){ System.out.print(s+" "); } System.out.println(); } public static void main(String args[]){ display(11,"My","Name","is","Adil"); display(22,"Name","is","Hina"); } } Introduction to Java Programming Language Notes By Adil Aslam Here Varargs is Last Arguments Output is: ID is: 11 My Name is Adil ID is: 22 Name is Hina
  219. 219. Another Example public class Test { public static int max(int n1, int n2, int... num) { // Initialize max to the maximum of n1 and n2 int max = (n1 > n2 ? n1 : n2); for (int i = 0; i < num.length; i++) { if (num[i] > max) { max = num[i]; } } return max; } public static void main(String[] args) { System.out.println("Max Value is: "+max(50, 30, 10)); System.out.println("Max Value is: "+max(11, 22, 55, 44)); } } Introduction to Java Programming Language Notes By Adil Aslam
  220. 220. Another Example public class Test { public static int max(int n1, int n2, int... num) { // Initialize max to the maximum of n1 and n2 int max = (n1 > n2 ? n1 : n2); for (int i = 0; i < num.length; i++) { if (num[i] > max) { max = num[i]; } } return max; } public static void main(String[] args) { System.out.println("Max Value is: "+max(50, 30, 10)); System.out.println("Max Value is: "+max(11, 22, 55, 44)); } } Introduction to Java Programming Language Notes By Adil Aslam Output is: Max Value is: 50 Max Value is: 55
  221. 221. Variable Argument or Varargs Methods • VarArgs internally behave like array. The best example for this is, we can replace String array argument of main method with VarArgs. Introduction to Java Programming Language Notes By Adil Aslam public class Test { //main method taking VarArgs as an argument public static void main(String... args) { System.out.println("Hello World"); } }
  222. 222. Variable Argument or Varargs Methods • Even constructors can have VarArgs as an argument. Introduction to Java Programming Language Notes By Adil Aslam public class Test { public Test(Double... d) { //Constructor having Variable arguments } public static void main(String[] args) { Test t = new Test(10.2, 15.4); } }
  223. 223. Variable Argument in Constructor public class Test{ public Test(Double... d){ int n = d.length; double sum = 0; for(Double i : d) { sum = sum + i; } System.out.println("Sum is: "+sum); } public static void main(String[] args){ Test t1 = new Test(10.2, 15.4); Test t2 = new Test(25.2,33.4,22.4); } } Introduction to Java Programming Language Notes By Adil Aslam
  224. 224. Variable Argument in Constructor public class Test{ public Test(Double... d){ int n = d.length; double sum = 0; for(Double i : d) { sum = sum + i; } System.out.println("Sum is: "+sum); } public static void main(String[] args){ Test t1 = new Test(10.2, 15.4); Test t2 = new Test(25.2,33.4,22.4); } } Introduction to Java Programming Language Notes By Adil Aslam Output is: Sum is: 25.6 Sum is: 81.0
  225. 225. Overloading Varargs Methods • It is possible to overload a method that takes varargs parameter. Varargs method can be overloaded by : • Types of its varargs parameter can be different. • By adding other parameters. • Example of type of Parameter are different Introduction to Java Programming Language Notes By Adil Aslam public void displayData(String ... values){ } public void displayData(int ... values){ }
  226. 226. Overloading Varargs Methods-1 public class Test{ // Method which has string vararg parameter public void displayData(String ... values){ System.out.println("Number of Arguments: " + values.length); for(String s : values){ System.out.print(s + " "); } System.out.println(); } // Method which has int vararg parameter public void displayData(int ... values){ System.out.println("Number of Arguments: " + values.length); for(int i : values){ System.out.print(i + " "); } System.out.println(); } Introduction to Java Programming Language Notes By Adil Aslam
  227. 227. Overloading Varargs Methods-1 public class Test{ // Method which has string vararg parameter public void displayData(String ... values){ System.out.println("Number of Arguments: " + values.length); for(String s : values){ System.out.print(s + " "); } System.out.println(); } // Method which has int vararg parameter public void displayData(int ... values){ System.out.println("Number of Arguments: " + values.length); for(int i : values){ System.out.print(i + " "); } System.out.println(); } Introduction to Java Programming Language Notes By Adil Aslam Both Method having Different vararg parameter Type
  228. 228. Overloading Varargs Methods-2 public static void main(String[] args) { Test obj = new Test(); // passing four string arguments obj.displayData("My", "Name", "is", "Adil", "Aslam"); // passing two int argument obj.displayData(10, 20); } } Introduction to Java Programming Language Notes By Adil Aslam
  229. 229. Overloading Varargs Methods-2 public static void main(String[] args) { Test obj = new Test(); // passing four string arguments obj.displayData("My", "Name", "is", "Adil", "Aslam"); // passing two int argument obj.displayData(10, 20); } } Introduction to Java Programming Language Notes By Adil Aslam Output is: Number of Argu: 5 My Name is Adil Aslam Number of Argu: 2 10 20

×