SlideShare a Scribd company logo
A closure look at methods and classes
Usingcommandlinearguments
Understandingstatic
Recursion
Methodsandclasses
abstract
continue
for
new
switch
assert
default
package
synchronized
boolean
do
if
private
this
break
double
implements
protected
throw
byte
else
import
public
throws
case
enum
instanceof
return
transient
catch
extends
int
short
try
char
final
interface
static
void
class
finally
long
strictfp
volatile
const
float
native
super
java keywords
A closure look at methods and classes
Usingcommandlinearguments
Understandingstatic
Recursion
Methodsandclasses
overloading
methods and its purpose
If a class have multiple methods by same name but
different parameters it is known as method overloading.
If we have to perform only one operation , having same
name of the methods increases the readability of the
program.
Different ways to overload the method:
1. By changing number of arguments
2. By changing data type
A closure look at methods and classes
Usingcommandlinearguments
Understandingstatic
Recursion
Method overloading with an
example:
// Demonstrate method overloading.
class OverloadDemo
{
void test()
{
System.out.println("No parameters"); }
// Overload test for one integer parameter.
void test(int a) {
System.out.println("a: " + a); }
// Overload test for two integer parameters.
void test(int a, int b) {
System.out.println("a and b: " + a + " " + b); }
// overload test for a double parameter
double test(double a) {
System.out.println("double a: " + a); return a*a; }
}
class Overload {
public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
double result;
// call all versions of test()
ob.test();
ob.test(10);
ob.test(10, 20);
result = ob.test(123.25);
System.out.println("Result of ob.test(123.25): " +
result); } }
This program generates the following output:
No parameters
a: 10
a and b: 10 20
double a: 123.25
Result of ob.test(123.25): 15190.5625
Methodoverloading
A closure look at methods and classes
Usingcommandlinearguments
Understandingstatic
Recursion
Why method overloading is not possible by changing the
return type?
Can we overload main() method?
Method overloading is not possible by changing the return
type of method because there may occur ambiguity.
Yes, we can have any number of main methods in a class
by method overloading
Methodoverloading
A closure look at methods and classes
Usingcommandlinearguments
Understandingstatic
Recursion
What is constructor overloading ?
Just like in case of method overloading you have
multiple methods with same name but different signature , in
Constructor overloading you have multiple constructor with
different signature with only difference that Constructor
doesn't have return type in Java.
Those constructor will be called as overloaded
constructor. Overloading is also another form of
polymorphism in Java which allows to have multiple
constructor with different name in one Class in java.
Constructoroverloading
A closure look at methods and classes
Usingcommandlinearguments
Understandingstatic
Recursion
Why do you overload Constructor?
Allows flexibility while create array list object.
It may be possible that you don't know size of array list
during creation than you can simply use default no argument
constructor but if you know size then its best to use
overloaded
Constructor which takes capacity. Since Array List can also
be created from another Collection, may be from another List
than having another overloaded constructor makes lot
of sense.
By using overloaded constructor you can convert
your Array List into Set or any other collection.
Constructoroverloading
A closure look at methods and classes
Usingcommandlinearguments
Understandingstatic
Recursion
Constructor overload with an
example
/* Here, Box defines three constructors to initialize
the dimensions of a box various ways. */
class Box {
double width;
double height;
double depth;
// constructor used when all dimensions specified
Box(double w, double h, double d) {
width = w;
height = h;
depth = d; }
// constructor used when no dimensions specified
Box() {
width = -1; // use -1 to indicate
height = -1; // an uninitialized
depth = -1; // box }
// constructor used when cube is created
Box(double len) {
width = height = depth = len; }
// compute and return volume
double volume() {
return width * height * depth; } }
class OverloadCons {
public static void main(String args[]) {
// create boxes using the various constructors
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
double vol;
// get volume of first
box vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
// get volume of second
box vol = mybox2.volume();
System.out.println is " + vol);
// get volume of
cube vol = mycube.volume();
System.out.println("Volume of mycube is " + vol);
} }
The output produced by this program is shown
here:
Volume of mybox1 is 3000.0
Volume of mybox2 is -1.0
Volume of mycube is 343.0
Constructoroverloading
A closure look at methods and classes
Usingcommandlinearguments
Understandingstatic
Methodoverloading
Recursion
Recursion is the process of defining something in terms of itself.
As it relates to Java programming, recursion is the attribute that
allows a method to call itself.
A method that calls itself is said to be recursive.
The classic example of recursion is the computation of the factorial
of a number. The factorial of a number N is the product of all the
whole numbers between 1 and N.
For example, 3 factorial is 1 × 2 × 3, or 6. Here is how a factorial
can be computed by use of a recursive method:
Recursion
A closure look at methods and classes
Usingcommandlinearguments
Understandingstatic
Methodoverloading
Recursion with example
// A simple example of recursion.
class Factorial {
// this is a recursive method
int fact(int n) {
int result;
if(n==1)
return 1;
result = fact(n-1) * n; return result; } }
class Recursion { public static void main(String args[]) {
Factorial f = new Factorial(); System.out.println("Factorial of 3 is " +
f.fact(3)); System.out.println("Factorial of 4 is " + f.fact(4));
System.out.println("Factorial of 5 is " + f.fact(5)); } }
The output from this program is shown here: Factorial of 3 is 6 Factorial of
4 is 24 Factorial of 5 is 120
Recursion
A closure look at methods and classes
Usingcommandlinearguments
Understandingstatic
Methodoverloading
Access ControlAccessControl
public private protected < unspecified >
Class allowed Not allowed Not allowed not allowed
Constructor allowed allowed allowed allowed
Variable allowed allowed allowed allowed
method allowed
allowed allowed allowed
Visible ?? class Sub class package
Outside
Package
private Yes No No No
protected Yes Yes Yes No
public Yes Yes Yes Yes
< unspecified > Yes Yes No No
A closure look at methods and classes
Usingcommandlinearguments
Recursion
Methodoverloading
Understanding static and final
Understandingstatic Why do we use static?
There will be times when you will want to define a class
member that will be used
independently of any object of that class.
Instance variables declared as static are, essentially,
global variables. When objects of
its class are declared, no copy of a static variable is made.
Instead, all instances of the class share the same static
variable.
Methods declared as static have several restrictions:
• They can only call other static methods.
• They must only access static data.
• They cannot refer to this or super in any way.
A closure look at methods and classes
Usingcommandlinearguments
Recursion
Methodoverloading
Understanding static
Understandingstatic // Demonstrate static variables, methods, and blocks.
class UseStatic {
static int a = 3;
static int b;
static void meth(int x) {
System.out.println("x = " + x);
System.out.println("a = " + a);
System.out.println("b = " + b);
}
static {
System.out.println("Static block initialized.");
b = a * 4;
}
public static void main(String args[]) {
meth(42);
}
}
A closure look at methods and classes
Usingcommandlinearguments
Recursion
Methodoverloading
Understanding static
Understandingstatic Why main method is declared as static?
Java program's main method has to be declared static because
keyword static allows main to be called without creating an object
of the class in which the main method is defined.
If we omit static keyword before main Java program will
successfully compile but it won't execute.
Inheritance
Usingabstractclassandfinalwith
inheritance
MethodOverriding
Usingsuper
InheritanceBasics
what is inheritance ?
Object-oriented programming allows classes
to inherit commonly used state and behavior from other
classes
The mechanism of deriving a new class from existing
old one is called inheritance.
The old class is known as super class or base class or
parent class
The new class is known as child class or subclass or
derived class.
To inherit properties of base class to sub class we use
extends keyword in the inherited class i.e. in sub class.
Inheritance
Usingabstractclassandfinalwith
inheritance
MethodOverriding
Usingsuper
InheritanceBasics
Why use inheritance ?
For method overriding.
For code reusability.
Inheritance
Usingabstractclassandfinalwith
inheritance
MethodOverriding
Usingsuper
InheritanceBasics
Inheritance with an example.
syntax:
class subclassname extends superclassname
{
variables declaration;
methods declaration;
}
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
}
Inheritance
Usingabstractclassandfinalwith
inheritance
MethodOverriding
Usingsuper
InheritanceBasics
Forms of inheritance:
Inheritance allows subclass to inherit all the variables
and methods of their parent classes.
Inheritance may take different forms:
1. Single inheritance(only one super class).
2. Multiple inheritance(several super classes).
3. Hierarchical inheritance(one super class many sub
classes).
4. Multilevel inheritance(derived from derived class).
Inheritance
Usingabstractclassandfinalwith
inheritance
MethodOverriding
Usingsuper
InheritanceBasics
Single inheritance
A
B
When a class extends another one class only
then we call it a single inheritance.
Class A {
public void methodA() {
System.out.println("Base class method"); }
}
Class B extends A { public void methodB()
{ System.out.println("Child class method");
}
public static void main(String args[]) {
B obj = new B();
obj.methodA(); //calling super class method
obj.methodB(); //calling local method } }
Inheritance
Usingabstractclassandfinalwith
inheritance
MethodOverriding
Usingsuper
InheritanceBasics
In such kind of inheritance one class is inherited by many sub
classes. In below example class B,C and D inherits the same
class A. A is parent class (or base class) of B,C & D.
A
B C D
Hierarchical
inheritance
Account
Current Savings
Fixed-deposit
Inheritance
Usingabstractclassandfinalwith
inheritance
MethodOverriding
Usingsuper
InheritanceBasics
A
B
C
Grand
father
Son
Father
Multilevel
inheritance
Class a
member
Class c
member Class b
member
Class a
member
class A
{…………
………….}
Class B extends A //first
{ ………… level
………..}
class C extends A// second level
{………….
………….}
Inheritance
Usingabstractclassandfinalwith
inheritance
MethodOverriding
Usingsuper
InheritanceBasics
Multiple
inheritance
A B
C
Multiple Inheritance” refers
to the concept of one class
extending (Or inherits) more
than one base class.
The inheritance we learnt
earlier had the concept of one
base class or parent. The
problem with “multiple
inheritance” is that the derived
class will have to manage the
dependency on two base
classes.
Note 1: Multiple Inheritance is very rarely used in software
projects. Using Multiple inheritance often leads to problems
in the hierarchy. This results in unwanted complexity when
further extending the class.
Inheritance
Usingabstractclassandfinalwith
inheritance
InheritanceBasics
Usingsuper
Methodoverriding Overriding methods and its purpose
Overridden methods allow Java to support run-time
polymorphism .
Polymorphism is essential to object-oriented
programming for one reason: it allows a general class to
specify methods that will be common to all of its
derivatives, while allowing subclasses to define the
specific implementation of some or all of those methods
Overridden methods are another way that Java
implements the “one interface, multiple methods” aspect
of polymorphism.
Inheritance
Usingabstractclassandfinalwith
inheritance
InheritanceBasics
Usingsuper
Finalvariables,methodsandclasses Final variables , methods and classes
All methods and variables can be Overridden by default
in subclass.
If we wish to prevent the subclass from overriding the
members of the superclass.
We can declare tem as final using the keyword final as a
modifier.
Ex : final int SIZE=100;
final void showstatus(){………….}
Making a method final ansures that the functionality
defined in this method will never be altered in anyway.
Inheritance
Usingabstractclassandfinalwith
inheritance
InheritanceBasics
Usingsuper
Finalvariables,methodsandclasses Final variables , methods and classes
A class that cannot be subclassed is called a final class
Ex : final class Aclass{…….}
final class Bclass extends Cclass{………….}
Any attempt to inherit these classes will cause an error
and the compiler will not allow it.
Declaring a class final prevents any unwanted extension
to the class.
It also allows the complier to perform some
optimization when a method of a final class is invoked.
Inheritance
Usingabstractclassandfinalwith
inheritance
InheritanceBasics
Usingsuper
Finalizermethod Finalize() method
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 window system fonts.
The garbage collector cannot free these resources. In
order to free these resources we must use finalize
method.tis is similar to destructor in C++.
The finalizer method is simply finalize() and can be
added to any class . Java calls that method whenever it is
about to reclaim te space for that object .
The finalize method should explicitly define the task to
be performed.
Inheritance
Usingabstractclassandfinalwith
inheritance
InheritanceBasics
Usingsuper
Finalizermethod
Using super
super has two general forms.
The first calls the superclass constructor.
The second is used to access a member of the
superclass that has been hidden by a member of a
subclass
Inheritance
Usingabstractclassandfinalwith
inheritance
InheritanceBasics
Usingsuper
Finalizermethod
A first Use for super
class a
{
a(){System.out.println("A");}
}
class b extends a
{
b()
{
super();
System.out.println("B");}
}
class c extends b
{
c(){System.out.println("c");}
}
class last
{
public static void main(String args[])
{
c obj = new c();
}
Inheritance
Usingabstractclassandfinalwith
inheritance
InheritanceBasics
Usingsuper
Finalizermethod A Second Use for super
The second form of super acts somewhat like this,
except that it always refers to the superclass
of the subclass in which it is used. This usage has the
following general form:
super.member
Here, member can be either a method or an instance
variable.
Most applicable to situations in which member names
of a subclass hide members by the same name in the
superclass. Consider this simple class
hierarchy:
Inheritance
Usingabstractclassandfinalwith
inheritance
InheritanceBasics
Usingsuper
Finalizermethod A Second Use for super
// Using super to overcome name hiding.
class A {
int i;
}
// Create a subclass by extending class A.
class B extends A {
int i; // this i hides the i in A
B(int a, int b) {
super.i = a; // i in A
i = b; // i in B
}
void show() {
System.out.println("i in superclass: " + super.i);
System.out.println("i in subclass: " + i);
}
}
class UseSuper {
public static void main(String args[]) {
B subOb = new B(1, 2);
subOb.show();
}
}
This program displays the following:
i in superclass: 1
i in subclass: 2
Inheritance
Usingabstractclass
InheritanceBasics
Usingsuper
Abstractmethodsandclasses Abstract methods and classes
A final class can never be subclassed.
Java allows us to do somethin exactly opposite to this
i.e. we can indicate that te method must always be
redefined in a subclass , thus making overriding
compulsory.
This is done by using the modifier keyword abstract.
Ex : abstract class shape
{
…………..
…………..
abstract void draw();
……………
……………
}
 A class with more than one abstract methods should be
declared as abstract class
Inheritance
Usingabstractclass
InheritanceBasics
Usingsuper
Methodoverriding
Abstract methods and classes
While using abstract classes , following conditions must
satisfy
1. We cannot use abstract classes to instantiate objects
directly.
Ex : Shape s = new Shape()
is illegal because is an abstract class.
2. The abstract methods of an abstract class must be
defined in its subclass.
3. We cannot declare abstract constructors or abstract
static methods.
Inheritance
Commandlinearguments
InheritanceBasics
Usingsuper
Methodoverriding
Command line arguments
Java has included a feature that simplifies the creation of
methods that need to take a variable number of arguments.
This feature is called varargs and it is short for variable-
length arguments. A method that takes a variable number of
arguments is called a variable-arity method, or simply a
varargs method.
Situations that require that a variable number of
arguments be passed to a method are not unusual. For
example, a method that opens an Internet connection might
take a user name, password, filename, protocol, and so on,
but supply defaults if some of this information is not
provided. In this situation, it would be convenient to pass
only the arguments to which the defaults did not apply
Inheritance
Commandlinearguments
InheritanceBasics
Usingsuper
Methodoverriding Command line arguments
// Use an array to pass a variable number of
// arguments to a method. This is the old-style
// approach to variable-length arguments.
class PassArray {
static void vaTest(int v[]) {
System.out.print("Number of args: " + v.length +
" Contents: ");
for(int x : v)
System.out.print(x + " "); System.out.println();
}
public static void main(String args[])
{
// Notice how an array must be created to
// hold the arguments.
int n1[] = { 10 };
int n2[] = { 1, 2, 3 };
int n3[] = { };
vaTest(n1); // 1 arg
vaTest(n2); // 3 args
vaTest(n3); // no args
}
}
The output from the program is shown here:
Number of args: 1 Contents: 10
Number of args: 3 Contents: 1 2 3
Number of args: 0 Contents:
Thank
you
B
C
A
c1
a1
b1
c2
a2
b2
Ad

More Related Content

What's hot (20)

Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in java
kamal kotecha
 
Packages and inbuilt classes of java
Packages and inbuilt classes of javaPackages and inbuilt classes of java
Packages and inbuilt classes of java
kamal kotecha
 
Lecture 4_Java Method-constructor_imp_keywords
Lecture   4_Java Method-constructor_imp_keywordsLecture   4_Java Method-constructor_imp_keywords
Lecture 4_Java Method-constructor_imp_keywords
manish kumar
 
java Method Overloading
java Method Overloadingjava Method Overloading
java Method Overloading
omkar bhagat
 
Java unit2
Java unit2Java unit2
Java unit2
Abhishek Khune
 
Java
JavaJava
Java
Khasim Cise
 
advanced java ppt
advanced java pptadvanced java ppt
advanced java ppt
PreetiDixit22
 
Java
JavaJava
Java
javeed_mhd
 
JAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesJAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examples
Sunil Kumar Gunasekaran
 
Lecture - 3 Variables-data type_operators_oops concept
Lecture - 3 Variables-data type_operators_oops conceptLecture - 3 Variables-data type_operators_oops concept
Lecture - 3 Variables-data type_operators_oops concept
manish kumar
 
Lecture - 5 Control Statement
Lecture - 5 Control StatementLecture - 5 Control Statement
Lecture - 5 Control Statement
manish kumar
 
Java basic tutorial
Java basic tutorialJava basic tutorial
Java basic tutorial
Bui Kiet
 
Ppt on this and super keyword
Ppt on this and super keywordPpt on this and super keyword
Ppt on this and super keyword
tanu_jaswal
 
Java class 3
Java class 3Java class 3
Java class 3
Edureka!
 
Method Overloading In Java
Method Overloading In JavaMethod Overloading In Java
Method Overloading In Java
CharthaGaglani
 
Chapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part IChapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part I
Eduardo Bergavera
 
Java Basics
Java BasicsJava Basics
Java Basics
Rajkattamuri
 
Method overloading
Method overloadingMethod overloading
Method overloading
Lovely Professional University
 
Java Basics
Java BasicsJava Basics
Java Basics
F K
 
Java Reflection
Java ReflectionJava Reflection
Java Reflection
Hamid Ghorbani
 
Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in java
kamal kotecha
 
Packages and inbuilt classes of java
Packages and inbuilt classes of javaPackages and inbuilt classes of java
Packages and inbuilt classes of java
kamal kotecha
 
Lecture 4_Java Method-constructor_imp_keywords
Lecture   4_Java Method-constructor_imp_keywordsLecture   4_Java Method-constructor_imp_keywords
Lecture 4_Java Method-constructor_imp_keywords
manish kumar
 
java Method Overloading
java Method Overloadingjava Method Overloading
java Method Overloading
omkar bhagat
 
JAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesJAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examples
Sunil Kumar Gunasekaran
 
Lecture - 3 Variables-data type_operators_oops concept
Lecture - 3 Variables-data type_operators_oops conceptLecture - 3 Variables-data type_operators_oops concept
Lecture - 3 Variables-data type_operators_oops concept
manish kumar
 
Lecture - 5 Control Statement
Lecture - 5 Control StatementLecture - 5 Control Statement
Lecture - 5 Control Statement
manish kumar
 
Java basic tutorial
Java basic tutorialJava basic tutorial
Java basic tutorial
Bui Kiet
 
Ppt on this and super keyword
Ppt on this and super keywordPpt on this and super keyword
Ppt on this and super keyword
tanu_jaswal
 
Java class 3
Java class 3Java class 3
Java class 3
Edureka!
 
Method Overloading In Java
Method Overloading In JavaMethod Overloading In Java
Method Overloading In Java
CharthaGaglani
 
Chapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part IChapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part I
Eduardo Bergavera
 
Java Basics
Java BasicsJava Basics
Java Basics
F K
 

Viewers also liked (7)

Handling inputs via scanner class
Handling inputs via scanner classHandling inputs via scanner class
Handling inputs via scanner class
simarsimmygrewal
 
Java Serialization
Java SerializationJava Serialization
Java Serialization
jeslie
 
Batch Applications for Java Platform 1.0: Java EE 7 and GlassFish
Batch Applications for Java Platform 1.0: Java EE 7 and GlassFishBatch Applications for Java Platform 1.0: Java EE 7 and GlassFish
Batch Applications for Java Platform 1.0: Java EE 7 and GlassFish
Arun Gupta
 
Java Serialization
Java SerializationJava Serialization
Java Serialization
imypraz
 
Java stream
Java streamJava stream
Java stream
Arati Gadgil
 
IO In Java
IO In JavaIO In Java
IO In Java
parag
 
Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and Streams
Anton Keks
 
Handling inputs via scanner class
Handling inputs via scanner classHandling inputs via scanner class
Handling inputs via scanner class
simarsimmygrewal
 
Java Serialization
Java SerializationJava Serialization
Java Serialization
jeslie
 
Batch Applications for Java Platform 1.0: Java EE 7 and GlassFish
Batch Applications for Java Platform 1.0: Java EE 7 and GlassFishBatch Applications for Java Platform 1.0: Java EE 7 and GlassFish
Batch Applications for Java Platform 1.0: Java EE 7 and GlassFish
Arun Gupta
 
Java Serialization
Java SerializationJava Serialization
Java Serialization
imypraz
 
IO In Java
IO In JavaIO In Java
IO In Java
parag
 
Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and Streams
Anton Keks
 
Ad

Similar to Inheritance (20)

Object Oriented Programming Inheritance with case study
Object Oriented Programming Inheritance with case studyObject Oriented Programming Inheritance with case study
Object Oriented Programming Inheritance with case study
MsPariyalNituLaxman
 
FINAL_DAY8_VISIBILITY_LABELS_Roles and.pptx
FINAL_DAY8_VISIBILITY_LABELS_Roles and.pptxFINAL_DAY8_VISIBILITY_LABELS_Roles and.pptx
FINAL_DAY8_VISIBILITY_LABELS_Roles and.pptx
VGaneshKarthikeyan
 
Inheritance & interface ppt Inheritance
Inheritance & interface ppt  InheritanceInheritance & interface ppt  Inheritance
Inheritance & interface ppt Inheritance
narikamalliy
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
backdoor
 
UNIT-2.pptx CS3391 Inheritance , types, packages and Interfaces
UNIT-2.pptx CS3391 Inheritance , types, packages and InterfacesUNIT-2.pptx CS3391 Inheritance , types, packages and Interfaces
UNIT-2.pptx CS3391 Inheritance , types, packages and Interfaces
SakkaravarthiS1
 
702641313-CS3391-OBJORIENTEDPS-Unit-2.pptx
702641313-CS3391-OBJORIENTEDPS-Unit-2.pptx702641313-CS3391-OBJORIENTEDPS-Unit-2.pptx
702641313-CS3391-OBJORIENTEDPS-Unit-2.pptx
SAJITHABANUS
 
java tutorial 3
 java tutorial 3 java tutorial 3
java tutorial 3
Tushar Desarda
 
introduction to object oriented programming language java
introduction to object oriented programming language javaintroduction to object oriented programming language java
introduction to object oriented programming language java
RitikGarg39
 
Computer programming 2 Lesson 15
Computer programming 2  Lesson 15Computer programming 2  Lesson 15
Computer programming 2 Lesson 15
MLG College of Learning, Inc
 
Polymorphism in C# Function overloading in C#
Polymorphism in C# Function overloading in C#Polymorphism in C# Function overloading in C#
Polymorphism in C# Function overloading in C#
Abid Kohistani
 
Diifeerences In C#
Diifeerences In C#Diifeerences In C#
Diifeerences In C#
rohit_gupta_mrt
 
Inheritance Slides
Inheritance SlidesInheritance Slides
Inheritance Slides
Ahsan Raja
 
Hemajava
HemajavaHemajava
Hemajava
SangeethaSasi1
 
‫Chapter3 inheritance
‫Chapter3 inheritance‫Chapter3 inheritance
‫Chapter3 inheritance
Mahmoud Alfarra
 
OOPs & Inheritance Notes
OOPs & Inheritance NotesOOPs & Inheritance Notes
OOPs & Inheritance Notes
Shalabh Chaudhary
 
Adv kvr -satya
Adv  kvr -satyaAdv  kvr -satya
Adv kvr -satya
Jyothsna Sree
 
Advance java kvr -satya
Advance java  kvr -satyaAdvance java  kvr -satya
Advance java kvr -satya
Satya Johnny
 
Core java oop
Core java oopCore java oop
Core java oop
Parth Shah
 
Chapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIChapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part II
Eduardo Bergavera
 
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sirAdvanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
AVINASH KUMAR
 
Object Oriented Programming Inheritance with case study
Object Oriented Programming Inheritance with case studyObject Oriented Programming Inheritance with case study
Object Oriented Programming Inheritance with case study
MsPariyalNituLaxman
 
FINAL_DAY8_VISIBILITY_LABELS_Roles and.pptx
FINAL_DAY8_VISIBILITY_LABELS_Roles and.pptxFINAL_DAY8_VISIBILITY_LABELS_Roles and.pptx
FINAL_DAY8_VISIBILITY_LABELS_Roles and.pptx
VGaneshKarthikeyan
 
Inheritance & interface ppt Inheritance
Inheritance & interface ppt  InheritanceInheritance & interface ppt  Inheritance
Inheritance & interface ppt Inheritance
narikamalliy
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
backdoor
 
UNIT-2.pptx CS3391 Inheritance , types, packages and Interfaces
UNIT-2.pptx CS3391 Inheritance , types, packages and InterfacesUNIT-2.pptx CS3391 Inheritance , types, packages and Interfaces
UNIT-2.pptx CS3391 Inheritance , types, packages and Interfaces
SakkaravarthiS1
 
702641313-CS3391-OBJORIENTEDPS-Unit-2.pptx
702641313-CS3391-OBJORIENTEDPS-Unit-2.pptx702641313-CS3391-OBJORIENTEDPS-Unit-2.pptx
702641313-CS3391-OBJORIENTEDPS-Unit-2.pptx
SAJITHABANUS
 
introduction to object oriented programming language java
introduction to object oriented programming language javaintroduction to object oriented programming language java
introduction to object oriented programming language java
RitikGarg39
 
Polymorphism in C# Function overloading in C#
Polymorphism in C# Function overloading in C#Polymorphism in C# Function overloading in C#
Polymorphism in C# Function overloading in C#
Abid Kohistani
 
Inheritance Slides
Inheritance SlidesInheritance Slides
Inheritance Slides
Ahsan Raja
 
Advance java kvr -satya
Advance java  kvr -satyaAdvance java  kvr -satya
Advance java kvr -satya
Satya Johnny
 
Chapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIChapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part II
Eduardo Bergavera
 
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sirAdvanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
AVINASH KUMAR
 
Ad

More from Mavoori Soshmitha (6)

Ppt on java basics1
Ppt on java basics1Ppt on java basics1
Ppt on java basics1
Mavoori Soshmitha
 
Packages,interfaces and exceptions
Packages,interfaces and exceptionsPackages,interfaces and exceptions
Packages,interfaces and exceptions
Mavoori Soshmitha
 
Multi threading
Multi threadingMulti threading
Multi threading
Mavoori Soshmitha
 
main memory
main memorymain memory
main memory
Mavoori Soshmitha
 
Virtual memory
Virtual memoryVirtual memory
Virtual memory
Mavoori Soshmitha
 
Ppt on java basics
Ppt on java basicsPpt on java basics
Ppt on java basics
Mavoori Soshmitha
 

Recently uploaded (20)

Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven InsightsAndrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
Quantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur MorganQuantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur Morgan
Arthur Morgan
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptxIncreasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Anoop Ashok
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven InsightsAndrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
Quantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur MorganQuantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur Morgan
Arthur Morgan
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptxIncreasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Anoop Ashok
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 

Inheritance

  • 1. A closure look at methods and classes Usingcommandlinearguments Understandingstatic Recursion Methodsandclasses abstract continue for new switch assert default package synchronized boolean do if private this break double implements protected throw byte else import public throws case enum instanceof return transient catch extends int short try char final interface static void class finally long strictfp volatile const float native super java keywords
  • 2. A closure look at methods and classes Usingcommandlinearguments Understandingstatic Recursion Methodsandclasses overloading methods and its purpose If a class have multiple methods by same name but different parameters it is known as method overloading. If we have to perform only one operation , having same name of the methods increases the readability of the program. Different ways to overload the method: 1. By changing number of arguments 2. By changing data type
  • 3. A closure look at methods and classes Usingcommandlinearguments Understandingstatic Recursion Method overloading with an example: // Demonstrate method overloading. class OverloadDemo { void test() { System.out.println("No parameters"); } // Overload test for one integer parameter. void test(int a) { System.out.println("a: " + a); } // Overload test for two integer parameters. void test(int a, int b) { System.out.println("a and b: " + a + " " + b); } // overload test for a double parameter double test(double a) { System.out.println("double a: " + a); return a*a; } } class Overload { public static void main(String args[]) { OverloadDemo ob = new OverloadDemo(); double result; // call all versions of test() ob.test(); ob.test(10); ob.test(10, 20); result = ob.test(123.25); System.out.println("Result of ob.test(123.25): " + result); } } This program generates the following output: No parameters a: 10 a and b: 10 20 double a: 123.25 Result of ob.test(123.25): 15190.5625 Methodoverloading
  • 4. A closure look at methods and classes Usingcommandlinearguments Understandingstatic Recursion Why method overloading is not possible by changing the return type? Can we overload main() method? Method overloading is not possible by changing the return type of method because there may occur ambiguity. Yes, we can have any number of main methods in a class by method overloading Methodoverloading
  • 5. A closure look at methods and classes Usingcommandlinearguments Understandingstatic Recursion What is constructor overloading ? Just like in case of method overloading you have multiple methods with same name but different signature , in Constructor overloading you have multiple constructor with different signature with only difference that Constructor doesn't have return type in Java. Those constructor will be called as overloaded constructor. Overloading is also another form of polymorphism in Java which allows to have multiple constructor with different name in one Class in java. Constructoroverloading
  • 6. A closure look at methods and classes Usingcommandlinearguments Understandingstatic Recursion Why do you overload Constructor? Allows flexibility while create array list object. It may be possible that you don't know size of array list during creation than you can simply use default no argument constructor but if you know size then its best to use overloaded Constructor which takes capacity. Since Array List can also be created from another Collection, may be from another List than having another overloaded constructor makes lot of sense. By using overloaded constructor you can convert your Array List into Set or any other collection. Constructoroverloading
  • 7. A closure look at methods and classes Usingcommandlinearguments Understandingstatic Recursion Constructor overload with an example /* Here, Box defines three constructors to initialize the dimensions of a box various ways. */ class Box { double width; double height; double depth; // constructor used when all dimensions specified Box(double w, double h, double d) { width = w; height = h; depth = d; } // constructor used when no dimensions specified Box() { width = -1; // use -1 to indicate height = -1; // an uninitialized depth = -1; // box } // constructor used when cube is created Box(double len) { width = height = depth = len; } // compute and return volume double volume() { return width * height * depth; } } class OverloadCons { public static void main(String args[]) { // create boxes using the various constructors Box mybox1 = new Box(10, 20, 15); Box mybox2 = new Box(); Box mycube = new Box(7); double vol; // get volume of first box vol = mybox1.volume(); System.out.println("Volume of mybox1 is " + vol); // get volume of second box vol = mybox2.volume(); System.out.println is " + vol); // get volume of cube vol = mycube.volume(); System.out.println("Volume of mycube is " + vol); } } The output produced by this program is shown here: Volume of mybox1 is 3000.0 Volume of mybox2 is -1.0 Volume of mycube is 343.0 Constructoroverloading
  • 8. A closure look at methods and classes Usingcommandlinearguments Understandingstatic Methodoverloading Recursion Recursion is the process of defining something in terms of itself. As it relates to Java programming, recursion is the attribute that allows a method to call itself. A method that calls itself is said to be recursive. The classic example of recursion is the computation of the factorial of a number. The factorial of a number N is the product of all the whole numbers between 1 and N. For example, 3 factorial is 1 × 2 × 3, or 6. Here is how a factorial can be computed by use of a recursive method: Recursion
  • 9. A closure look at methods and classes Usingcommandlinearguments Understandingstatic Methodoverloading Recursion with example // A simple example of recursion. class Factorial { // this is a recursive method int fact(int n) { int result; if(n==1) return 1; result = fact(n-1) * n; return result; } } class Recursion { public static void main(String args[]) { Factorial f = new Factorial(); System.out.println("Factorial of 3 is " + f.fact(3)); System.out.println("Factorial of 4 is " + f.fact(4)); System.out.println("Factorial of 5 is " + f.fact(5)); } } The output from this program is shown here: Factorial of 3 is 6 Factorial of 4 is 24 Factorial of 5 is 120 Recursion
  • 10. A closure look at methods and classes Usingcommandlinearguments Understandingstatic Methodoverloading Access ControlAccessControl public private protected < unspecified > Class allowed Not allowed Not allowed not allowed Constructor allowed allowed allowed allowed Variable allowed allowed allowed allowed method allowed allowed allowed allowed Visible ?? class Sub class package Outside Package private Yes No No No protected Yes Yes Yes No public Yes Yes Yes Yes < unspecified > Yes Yes No No
  • 11. A closure look at methods and classes Usingcommandlinearguments Recursion Methodoverloading Understanding static and final Understandingstatic Why do we use static? There will be times when you will want to define a class member that will be used independently of any object of that class. Instance variables declared as static are, essentially, global variables. When objects of its class are declared, no copy of a static variable is made. Instead, all instances of the class share the same static variable. Methods declared as static have several restrictions: • They can only call other static methods. • They must only access static data. • They cannot refer to this or super in any way.
  • 12. A closure look at methods and classes Usingcommandlinearguments Recursion Methodoverloading Understanding static Understandingstatic // Demonstrate static variables, methods, and blocks. class UseStatic { static int a = 3; static int b; static void meth(int x) { System.out.println("x = " + x); System.out.println("a = " + a); System.out.println("b = " + b); } static { System.out.println("Static block initialized."); b = a * 4; } public static void main(String args[]) { meth(42); } }
  • 13. A closure look at methods and classes Usingcommandlinearguments Recursion Methodoverloading Understanding static Understandingstatic Why main method is declared as static? Java program's main method has to be declared static because keyword static allows main to be called without creating an object of the class in which the main method is defined. If we omit static keyword before main Java program will successfully compile but it won't execute.
  • 14. Inheritance Usingabstractclassandfinalwith inheritance MethodOverriding Usingsuper InheritanceBasics what is inheritance ? Object-oriented programming allows classes to inherit commonly used state and behavior from other classes The mechanism of deriving a new class from existing old one is called inheritance. The old class is known as super class or base class or parent class The new class is known as child class or subclass or derived class. To inherit properties of base class to sub class we use extends keyword in the inherited class i.e. in sub class.
  • 16. Inheritance Usingabstractclassandfinalwith inheritance MethodOverriding Usingsuper InheritanceBasics Inheritance with an example. syntax: class subclassname extends superclassname { variables declaration; methods declaration; } class Employee{ float salary=40000; } class Programmer extends Employee{ int bonus=10000; public static void main(String args[]){ Programmer p=new Programmer(); System.out.println("Programmer salary is:"+p.salary); System.out.println("Bonus of Programmer is:"+p.bonus); } } }
  • 17. Inheritance Usingabstractclassandfinalwith inheritance MethodOverriding Usingsuper InheritanceBasics Forms of inheritance: Inheritance allows subclass to inherit all the variables and methods of their parent classes. Inheritance may take different forms: 1. Single inheritance(only one super class). 2. Multiple inheritance(several super classes). 3. Hierarchical inheritance(one super class many sub classes). 4. Multilevel inheritance(derived from derived class).
  • 18. Inheritance Usingabstractclassandfinalwith inheritance MethodOverriding Usingsuper InheritanceBasics Single inheritance A B When a class extends another one class only then we call it a single inheritance. Class A { public void methodA() { System.out.println("Base class method"); } } Class B extends A { public void methodB() { System.out.println("Child class method"); } public static void main(String args[]) { B obj = new B(); obj.methodA(); //calling super class method obj.methodB(); //calling local method } }
  • 19. Inheritance Usingabstractclassandfinalwith inheritance MethodOverriding Usingsuper InheritanceBasics In such kind of inheritance one class is inherited by many sub classes. In below example class B,C and D inherits the same class A. A is parent class (or base class) of B,C & D. A B C D Hierarchical inheritance Account Current Savings Fixed-deposit
  • 20. Inheritance Usingabstractclassandfinalwith inheritance MethodOverriding Usingsuper InheritanceBasics A B C Grand father Son Father Multilevel inheritance Class a member Class c member Class b member Class a member class A {………… ………….} Class B extends A //first { ………… level ………..} class C extends A// second level {…………. ………….}
  • 21. Inheritance Usingabstractclassandfinalwith inheritance MethodOverriding Usingsuper InheritanceBasics Multiple inheritance A B C Multiple Inheritance” refers to the concept of one class extending (Or inherits) more than one base class. The inheritance we learnt earlier had the concept of one base class or parent. The problem with “multiple inheritance” is that the derived class will have to manage the dependency on two base classes. Note 1: Multiple Inheritance is very rarely used in software projects. Using Multiple inheritance often leads to problems in the hierarchy. This results in unwanted complexity when further extending the class.
  • 22. Inheritance Usingabstractclassandfinalwith inheritance InheritanceBasics Usingsuper Methodoverriding Overriding methods and its purpose Overridden methods allow Java to support run-time polymorphism . Polymorphism is essential to object-oriented programming for one reason: it allows a general class to specify methods that will be common to all of its derivatives, while allowing subclasses to define the specific implementation of some or all of those methods Overridden methods are another way that Java implements the “one interface, multiple methods” aspect of polymorphism.
  • 23. Inheritance Usingabstractclassandfinalwith inheritance InheritanceBasics Usingsuper Finalvariables,methodsandclasses Final variables , methods and classes All methods and variables can be Overridden by default in subclass. If we wish to prevent the subclass from overriding the members of the superclass. We can declare tem as final using the keyword final as a modifier. Ex : final int SIZE=100; final void showstatus(){………….} Making a method final ansures that the functionality defined in this method will never be altered in anyway.
  • 24. Inheritance Usingabstractclassandfinalwith inheritance InheritanceBasics Usingsuper Finalvariables,methodsandclasses Final variables , methods and classes A class that cannot be subclassed is called a final class Ex : final class Aclass{…….} final class Bclass extends Cclass{………….} Any attempt to inherit these classes will cause an error and the compiler will not allow it. Declaring a class final prevents any unwanted extension to the class. It also allows the complier to perform some optimization when a method of a final class is invoked.
  • 25. Inheritance Usingabstractclassandfinalwith inheritance InheritanceBasics Usingsuper Finalizermethod Finalize() method 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 window system fonts. The garbage collector cannot free these resources. In order to free these resources we must use finalize method.tis is similar to destructor in C++. The finalizer method is simply finalize() and can be added to any class . Java calls that method whenever it is about to reclaim te space for that object . The finalize method should explicitly define the task to be performed.
  • 26. Inheritance Usingabstractclassandfinalwith inheritance InheritanceBasics Usingsuper Finalizermethod Using super super has two general forms. The first calls the superclass constructor. The second is used to access a member of the superclass that has been hidden by a member of a subclass
  • 27. Inheritance Usingabstractclassandfinalwith inheritance InheritanceBasics Usingsuper Finalizermethod A first Use for super class a { a(){System.out.println("A");} } class b extends a { b() { super(); System.out.println("B");} } class c extends b { c(){System.out.println("c");} } class last { public static void main(String args[]) { c obj = new c(); }
  • 28. Inheritance Usingabstractclassandfinalwith inheritance InheritanceBasics Usingsuper Finalizermethod A Second Use for super The second form of super acts somewhat like this, except that it always refers to the superclass of the subclass in which it is used. This usage has the following general form: super.member Here, member can be either a method or an instance variable. Most applicable to situations in which member names of a subclass hide members by the same name in the superclass. Consider this simple class hierarchy:
  • 29. Inheritance Usingabstractclassandfinalwith inheritance InheritanceBasics Usingsuper Finalizermethod A Second Use for super // Using super to overcome name hiding. class A { int i; } // Create a subclass by extending class A. class B extends A { int i; // this i hides the i in A B(int a, int b) { super.i = a; // i in A i = b; // i in B } void show() { System.out.println("i in superclass: " + super.i); System.out.println("i in subclass: " + i); } } class UseSuper { public static void main(String args[]) { B subOb = new B(1, 2); subOb.show(); } } This program displays the following: i in superclass: 1 i in subclass: 2
  • 30. Inheritance Usingabstractclass InheritanceBasics Usingsuper Abstractmethodsandclasses Abstract methods and classes A final class can never be subclassed. Java allows us to do somethin exactly opposite to this i.e. we can indicate that te method must always be redefined in a subclass , thus making overriding compulsory. This is done by using the modifier keyword abstract. Ex : abstract class shape { ………….. ………….. abstract void draw(); …………… …………… }  A class with more than one abstract methods should be declared as abstract class
  • 31. Inheritance Usingabstractclass InheritanceBasics Usingsuper Methodoverriding Abstract methods and classes While using abstract classes , following conditions must satisfy 1. We cannot use abstract classes to instantiate objects directly. Ex : Shape s = new Shape() is illegal because is an abstract class. 2. The abstract methods of an abstract class must be defined in its subclass. 3. We cannot declare abstract constructors or abstract static methods.
  • 32. Inheritance Commandlinearguments InheritanceBasics Usingsuper Methodoverriding Command line arguments Java has included a feature that simplifies the creation of methods that need to take a variable number of arguments. This feature is called varargs and it is short for variable- length arguments. A method that takes a variable number of arguments is called a variable-arity method, or simply a varargs method. Situations that require that a variable number of arguments be passed to a method are not unusual. For example, a method that opens an Internet connection might take a user name, password, filename, protocol, and so on, but supply defaults if some of this information is not provided. In this situation, it would be convenient to pass only the arguments to which the defaults did not apply
  • 33. Inheritance Commandlinearguments InheritanceBasics Usingsuper Methodoverriding Command line arguments // Use an array to pass a variable number of // arguments to a method. This is the old-style // approach to variable-length arguments. class PassArray { static void vaTest(int v[]) { System.out.print("Number of args: " + v.length + " Contents: "); for(int x : v) System.out.print(x + " "); System.out.println(); } public static void main(String args[]) { // Notice how an array must be created to // hold the arguments. int n1[] = { 10 }; int n2[] = { 1, 2, 3 }; int n3[] = { }; vaTest(n1); // 1 arg vaTest(n2); // 3 args vaTest(n3); // no args } } The output from the program is shown here: Number of args: 1 Contents: 10 Number of args: 3 Contents: 1 2 3 Number of args: 0 Contents: