SlideShare une entreprise Scribd logo
1  sur  35
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

Contenu connexe

Tendances

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
 
Java class 3
Java class 3Java class 3
Java class 3
Edureka!
 

Tendances (20)

Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in java
 
Packages and inbuilt classes of java
Packages and inbuilt classes of javaPackages and inbuilt classes of java
Packages and inbuilt classes of java
 
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
 
java Method Overloading
java Method Overloadingjava Method Overloading
java Method Overloading
 
Java unit2
Java unit2Java unit2
Java unit2
 
Java
JavaJava
Java
 
advanced java ppt
advanced java pptadvanced java ppt
advanced java ppt
 
Java
JavaJava
Java
 
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
 
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
 
Lecture - 5 Control Statement
Lecture - 5 Control StatementLecture - 5 Control Statement
Lecture - 5 Control Statement
 
Java basic tutorial
Java basic tutorialJava basic tutorial
Java basic tutorial
 
Ppt on this and super keyword
Ppt on this and super keywordPpt on this and super keyword
Ppt on this and super keyword
 
Java class 3
Java class 3Java class 3
Java class 3
 
Method Overloading In Java
Method Overloading In JavaMethod Overloading In Java
Method Overloading In Java
 
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
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Method overloading
Method overloadingMethod overloading
Method overloading
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Java Reflection
Java ReflectionJava Reflection
Java Reflection
 

En vedette (7)

Handling inputs via scanner class
Handling inputs via scanner classHandling inputs via scanner class
Handling inputs via scanner class
 
Java Serialization
Java SerializationJava Serialization
Java Serialization
 
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
 
Java Serialization
Java SerializationJava Serialization
Java Serialization
 
Java stream
Java streamJava stream
Java stream
 
IO In Java
IO In JavaIO In Java
IO In Java
 
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
 

Similaire à Inheritance

Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
backdoor
 
Advance java kvr -satya
Advance java  kvr -satyaAdvance java  kvr -satya
Advance java kvr -satya
Satya Johnny
 

Similaire à Inheritance (20)

Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
 
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
 
java tutorial 3
 java tutorial 3 java tutorial 3
java tutorial 3
 
Computer programming 2 Lesson 15
Computer programming 2  Lesson 15Computer programming 2  Lesson 15
Computer programming 2 Lesson 15
 
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#
 
Diifeerences In C#
Diifeerences In C#Diifeerences In C#
Diifeerences In C#
 
Inheritance Slides
Inheritance SlidesInheritance Slides
Inheritance Slides
 
Hemajava
HemajavaHemajava
Hemajava
 
‫Chapter3 inheritance
‫Chapter3 inheritance‫Chapter3 inheritance
‫Chapter3 inheritance
 
OOPs & Inheritance Notes
OOPs & Inheritance NotesOOPs & Inheritance Notes
OOPs & Inheritance Notes
 
Adv kvr -satya
Adv  kvr -satyaAdv  kvr -satya
Adv kvr -satya
 
Advance java kvr -satya
Advance java  kvr -satyaAdvance java  kvr -satya
Advance java kvr -satya
 
Core java oop
Core java oopCore java oop
Core java oop
 
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
 
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
 
Class notes(week 6) on inheritance and multiple inheritance
Class notes(week 6) on inheritance and multiple inheritanceClass notes(week 6) on inheritance and multiple inheritance
Class notes(week 6) on inheritance and multiple inheritance
 
Presentation.pptx
Presentation.pptxPresentation.pptx
Presentation.pptx
 
CJP Unit-1 contd.pptx
CJP Unit-1 contd.pptxCJP Unit-1 contd.pptx
CJP Unit-1 contd.pptx
 
JAVA CONCEPTS AND PRACTICES
JAVA CONCEPTS AND PRACTICESJAVA CONCEPTS AND PRACTICES
JAVA CONCEPTS AND PRACTICES
 
Jist of Java
Jist of JavaJist of Java
Jist of Java
 

Plus de Mavoori Soshmitha (6)

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

Dernier

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Dernier (20)

Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 

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: