inheritance
TRANSCRIPT
A closure look at methods and classes
Usi
ng c
om
man
d lin
e a
rgu
men
ts
Und
ers
tand
ing
sta
tic
Recu
rsio
n
Meth
od
s and
cla
sses
abstractcontinuefornew switchassertdefaultpackagesynchronizedbooleandoifprivatethisbreakdouble
implementsprotectedthrowbyteelseimportpublicthrowscaseenuminstanceofreturntransientcatchextendsint
shorttrycharfinalinterfacestaticvoidclassfinallylongstrictfpvolatileconstfloatnativesuperwhile.
java keywords
A closure look at methods and classes
Usi
ng c
om
man
d lin
e a
rgu
men
ts
Und
ers
tand
ing
sta
tic
Recu
rsio
n
Meth
od
s and
cla
ssesoverloading
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 arguments2. By changing data type
A closure look at methods and classes
Usi
ng c
om
man
d lin
e a
rgu
men
ts
Und
ers
tand
ing
sta
tic
Recu
rsio
nMethod 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
Meth
od
overl
oad
ing
A closure look at methods and classes
Usi
ng c
om
man
d lin
e a
rgu
men
ts
Und
ers
tand
ing
sta
tic
Recu
rsio
nWhy 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
Meth
od
overl
oad
ing
A closure look at methods and classes
Usi
ng c
om
man
d lin
e a
rgu
men
ts
Und
ers
tand
ing
sta
tic
Recu
rsio
nWhat 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.
Con
stru
ctor
overl
oadin
g
A closure look at methods and classes
Usi
ng c
om
man
d lin
e a
rgu
men
ts
Und
ers
tand
ing
sta
tic
Recu
rsio
nWhy 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.
Con
stru
ctor
overl
oadin
g
A closure look at methods and classes
Usi
ng c
om
man
d lin
e a
rgu
men
ts
Und
ers
tand
ing
sta
tic
Recu
rsio
n
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
Con
stru
ctor
overl
oadin
g
A closure look at methods and classes
Usi
ng c
om
man
d lin
e a
rgu
men
ts
Und
ers
tand
ing
sta
tic
M
eth
od
overl
oad
ing
RecursionRecursion 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:
Recu
rsio
n
A closure look at methods and classes
Usi
ng c
om
man
d lin
e
arg
um
en
ts
Und
ers
tand
ing
sta
tic
M
eth
od
overl
oad
ing
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
Recu
rsio
n
A closure look at methods and classes
Usi
ng c
om
man
d lin
e
arg
um
en
ts
Und
ers
tand
ing
sta
tic
M
eth
od
overl
oad
ing Access Control
Acc
ess
Con
trol
publicprivate protected
< unspecified >
Class allowed Not allowed Not allowed not allowed
Constructor allowed allowed allowed allowed
Variable allowed allowed allowed allowed
method allowedallowed allowed allowed
Visible ?? class Sub class packageOutside 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
Usi
ng c
om
man
d lin
e
arg
um
en
ts
Recu
rsio
n
Meth
od
overl
oad
ing Understanding static and final
Und
ers
tand
ing
sta
tic
Why do we use static?
There will be times when you will want to define a class member that will be usedindependently of any object of that class.
Instance variables declared as static are, essentially, global variables. When objects ofits 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
Usi
ng c
om
man
d lin
e
arg
um
en
ts
Recu
rsio
n
Meth
od
overl
oad
ing Understanding static
Und
ers
tand
ing
sta
tic
// 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
Usi
ng c
om
man
d lin
e
arg
um
en
ts
Recu
rsio
n
Meth
od
overl
oad
ing Understanding static
Und
ers
tand
ing
sta
tic
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
Usi
ng a
bst
ract
cla
ss a
nd
fin
al
wit
h inh
eri
tance
Meth
od
Overr
idin
g
Usi
ng s
up
er
Inheri
tance
Basi
cs 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
Usi
ng a
bst
ract
cla
ss a
nd
fin
al
wit
h inh
eri
tance
Meth
od
Overr
idin
g
Usi
ng s
up
er
Inheri
tance
Basi
cs
Why use inheritance ?
For method overriding.For code reusability.
Inheritance
Usi
ng a
bst
ract
cla
ss a
nd
fin
al
wit
h inh
eri
tance
Meth
od
Overr
idin
g
Usi
ng s
up
er
Inheri
tance
Basi
cs 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
Usi
ng a
bst
ract
cla
ss a
nd
fin
al
wit
h inh
eri
tance
Meth
od
Overr
idin
g
Usi
ng s
up
er
Inheri
tance
Basi
cs 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
Usi
ng a
bst
ract
cla
ss a
nd
fin
al
wit
h inh
eri
tance
Meth
od
Overr
idin
g
Usi
ng s
up
er
Inheri
tance
Basi
cs
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
Usi
ng a
bst
ract
cla
ss a
nd
fin
al
wit
h inh
eri
tance
Meth
od
Overr
idin
g
Usi
ng s
up
er
Inheri
tance
Basi
cs
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
Usi
ng a
bst
ract
cla
ss a
nd
fin
al
wit
h inh
eri
tance
Meth
od
Overr
idin
g
Usi
ng s
up
er
Inheri
tance
Basi
cs
A
B
C
Grandfather
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
Usi
ng a
bst
ract
cla
ss a
nd
fin
al
wit
h inh
eri
tance
Meth
od
Overr
idin
g
Usi
ng s
up
er
Inheri
tance
Basi
cs 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
Usi
ng a
bst
ract
cla
ss a
nd
fin
al
wit
h inh
eri
tance
Inheri
tance
Basi
cs
Usi
ng s
up
er
Meth
od
overr
idin
g 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
Usi
ng a
bst
ract
cla
ss a
nd
fin
al
wit
h inh
eri
tance
Inheri
tance
Basi
cs
Usi
ng s
up
er
Fin
al vari
ab
les
, m
eth
ods
an
d
class
es 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
Usi
ng a
bst
ract
cla
ss a
nd
fin
al
wit
h inh
eri
tance
Inheri
tance
Basi
cs
Usi
ng s
up
er
Fin
al vari
ab
les
, m
eth
ods
an
d
class
es 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
Usi
ng a
bst
ract
cla
ss a
nd
fin
al
wit
h inh
eri
tance
Inheri
tance
Basi
cs
Usi
ng s
up
er
Fin
aliz
er
meth
od
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
Usi
ng a
bst
ract
cla
ss a
nd
fin
al
wit
h inh
eri
tance
Inheri
tance
Basi
cs
Usi
ng s
up
er
Fin
aliz
er
meth
od
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
Usi
ng a
bst
ract
cla
ss a
nd
fin
al
wit
h inh
eri
tance
Inheri
tance
Basi
cs
Usi
ng s
up
er
Fin
aliz
er
meth
od
A first Use for superclass 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
Usi
ng a
bst
ract
cla
ss a
nd
fin
al
wit
h inh
eri
tance
Inheri
tance
Basi
cs
Usi
ng s
up
er
Fin
aliz
er
meth
od
A Second Use for super
The second form of super acts somewhat like this, except that it always refers to the superclassof the subclass in which it is used. This usage has the following general form:super.memberHere, 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 classhierarchy:
Inheritance
Usi
ng a
bst
ract
cla
ss a
nd
fin
al
wit
h inh
eri
tance
Inheri
tance
Basi
cs
Usi
ng s
up
er
Fin
aliz
er
meth
od
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 AB(int a, int b) {super.i = a; // i in Ai = 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: 1i in subclass: 2
Inheritance
Usi
ng a
bst
ract
cla
ss
Inheri
tance
Basi
cs
Usi
ng s
up
er
Ab
stra
ct m
eth
ods
an
d c
lass
es 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
Usi
ng a
bst
ract
cla
ss
Inheri
tance
Basi
cs
Usi
ng s
up
er
Meth
od
overr
idin
g
Abstract methods and classes
While using abstract classes , following conditions must satisfy1. 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
Com
mand
lin
e a
rgum
ents
Inheri
tance
Basi
cs
Usi
ng s
up
er
Meth
od
overr
idin
gCommand 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
Com
mand
lin
e a
rgum
ents
Inheri
tance
Basi
cs
Usi
ng s
up
er
Meth
od
overr
idin
g 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 argvaTest(n2); // 3 argsvaTest(n3); // no args}}The output from the program is shown here:Number of args: 1 Contents: 10Number of args: 3 Contents: 1 2 3Number of args: 0 Contents:
Thank
you
B
C
A
c1
a1
b1
c2
a2
b2