Академический Документы
Профессиональный Документы
Культура Документы
Objectives
Slide 1 of 19
Ver. 1.0
Programming in Java
What Is Polymorphism?
Polymorphism:
Means “many forms”
Ability to refer to an object using either its actual form or a
parent form
The following code snippet shows how polymorphism is
used by the emp object: Here,
assignment
Parent class Child class
is legal as a
Employee emp = new Manager(); Manager is
also an
Employee.
Slide 2 of 19
Ver. 1.0
Programming in Java
Overloading Methods
Slide 3 of 19
Ver. 1.0
Programming in Java
Methods Using Variable Arguments
varargs
Slide 4 of 19
Ver. 1.0
Programming in Java
Activity: StatisticsExample
Slide 5 of 19
Ver. 1.0
Programming in Java
Single Inheritance
Slide 6 of 19
Ver. 1.0
Programming in Java
Using Access Control
Slide 7 of 19
Ver. 1.0
Programming in Java
Protected Access Control: Example
Slide 8 of 19
Ver. 1.0
Programming in Java
Protected Access Control: Example (Contd.)
import demo.Foo;
public class Bar extends Foo {
private int sum = 10;
public void reportSum ()
{
sum += result; Compiler
sum += other; error
}
} The result variable is accessible as it is
declared with protected access in the
superclass, but the other variable is not
accessible as it is declared with default access
in the superclass.
Slide 9 of 19
Ver. 1.0
Programming in Java
Access Control: Good Practice
Slide 10 of 19
Ver. 1.0
Programming in Java
Activity: javaAccessExample
Slide 11 of 19
Ver. 1.0
Programming in Java
Field Shadowing: Example
Field shadowing:
Occurs when a non-private field of the superclass is also
declared in the subclass and the field is hidden in the subclass
Example:
package demo;
public class Foo2
{//superclass
protected int result = 20;
}
public class Bar2 extends Foo2 {
private int sum = 10; The result
private int result = 30; field shadows the
superclass field.
public void reportSum() {
sum += result;
}
}
Slide 12 of 19
Ver. 1.0
Programming in Java
Overriding Methods
Overridden method:
Non-private method of the superclass that is also defined in
the subclass
Rules to override methods:
At least two classes must exists, a superclass and a subclass
Method signature of the superclass must be same in the
subclass
The following embedded Word document shows how to
implement the concept of method overriding.
Method
overriding
The super keyword is used to invoke a parent method from
a subclass.
Slide 13 of 19
Ver. 1.0
Programming in Java
Accessibility of Overridden Methods
Overriding
methods
Slide 14 of 19
Ver. 1.0
Programming in Java
Invoking an Overridden Method
Invoke overriden
method
Slide 15 of 19
Ver. 1.0
Programming in Java
Quiz
Slide 16 of 19
Ver. 1.0
Programming in Java
Quiz (Contd.)
Solution:
public void dostuff(float i);
public void dostuff(double i);
Slide 17 of 19
Ver. 1.0
Programming in Java
Quiz (Contd.)
Solution:
single inheritance
Slide 18 of 19
Ver. 1.0
Programming in Java
Summary
Slide 19 of 19
Ver. 1.0