[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.
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.
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: