SlideShare a Scribd company logo
 OOP Principles
 Encapsulation and Data abstraction.
 Inheritance
 Super keyword
 Abstract Classes
 Interface
 Polymorphism
 Method overridding
 Method overloading
 Packages
 Passing and returning objects
 Wrapper Classes (Reading
Assignment)
 All object-oriented programming languages
provide mechanisms that help you implement the
object-oriented model.
 The three fundamental object oriented
programming principles are:
 Encapsulation (data hiding) and Data
abstraction
 Inheritance
 Polymorphism
 Main purpose of these principles is to manage
software system complexity by improving software
quality factors.
Encapsulation refers to
the combining of fields and
methods together in a class
such that the methods
operate on the data, as
opposed to users of the
class accessing the fields
directly.
 It is a the technique
which involves making
the fields in a class private
and providing access to
the fields via public
..
Class
 If a field is declared private, it cannot be accessed
by anyone outside the class, thereby hiding the
fields within the class.
 For this reason, encapsulation is also referred to as
data hiding.
 Encapsulation can be described as a protective
barrier that prevents the code and data being
randomly accessed by other code defined outside
the class.
 Access to the data and code is tightly controlled by
an interface.
 The main benefit of encapsulation is the ability to
modify our implemented code without breaking the
public class EncapTest{
private String name;
private String idNum;
private int age;
public int getAge(){
return age;
}
public String
getName(){
return name;
}
public String getIdNum(){
return idNum;
}
public void setAge( int
newAge){
age = newAge;
}
public void
setName(String newName){
name = newName;
}
public void setIdNum(
String newId){
idNum = newId;
}
}
 The public methods are the access points to this class’s
fields from the outside java world.
 Normally these methods are referred as getters and
setters. Therefore any class that wants to access the
variables should access them through these getters and
setters.
 The variables of the EncapTest class can be accessed
as below:
public class RunEncap{
public static void main(String args[]){
EncapTest encap = new EncapTest();
encap.setName("James");
encap.setAge(20);
encap.setIdNum("12343ms");
System.out.print("Name : " + encap.getName()+ " Age : "+
encap.getAge());
}
}
Out Put:
Name : James Age : 20
 Classes normally hide
the details of their
implementation from
their clients.
 This is called information
hiding.
 The client cares about
what functionality a
class offers, not about
how that functionality is
implemented.
 This concept is referred
to as data abstraction.
MOM
DAD
Inherits
Inheritance Hierarchy for Shapes
 In object-oriented programming (OOP)
 Inheritance is the capability of a class to use the
properties and methods of another class (Super
Classes) while adding its own functionality.
 I.e. Inheritance is a way to form new classes using
classes that have already been defined.
 Inheritance is employed to help reuse existing code
with little or no modification.
 The new classes, known as derived classes, inherit
attributes and behavior of the pre-existing classes,
which are referred to as base classes (or ancestor
classes).
 The inheritance relationship of sub- and
superclasses gives rise to a hierarchy.
 With the use of inheritance the information is made
manageable in a hierarchical order.
 Elements to be inherited form parent class are
protected and public Members.
 Applications of inheritance
 Specialization
 the new class or object has data or behavior
aspects that are not part of the inherited class.
 Overriding
 permit a class or object to replace the
implementation of an aspect—typically a
behavior—that it has inherited
 Code re-use
 re-use of code which already existed in another
class.
 When we talk about inheritance in java the most
commonly used key words would be extends and
implements.
 These words would determine whether one object
IS-A type of another.
 With use of the extends keyword the subclasses
will be able to inherit all the properties of the
superclass except for the private properties of the
superclass.
 IS-A defines relationship between a superclass and
its subclasses.
 This means that an object of a subclass can be
public class Student {
protected String name;
public Student() {
name = “”;
}
public Student(String s) {
name = s;
}
public String getName() {
return name;
}
} Note: Object is the super class of all Java Classes
 Now based on the above example, In Object Oriented
terms following are true:
 Animal is the superclass of Mammal and Reptile classes.
 Mammal and Reptile are subclasses of Animal class.
 Dog is the subclass of both Mammal and Animal classes.
 A very important fact to remember is that Java only
supports only single inheritance. This means that a
class cannot extend more than one class. Therefore
the following is illegal:
public class extends Animal, Mammal{…}
public class Animal{ …}
public class Mammal extends Animal{…}
public class Reptile extends Animal{…}
public class Dog extends Mammal{…}
 We can assure that Mammal is actually an Animal with
the use of the instance operator.
public class Dog extends Mammal{
public static void main(String args[]){
Animal a = new Animal();
Mammal m = new Mammal();
Dog d = new Dog();
System.out.println(m instanceof Animal);
System.out.println(d instanceof Mammal);
System.out.println(d instanceof Animal);
}
} This would produce following result:
true
true
true
 When extending a class constructor you can reuse the
immediate superclass constructor and overridden
superclass methods by using the reserved word
super.
 Note that
 You cannot override final methods, methods in final
classes, private methods or static methods.
 Example
class A{
int a, b, c;
A(int p, int q, int r){
a=p;
b=q;
c=r;
}
void Show(){
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
}
}
public class B extends A{
int d;
B(int l, int m, int n, int o){
super(l, m, n);
d=o;
}
void Show(){
super.show()
System.out.println("d = " + d);
}
public static void main(String args[]
){
B b = new B(4,3,8,7);
b.Show();
}
}
Output
a =
4
b =
3
c =
8
d =
7
 An abstract class is one that cannot be instantiated.
Abstraction refers to the ability to make a class abstract
in OOP.
 All other functionality of the class still exists, and its
fields, methods, and constructors are all accessed in
the same manner.
 Classes that can be instantiated are known as concrete
classes.
 If a class is abstract and cannot be instantiated, the
class does not have much use unless it is subclassed.
This is typically how abstract classes come about during
the design phase.
 A parent class contains the common functionality of a
collection of child classes, but the parent class itself is
too abstract to be used on its own.
public abstract class Employee{
private String name, address;
private int number;
public Employee(String name, String address, int
number){
System.out.println("Constructing an Employee");
this.name = name;
this.address = address;
this.number = number;
}
public double computePay() {
System.out.println("Inside Employee computePay");
return 0.0;
}
public void mailCheck(){
System.out.println("Within mailCheck of Salary class ");
System.out.println("Mailing a check to " + name + " " +
address); }
public String toString() {
return name + " " + address + " " + number; }
public String getName() { return name; }
public String getAddress() { return address; }
public void setAddress(String newAddress) { address =
newAddress; }
public int getNumber(){ return number; }
}
 When you would compile, using instances of Employee
class, above class then you would get following error:
public class Salary extends Employee {
private double salary; //Annual salary
public Salary(String name, String address, int number,
double salary){
super(name, address, number);
setSalary(salary);
}
public void mailCheck(){
System.out.println("Within mailCheck of Salary
class ");
System.out.println("Mailing check to " + getName()
+ " with salary " + salary);
}
public double getSalary(){ return salary; }
public void setSalary(double newSalary){
if(newSalary >= 0.0){
salary = newSalary;
}
}
public double computePay(){
System.out.println("Computing salary pay for " +
getName());
return salary/52;
}
}
 Here we cannot instantiate a new Employee, but if we
instantiate a new Salary object, the Salary object will
inherit the three fields and seven methods from Employee.
public class AbstractDemo{
public static void main(String [] args) {
Salary s = new Salary("Mohd ", "Ambehta, UP“, 3,
3600.00);
Salary e = new Salary("John ", "Boston, MA", 2,
2400.00);
System.out.println("Call mailCheck using Salary
reference --");
s.mailCheck();
System.out.println("n Call mailCheck using Employee
reference--");
e.mailCheck();
 This would produce following result:
Constructing an Employee
Constructing an Employee
Call mailCheck using Salary reference --
Within mailCheck of Salary class
Mailing check to Mohd Mohtashim with salary 3600.0
Call mailCheck using Employee reference--
Within mailCheck of Salary class
Mailing check to John Adams with salary 2400.
 If you want a class to contain a particular method but
you want the actual implementation of that method to be
determined by child classes, you can declare the
method in the parent class as abstract.
 The abstract keyword is also used to declare a method
as abstract.
 An abstract methods consist of a method signature, but
no method body - its signature is followed by a
semicolon, not curly braces as usual.
 Declaring a method as abstract has two results:
 The class must also be declared abstract. If a class
contains an abstract method, the class must be abstract as
well.
public abstract class Employee{
private String name, address;
private int number;
public abstract double computePay();
…//remainder of the class definition
}
public class Salary extends Employee{
private double salary; //Annual salary
public double computePay(){
System.out.println("Computing salary pay for " +
getName());
return salary/52;
}
…//remainder of the class defiition
}
 Interfaces are similar to abstract classes but all
methods are abstract and all data fields are static final.
 That is an interface is a collection of abstract methods and
static final variables.
 Interfaces can be inherited (i.e. you can have a sub-
interface). As with classes the extends keyword is used
for inheritance.
 A class implements an interface, thereby inheriting the
abstract methods of the interface.
 An interface is not a class. Writing an interface is similar
to writing a class, but they are two different concepts. A
class describes the attributes and behaviors of an
object. An interface contains behaviors that a class
 Unless the class that implements the interface is
abstract, all the methods of the interface need to
be defined in the class.
 Java does not allow multiple inheritance for
classes (i.e. a subclass being the extension of
more than one superclass).
 An interface is similar to a class in the following
ways:
 An interface can contain any number of methods.
 An interface is written in a file with a .java
extension, with the name of the interface matching
the name of the file.
 The bytecode of an interface appears in a .class
file.
 However, an interface is different from a class in
several ways, including:
 You cannot instantiate an interface.
 An interface does not contain any constructors.
 All of the methods in an interface are abstract.
 An interface cannot contain instance fields.
 An interface is not extended by a class; it is
implemented by a class.
 An interface can extend multiple interfaces.
 The interface keyword is used to declare an
interface.
public interface NameOfInterface
{
//Any number of final, static fields
//Any number of abstract method declarations
}
 Interfaces have the following properties:
 An interface is implicitly abstract. You do not need to use
the abstract keyword when declaring an interface.
 Each method in an interface is also implicitly abstract, so
the abstract keyword is not needed.
 Methods in an interface are implicitly public.
 A class uses the implements keyword to implement an
interface.
 The implements keyword appears in the class declaration
following the extends portion of the declaration.
interface Animal { public void eat(); public void travel(); }
public class MammalInt implements Animal{
public void eat(){ System.out.println("Mammal eats"); }
public void travel(){ System.out.println("Mammal travels"); }
public int noOfLegs(){ return 0; }
public static void main(String args[]){
MammalInt m = new MammalInt();
m.eat();
m.travel();
}
}
Output:
Mammal eats
Mammal travels
 An interface can extend another interface, similarly to
the way that a class can extend another class.
 The extends keyword is used to extend an interface,
and the child interface inherits the methods of the
parent interface.
public interface Sports{
public void setHomeTeam(String name);
public void setVisitingTeam(String name);
}
public interface Football extends Sports{
public void homeTeamScored(int points);
public void visitingTeamScored(int points);
public void endOfQuarter(int quarter);
}
public interface Hockey extends Sports{
public void homeGoalScored();
public void visitingGoalScored();
public void endOfPeriod(int period);
public void overtimePeriod(int ot);
}
 The Hockey interface has four methods, but it inherits
two from Sports; thus, a class that implements Hockey
needs to implement all six methods.
 Similarly, a class that implements Football needs to
define the three methods from Football and the two
methods from Sports.
 Note that an interface can extend more than one parent
interface
 When should you use an abstract class, when an
interface, when both?
 Interfaces and abstract classes seem superficially to
provide almost the same capability.
 How do you decide which to use?
interfacevsabstract.html
 Polymorphism (from the Greek, meaning “many forms”)
is the ability of an object to take on many forms.
 The most common use of polymorphism in OOP occurs
when a parent class reference is used to refer to a child
class object.
 A reference variable can be of only one type. Once
declared the type of a reference variable cannot be
changed.
 The reference variable can be reassigned to other
objects provided that it is not declared final.
 The type of the reference variable would determine the
methods that it can invoke on the object.
 A reference variable can refer to any object of its
public class Shape{
public double computeArea(){ return -1; }
Public double computeCircumfrence(){ return -1; }
}
public class Circle extends Shape{
private double radius;
public Circle(double r){ this.radius = r;}
public double computeArea(){return Math.PI*this.radius *
this.radius; }
public double computeCircumfrence(){ return
2*Math.PI*this.radius; }
}
public class Rectangle extends Shape{
private double width;
private double height;
public Rectangle(double w, double h){this.width =
0;this.height = 0;}
public double computeArea(){ return this.width *
this.height; }
public double computeCircum(){return 2*(this.width
*this.height);}
}
public class ShapeTest{
public static void main(String args[]){
Shape[] shapes = new Shape[3];
shapes[0] = new Circle(4.0);
double totalArea = 0;
for(int i = 0;i<shapes.length;i++){
totalArea+=shapes[i].computeArea();
}
System.out.println(“Total area = “ +totalArea);
}
}
Out Put: Total area = 60.44424265506762
 A reference variable of type Shape is used to refer
objects of types of its subclasses (Circle and
rectangle)
 What is the output of the above code if you comment
out computeArea() method in Circle and Rectangle
classes?
Out Put: Total area = -3.0
 When a superclass variable contains a reference to a
subclass object, and that reference is used to call a
method, the subclass version of the method is called.
(See the example on shapes)
 The output illustrates that the appropriate methods for
each class are indeed invoked based on the type of
the object to which shapes refers.
 This is called dynamic binding or late binding.
 However, if a program needs to perform a subclass-
specific operation on a subclass object referenced by
a superclass variable, the program must first cast the
superclass reference to a subclass reference through
a technique known as downcasting.
 This enables the program to invoke subclass methods
that are not in the superclass.
 To know which subclass’s object (or any of subclass’s
subclass objects) is stored in a supperclass reference,
use instanceOf operator.
 And if it is the type of the subclass in question,
downcast it explicitly.
 For Example if a Rectangle class had getDiagonal()
method and if we want to use this method we must first
downcast it.
if(shap[1] instanceOf Rectangle)
Rectangle r = (Rectangle)shapes[1];
 We cannot treat a superclass object as a subclass
object because a superclass object is not an object of
any of its subclasses.
 It is possible to display each shape’s type as a
string.
for(int i = 0;i<shapes.length;i++){
System.out.printf( “Shape %d is a %sn", i,
shapes[ i] .getClass().getName());
}
 The output is
Shape 0 is a Circle
Shape 1 is a Rectangle
Shape 2 is a Circle
 Polymorphism can also be achieved through
method overriding and method overloading.
 Overridden methods
 are methods that are redefined within an inherited
or subclass. They have the same signature and the
subclass definition is used.
 The implementation in the subclass overrides
(replaces) the implementation in the superclass.
 In other words an instance method in a subclass
with the same signature (name, plus the number and
the type of its parameters) and return type as an
instance method in the superclass overrides the
superclass's method.
class Rectangle {
private int x, y, w, h;
public String toString() {
return “x = “ + x + “, y = “ + y +“, w = “ + w + “, h = “ + h;
}
}
class DecoratedRectangle extends Rectangle {
private int borderWidth;
public String toString() {
return super.toString() + “, borderWidth = “ +
borderWidth;
}
}
 The argument list should be exactly the same as that
of the overridden method.
 The return type should be the same or a subtype of
the return type declared in the original overridden
method in the super class.
 The access level cannot be more restrictive than the
overridden method's access level. For example: if the
super class method is declared public then the
overridding method in the sub class cannot be either
private or protected. However the access level can
be less restrictive than the overridden method's
access level.
 Instance methods can be overridden only if they are
inherited by the subclass.
 Constructors cannot be overridden.
 A method declared final cannot be overridden.
 A method declared static cannot be overridden but can be
re-declared.
 If a method cannot be inherited then it cannot be
overridden.
 A subclass within the same package as the instance's
superclass can override any superclass method that is
not declared private or final.
 A subclass in a different package can only override the
non-final methods declared public or protected.
 An overriding method can throw any uncheck exceptions,
regardless of whether the overridden method throws
exceptions or not. However the overridden method should
not throw checked exceptions that are new or broader
 We already have discussed method overriding,
where a child class can override a method in its
parent.
 An overridden method is essentially hidden in the
parent class, and is not invoked unless the child
class uses the super keyword within the overriding
method.
 Calling overridden method from subclass using super
class reference is referred to as virtual method
invocation, and the methods are referred to as virtual
methods.
 All methods in Java behave in this manner, whereby
an overridden method is invoked at run time, no
 Method Overloading
 Overloaded methods are methods with the same name
signature but either a different number of parameters or
different types in the parameter list.
 Compiler automatically select the most appropriate method
based on the parameter supplied.
 Example
public class MultiplyNumbers {
public int Multiply(int a, int b) {
return a * b;
}
public int Multiply(int a, int b, int c) {
eturn a*b*c;
}
}
 A Package (named collections of classes) can be
defined as a grouping of related types(classes and
interfaces) providing access protection and name space
management.
 Packages are used in Java in-order to prevent naming
conflicts, to control access, to make searching/locating
and usage of classes, interfaces, enumerations and
annotations easier etc.
 Java has numerous built in packages: java.io, java.lang,
java.util …
 Programmers can define their own packages to bundle
group of classes/interfaces etc.
 It is a good practice to group related classes
 When creating a package, you should choose a name
for the package and put a package statement with that
name at the top of every source file that contains the
classes and interfaces types that you want to include in
the package.
 The package statement should be the first line in the
source file.
 There can be only one package statement in each
source file, and it applies to all types in the file.
 It is common practice to use lowercased names of
packages to avoid any conflicts with the names of
classes, interfaces.
 If a package statement is not used then the class and
 If a class wants to use another class in the same
package, the package name does not need to be
used.
 Classes in the same package find each other
without any special syntax.
 A class file can contain any number of import
statements.
 The import statements must appear after the
package statement and before the class
declaration.
 Let us look at an example that creates a package
called animals.
package animals;
interface Animal {
public void eat();
public void travel();
}
//-------------------------------------------------------------------------
-
package animals;
public class MammalInt implements Animal{
public void eat(){ System.out.println("Mammal eats");
}
public void travel(){ System.out.println("Mammal
public static void main(String args[]){
MammalInt m = new MammalInt();
m.eat();
m.travel();
}
}
 Now you compile these two files and put them in a
sub-directory called animals and try to run as follows:
$ mkdir animals
$ cp Animal.class MammalInt.class animals
$ java animals/MammalInt
Mammal eats
Mammal travels
 Here a class named Boss is added to the payroll
package that already contains Employee.
 The Boss can then refer to the Employee class without
using the payroll prefix, as demonstrated by the
following Boss class.
package payroll;
public class Boss{
public void payEmployee(Employee e) {
e.mailCheck();
}
}
 If Boss was not in the payroll package, then use
one of the following techniques for referring to a
class in a different package.
 The fully qualified name of the class can be used.
For example: payroll.Employee
 The package can be imported using the import
keyword and the wild card (*).
For example: import payroll.*;
 The class itself can be imported using the import
keyword.
For example: import payroll.Employee;
 Passing by value for primitive type value
 the value is passed to the parameter
 Passing by value for reference type value
 the value is the reference to the object
 Example
public class TestPassObject {
public static void main(String[] args) {
radius 1 Circle3 myCircle = new Circle3(1);
int n = 5;
printAreas(myCircle, n);
System.out.println("n" + "Radius is " +
myCircle.getRadius());
System.out.println("n is " + n);
}
public static void printAreas(Circle3 c, int times) {
System.out.println("Radius ttArea");
while (times >= 1) {
System.out.println(c.getRadius() + "tt" +
c.getArea()); c.setRadius(c.getRadius() + 1);
times--;
}
}
}
 A reference type of Circle3 called c is passed to
a function printAreas()
public class BirthDate {
private int year;
private int month;
private int day;
public BirthDate(int newYear,
int newMonth, int newDay) {
year = newYear;
month = newMonth;
day = newDay;
}
public void setYear(int newYear) {
year = newYear;
}
}
public class Student {
private int id;
private BirthDate birthDate;
public Student(int ssn,
int year, int month, int day) {
id = ssn;
birthDate = new BirthDate(year, month, day);
}
public int getId() {
return id;
}
public BirthDate getBirthDate() {
return birthDate;
}
}
BirthDate is
returned
public class Test {
public static void main(String[]args{
Student student = new
Student(111223333, 1970, 5, 3);
BirthDate date =
student.getBirthDate();
date.setYear(2010);
// Now the student birth year is changed!
}
}
Chapter 5 (OOP Principles).ppt

More Related Content

Similar to Chapter 5 (OOP Principles).ppt

A457405934_21789_26_2018_Inheritance.ppt
A457405934_21789_26_2018_Inheritance.pptA457405934_21789_26_2018_Inheritance.ppt
A457405934_21789_26_2018_Inheritance.ppt
RithwikRanjan
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
mha4
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
mha4
 
Lecture 6 inheritance
Lecture   6 inheritanceLecture   6 inheritance
Lecture 6 inheritance
manish kumar
 
11.Object Oriented Programming.pdf
11.Object Oriented Programming.pdf11.Object Oriented Programming.pdf
11.Object Oriented Programming.pdf
Export Promotion Bureau
 
Inheritance Slides
Inheritance SlidesInheritance Slides
Inheritance Slides
Ahsan Raja
 
Chapter 8.2
Chapter 8.2Chapter 8.2
Chapter 8.2
sotlsoc
 
Java02
Java02Java02
java_inheritance.pdf
java_inheritance.pdfjava_inheritance.pdf
java_inheritance.pdf
JayMistry91473
 
C++ Notes
C++ NotesC++ Notes
Inheritance and Polymorphism in java simple and clear
Inheritance and Polymorphism in java simple and clear Inheritance and Polymorphism in java simple and clear
Inheritance and Polymorphism in java simple and clear
ASHNA nadhm
 
Inheritance in Java beginner to advance with examples.pptx
Inheritance in Java beginner to advance with examples.pptxInheritance in Java beginner to advance with examples.pptx
Inheritance in Java beginner to advance with examples.pptx
naeemcse
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in java
CPD INDIA
 
3 functions and class
3   functions and class3   functions and class
3 functions and class
trixiacruz
 
Class and object in C++ By Pawan Thakur
Class and object in C++ By Pawan ThakurClass and object in C++ By Pawan Thakur
Class and object in C++ By Pawan Thakur
Govt. P.G. College Dharamshala
 
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCE
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCECLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCE
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCE
Venugopalavarma Raja
 
Lecture 2 (1)
Lecture 2 (1)Lecture 2 (1)
Lecture 2 (1)
zahid khan
 
Jedi slides 2.1 object-oriented concepts
Jedi slides 2.1 object-oriented conceptsJedi slides 2.1 object-oriented concepts
Jedi slides 2.1 object-oriented concepts
Maryo Manjaruni
 
Introduction to OOP with PHP
Introduction to OOP with PHPIntroduction to OOP with PHP
Introduction to OOP with PHP
Michael Peacock
 
20 Object-oriented programming principles
20 Object-oriented programming principles20 Object-oriented programming principles
20 Object-oriented programming principles
maznabili
 

Similar to Chapter 5 (OOP Principles).ppt (20)

A457405934_21789_26_2018_Inheritance.ppt
A457405934_21789_26_2018_Inheritance.pptA457405934_21789_26_2018_Inheritance.ppt
A457405934_21789_26_2018_Inheritance.ppt
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
 
Lecture 6 inheritance
Lecture   6 inheritanceLecture   6 inheritance
Lecture 6 inheritance
 
11.Object Oriented Programming.pdf
11.Object Oriented Programming.pdf11.Object Oriented Programming.pdf
11.Object Oriented Programming.pdf
 
Inheritance Slides
Inheritance SlidesInheritance Slides
Inheritance Slides
 
Chapter 8.2
Chapter 8.2Chapter 8.2
Chapter 8.2
 
Java02
Java02Java02
Java02
 
java_inheritance.pdf
java_inheritance.pdfjava_inheritance.pdf
java_inheritance.pdf
 
C++ Notes
C++ NotesC++ Notes
C++ Notes
 
Inheritance and Polymorphism in java simple and clear
Inheritance and Polymorphism in java simple and clear Inheritance and Polymorphism in java simple and clear
Inheritance and Polymorphism in java simple and clear
 
Inheritance in Java beginner to advance with examples.pptx
Inheritance in Java beginner to advance with examples.pptxInheritance in Java beginner to advance with examples.pptx
Inheritance in Java beginner to advance with examples.pptx
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in java
 
3 functions and class
3   functions and class3   functions and class
3 functions and class
 
Class and object in C++ By Pawan Thakur
Class and object in C++ By Pawan ThakurClass and object in C++ By Pawan Thakur
Class and object in C++ By Pawan Thakur
 
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCE
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCECLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCE
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCE
 
Lecture 2 (1)
Lecture 2 (1)Lecture 2 (1)
Lecture 2 (1)
 
Jedi slides 2.1 object-oriented concepts
Jedi slides 2.1 object-oriented conceptsJedi slides 2.1 object-oriented concepts
Jedi slides 2.1 object-oriented concepts
 
Introduction to OOP with PHP
Introduction to OOP with PHPIntroduction to OOP with PHP
Introduction to OOP with PHP
 
20 Object-oriented programming principles
20 Object-oriented programming principles20 Object-oriented programming principles
20 Object-oriented programming principles
 

Recently uploaded

B. Ed Syllabus for babasaheb ambedkar education university.pdf
B. Ed Syllabus for babasaheb ambedkar education university.pdfB. Ed Syllabus for babasaheb ambedkar education university.pdf
B. Ed Syllabus for babasaheb ambedkar education university.pdf
BoudhayanBhattachari
 
The History of Stoke Newington Street Names
The History of Stoke Newington Street NamesThe History of Stoke Newington Street Names
The History of Stoke Newington Street Names
History of Stoke Newington
 
Walmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdfWalmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdf
TechSoup
 
UGC NET Exam Paper 1- Unit 1:Teaching Aptitude
UGC NET Exam Paper 1- Unit 1:Teaching AptitudeUGC NET Exam Paper 1- Unit 1:Teaching Aptitude
UGC NET Exam Paper 1- Unit 1:Teaching Aptitude
S. Raj Kumar
 
Mule event processing models | MuleSoft Mysore Meetup #47
Mule event processing models | MuleSoft Mysore Meetup #47Mule event processing models | MuleSoft Mysore Meetup #47
Mule event processing models | MuleSoft Mysore Meetup #47
MysoreMuleSoftMeetup
 
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...
Nguyen Thanh Tu Collection
 
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptxBeyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
EduSkills OECD
 
How to deliver Powerpoint Presentations.pptx
How to deliver Powerpoint  Presentations.pptxHow to deliver Powerpoint  Presentations.pptx
How to deliver Powerpoint Presentations.pptx
HajraNaeem15
 
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
PECB
 
Film vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movieFilm vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movie
Nicholas Montgomery
 
IGCSE Biology Chapter 14- Reproduction in Plants.pdf
IGCSE Biology Chapter 14- Reproduction in Plants.pdfIGCSE Biology Chapter 14- Reproduction in Plants.pdf
IGCSE Biology Chapter 14- Reproduction in Plants.pdf
Amin Marwan
 
Constructing Your Course Container for Effective Communication
Constructing Your Course Container for Effective CommunicationConstructing Your Course Container for Effective Communication
Constructing Your Course Container for Effective Communication
Chevonnese Chevers Whyte, MBA, B.Sc.
 
clinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdfclinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdf
Priyankaranawat4
 
Chapter wise All Notes of First year Basic Civil Engineering.pptx
Chapter wise All Notes of First year Basic Civil Engineering.pptxChapter wise All Notes of First year Basic Civil Engineering.pptx
Chapter wise All Notes of First year Basic Civil Engineering.pptx
Denish Jangid
 
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdfANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
Priyankaranawat4
 
How to Create a More Engaging and Human Online Learning Experience
How to Create a More Engaging and Human Online Learning Experience How to Create a More Engaging and Human Online Learning Experience
How to Create a More Engaging and Human Online Learning Experience
Wahiba Chair Training & Consulting
 
The basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptxThe basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptx
heathfieldcps1
 
Bed Making ( Introduction, Purpose, Types, Articles, Scientific principles, N...
Bed Making ( Introduction, Purpose, Types, Articles, Scientific principles, N...Bed Making ( Introduction, Purpose, Types, Articles, Scientific principles, N...
Bed Making ( Introduction, Purpose, Types, Articles, Scientific principles, N...
Leena Ghag-Sakpal
 
writing about opinions about Australia the movie
writing about opinions about Australia the moviewriting about opinions about Australia the movie
writing about opinions about Australia the movie
Nicholas Montgomery
 
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptxC1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
mulvey2
 

Recently uploaded (20)

B. Ed Syllabus for babasaheb ambedkar education university.pdf
B. Ed Syllabus for babasaheb ambedkar education university.pdfB. Ed Syllabus for babasaheb ambedkar education university.pdf
B. Ed Syllabus for babasaheb ambedkar education university.pdf
 
The History of Stoke Newington Street Names
The History of Stoke Newington Street NamesThe History of Stoke Newington Street Names
The History of Stoke Newington Street Names
 
Walmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdfWalmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdf
 
UGC NET Exam Paper 1- Unit 1:Teaching Aptitude
UGC NET Exam Paper 1- Unit 1:Teaching AptitudeUGC NET Exam Paper 1- Unit 1:Teaching Aptitude
UGC NET Exam Paper 1- Unit 1:Teaching Aptitude
 
Mule event processing models | MuleSoft Mysore Meetup #47
Mule event processing models | MuleSoft Mysore Meetup #47Mule event processing models | MuleSoft Mysore Meetup #47
Mule event processing models | MuleSoft Mysore Meetup #47
 
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...
 
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptxBeyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
 
How to deliver Powerpoint Presentations.pptx
How to deliver Powerpoint  Presentations.pptxHow to deliver Powerpoint  Presentations.pptx
How to deliver Powerpoint Presentations.pptx
 
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
 
Film vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movieFilm vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movie
 
IGCSE Biology Chapter 14- Reproduction in Plants.pdf
IGCSE Biology Chapter 14- Reproduction in Plants.pdfIGCSE Biology Chapter 14- Reproduction in Plants.pdf
IGCSE Biology Chapter 14- Reproduction in Plants.pdf
 
Constructing Your Course Container for Effective Communication
Constructing Your Course Container for Effective CommunicationConstructing Your Course Container for Effective Communication
Constructing Your Course Container for Effective Communication
 
clinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdfclinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdf
 
Chapter wise All Notes of First year Basic Civil Engineering.pptx
Chapter wise All Notes of First year Basic Civil Engineering.pptxChapter wise All Notes of First year Basic Civil Engineering.pptx
Chapter wise All Notes of First year Basic Civil Engineering.pptx
 
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdfANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
 
How to Create a More Engaging and Human Online Learning Experience
How to Create a More Engaging and Human Online Learning Experience How to Create a More Engaging and Human Online Learning Experience
How to Create a More Engaging and Human Online Learning Experience
 
The basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptxThe basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptx
 
Bed Making ( Introduction, Purpose, Types, Articles, Scientific principles, N...
Bed Making ( Introduction, Purpose, Types, Articles, Scientific principles, N...Bed Making ( Introduction, Purpose, Types, Articles, Scientific principles, N...
Bed Making ( Introduction, Purpose, Types, Articles, Scientific principles, N...
 
writing about opinions about Australia the movie
writing about opinions about Australia the moviewriting about opinions about Australia the movie
writing about opinions about Australia the movie
 
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptxC1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
 

Chapter 5 (OOP Principles).ppt

  • 1.
  • 2.  OOP Principles  Encapsulation and Data abstraction.  Inheritance  Super keyword  Abstract Classes  Interface  Polymorphism  Method overridding  Method overloading  Packages  Passing and returning objects  Wrapper Classes (Reading Assignment)
  • 3.  All object-oriented programming languages provide mechanisms that help you implement the object-oriented model.  The three fundamental object oriented programming principles are:  Encapsulation (data hiding) and Data abstraction  Inheritance  Polymorphism  Main purpose of these principles is to manage software system complexity by improving software quality factors.
  • 4. Encapsulation refers to the combining of fields and methods together in a class such that the methods operate on the data, as opposed to users of the class accessing the fields directly.  It is a the technique which involves making the fields in a class private and providing access to the fields via public .. Class
  • 5.  If a field is declared private, it cannot be accessed by anyone outside the class, thereby hiding the fields within the class.  For this reason, encapsulation is also referred to as data hiding.  Encapsulation can be described as a protective barrier that prevents the code and data being randomly accessed by other code defined outside the class.  Access to the data and code is tightly controlled by an interface.  The main benefit of encapsulation is the ability to modify our implemented code without breaking the
  • 6. public class EncapTest{ private String name; private String idNum; private int age; public int getAge(){ return age; } public String getName(){ return name; } public String getIdNum(){ return idNum; } public void setAge( int newAge){ age = newAge; } public void setName(String newName){ name = newName; } public void setIdNum( String newId){ idNum = newId; } }
  • 7.  The public methods are the access points to this class’s fields from the outside java world.  Normally these methods are referred as getters and setters. Therefore any class that wants to access the variables should access them through these getters and setters.  The variables of the EncapTest class can be accessed as below: public class RunEncap{ public static void main(String args[]){ EncapTest encap = new EncapTest(); encap.setName("James"); encap.setAge(20); encap.setIdNum("12343ms"); System.out.print("Name : " + encap.getName()+ " Age : "+ encap.getAge()); } } Out Put: Name : James Age : 20
  • 8.  Classes normally hide the details of their implementation from their clients.  This is called information hiding.  The client cares about what functionality a class offers, not about how that functionality is implemented.  This concept is referred to as data abstraction.
  • 10.
  • 12.  In object-oriented programming (OOP)  Inheritance is the capability of a class to use the properties and methods of another class (Super Classes) while adding its own functionality.  I.e. Inheritance is a way to form new classes using classes that have already been defined.  Inheritance is employed to help reuse existing code with little or no modification.  The new classes, known as derived classes, inherit attributes and behavior of the pre-existing classes, which are referred to as base classes (or ancestor classes).  The inheritance relationship of sub- and superclasses gives rise to a hierarchy.  With the use of inheritance the information is made manageable in a hierarchical order.
  • 13.  Elements to be inherited form parent class are protected and public Members.  Applications of inheritance  Specialization  the new class or object has data or behavior aspects that are not part of the inherited class.  Overriding  permit a class or object to replace the implementation of an aspect—typically a behavior—that it has inherited  Code re-use  re-use of code which already existed in another class.
  • 14.  When we talk about inheritance in java the most commonly used key words would be extends and implements.  These words would determine whether one object IS-A type of another.  With use of the extends keyword the subclasses will be able to inherit all the properties of the superclass except for the private properties of the superclass.  IS-A defines relationship between a superclass and its subclasses.  This means that an object of a subclass can be
  • 15. public class Student { protected String name; public Student() { name = “”; } public Student(String s) { name = s; } public String getName() { return name; } } Note: Object is the super class of all Java Classes
  • 16.  Now based on the above example, In Object Oriented terms following are true:  Animal is the superclass of Mammal and Reptile classes.  Mammal and Reptile are subclasses of Animal class.  Dog is the subclass of both Mammal and Animal classes.  A very important fact to remember is that Java only supports only single inheritance. This means that a class cannot extend more than one class. Therefore the following is illegal: public class extends Animal, Mammal{…} public class Animal{ …} public class Mammal extends Animal{…} public class Reptile extends Animal{…} public class Dog extends Mammal{…}
  • 17.  We can assure that Mammal is actually an Animal with the use of the instance operator. public class Dog extends Mammal{ public static void main(String args[]){ Animal a = new Animal(); Mammal m = new Mammal(); Dog d = new Dog(); System.out.println(m instanceof Animal); System.out.println(d instanceof Mammal); System.out.println(d instanceof Animal); } } This would produce following result: true true true
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.  When extending a class constructor you can reuse the immediate superclass constructor and overridden superclass methods by using the reserved word super.  Note that  You cannot override final methods, methods in final classes, private methods or static methods.  Example class A{ int a, b, c; A(int p, int q, int r){ a=p; b=q; c=r; } void Show(){ System.out.println("a = " + a); System.out.println("b = " + b); System.out.println("c = " + c); } }
  • 23. public class B extends A{ int d; B(int l, int m, int n, int o){ super(l, m, n); d=o; } void Show(){ super.show() System.out.println("d = " + d); } public static void main(String args[] ){ B b = new B(4,3,8,7); b.Show(); } } Output a = 4 b = 3 c = 8 d = 7
  • 24.  An abstract class is one that cannot be instantiated. Abstraction refers to the ability to make a class abstract in OOP.  All other functionality of the class still exists, and its fields, methods, and constructors are all accessed in the same manner.  Classes that can be instantiated are known as concrete classes.  If a class is abstract and cannot be instantiated, the class does not have much use unless it is subclassed. This is typically how abstract classes come about during the design phase.  A parent class contains the common functionality of a collection of child classes, but the parent class itself is too abstract to be used on its own.
  • 25. public abstract class Employee{ private String name, address; private int number; public Employee(String name, String address, int number){ System.out.println("Constructing an Employee"); this.name = name; this.address = address; this.number = number; } public double computePay() { System.out.println("Inside Employee computePay"); return 0.0; }
  • 26. public void mailCheck(){ System.out.println("Within mailCheck of Salary class "); System.out.println("Mailing a check to " + name + " " + address); } public String toString() { return name + " " + address + " " + number; } public String getName() { return name; } public String getAddress() { return address; } public void setAddress(String newAddress) { address = newAddress; } public int getNumber(){ return number; } }  When you would compile, using instances of Employee class, above class then you would get following error:
  • 27. public class Salary extends Employee { private double salary; //Annual salary public Salary(String name, String address, int number, double salary){ super(name, address, number); setSalary(salary); } public void mailCheck(){ System.out.println("Within mailCheck of Salary class "); System.out.println("Mailing check to " + getName() + " with salary " + salary); }
  • 28. public double getSalary(){ return salary; } public void setSalary(double newSalary){ if(newSalary >= 0.0){ salary = newSalary; } } public double computePay(){ System.out.println("Computing salary pay for " + getName()); return salary/52; } }
  • 29.  Here we cannot instantiate a new Employee, but if we instantiate a new Salary object, the Salary object will inherit the three fields and seven methods from Employee. public class AbstractDemo{ public static void main(String [] args) { Salary s = new Salary("Mohd ", "Ambehta, UP“, 3, 3600.00); Salary e = new Salary("John ", "Boston, MA", 2, 2400.00); System.out.println("Call mailCheck using Salary reference --"); s.mailCheck(); System.out.println("n Call mailCheck using Employee reference--"); e.mailCheck();
  • 30.  This would produce following result: Constructing an Employee Constructing an Employee Call mailCheck using Salary reference -- Within mailCheck of Salary class Mailing check to Mohd Mohtashim with salary 3600.0 Call mailCheck using Employee reference-- Within mailCheck of Salary class Mailing check to John Adams with salary 2400.
  • 31.  If you want a class to contain a particular method but you want the actual implementation of that method to be determined by child classes, you can declare the method in the parent class as abstract.  The abstract keyword is also used to declare a method as abstract.  An abstract methods consist of a method signature, but no method body - its signature is followed by a semicolon, not curly braces as usual.  Declaring a method as abstract has two results:  The class must also be declared abstract. If a class contains an abstract method, the class must be abstract as well.
  • 32. public abstract class Employee{ private String name, address; private int number; public abstract double computePay(); …//remainder of the class definition } public class Salary extends Employee{ private double salary; //Annual salary public double computePay(){ System.out.println("Computing salary pay for " + getName()); return salary/52; } …//remainder of the class defiition }
  • 33.  Interfaces are similar to abstract classes but all methods are abstract and all data fields are static final.  That is an interface is a collection of abstract methods and static final variables.  Interfaces can be inherited (i.e. you can have a sub- interface). As with classes the extends keyword is used for inheritance.  A class implements an interface, thereby inheriting the abstract methods of the interface.  An interface is not a class. Writing an interface is similar to writing a class, but they are two different concepts. A class describes the attributes and behaviors of an object. An interface contains behaviors that a class
  • 34.  Unless the class that implements the interface is abstract, all the methods of the interface need to be defined in the class.  Java does not allow multiple inheritance for classes (i.e. a subclass being the extension of more than one superclass).  An interface is similar to a class in the following ways:  An interface can contain any number of methods.  An interface is written in a file with a .java extension, with the name of the interface matching the name of the file.  The bytecode of an interface appears in a .class file.
  • 35.  However, an interface is different from a class in several ways, including:  You cannot instantiate an interface.  An interface does not contain any constructors.  All of the methods in an interface are abstract.  An interface cannot contain instance fields.  An interface is not extended by a class; it is implemented by a class.  An interface can extend multiple interfaces.
  • 36.  The interface keyword is used to declare an interface. public interface NameOfInterface { //Any number of final, static fields //Any number of abstract method declarations }  Interfaces have the following properties:  An interface is implicitly abstract. You do not need to use the abstract keyword when declaring an interface.  Each method in an interface is also implicitly abstract, so the abstract keyword is not needed.  Methods in an interface are implicitly public.
  • 37.  A class uses the implements keyword to implement an interface.  The implements keyword appears in the class declaration following the extends portion of the declaration. interface Animal { public void eat(); public void travel(); } public class MammalInt implements Animal{ public void eat(){ System.out.println("Mammal eats"); } public void travel(){ System.out.println("Mammal travels"); } public int noOfLegs(){ return 0; } public static void main(String args[]){ MammalInt m = new MammalInt(); m.eat(); m.travel(); } } Output: Mammal eats Mammal travels
  • 38.  An interface can extend another interface, similarly to the way that a class can extend another class.  The extends keyword is used to extend an interface, and the child interface inherits the methods of the parent interface. public interface Sports{ public void setHomeTeam(String name); public void setVisitingTeam(String name); } public interface Football extends Sports{ public void homeTeamScored(int points); public void visitingTeamScored(int points); public void endOfQuarter(int quarter); }
  • 39. public interface Hockey extends Sports{ public void homeGoalScored(); public void visitingGoalScored(); public void endOfPeriod(int period); public void overtimePeriod(int ot); }  The Hockey interface has four methods, but it inherits two from Sports; thus, a class that implements Hockey needs to implement all six methods.  Similarly, a class that implements Football needs to define the three methods from Football and the two methods from Sports.  Note that an interface can extend more than one parent interface
  • 40.  When should you use an abstract class, when an interface, when both?  Interfaces and abstract classes seem superficially to provide almost the same capability.  How do you decide which to use? interfacevsabstract.html
  • 41.  Polymorphism (from the Greek, meaning “many forms”) is the ability of an object to take on many forms.  The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object.  A reference variable can be of only one type. Once declared the type of a reference variable cannot be changed.  The reference variable can be reassigned to other objects provided that it is not declared final.  The type of the reference variable would determine the methods that it can invoke on the object.  A reference variable can refer to any object of its
  • 42. public class Shape{ public double computeArea(){ return -1; } Public double computeCircumfrence(){ return -1; } } public class Circle extends Shape{ private double radius; public Circle(double r){ this.radius = r;} public double computeArea(){return Math.PI*this.radius * this.radius; } public double computeCircumfrence(){ return 2*Math.PI*this.radius; } }
  • 43. public class Rectangle extends Shape{ private double width; private double height; public Rectangle(double w, double h){this.width = 0;this.height = 0;} public double computeArea(){ return this.width * this.height; } public double computeCircum(){return 2*(this.width *this.height);} } public class ShapeTest{ public static void main(String args[]){ Shape[] shapes = new Shape[3]; shapes[0] = new Circle(4.0);
  • 44. double totalArea = 0; for(int i = 0;i<shapes.length;i++){ totalArea+=shapes[i].computeArea(); } System.out.println(“Total area = “ +totalArea); } } Out Put: Total area = 60.44424265506762  A reference variable of type Shape is used to refer objects of types of its subclasses (Circle and rectangle)  What is the output of the above code if you comment out computeArea() method in Circle and Rectangle classes? Out Put: Total area = -3.0
  • 45.  When a superclass variable contains a reference to a subclass object, and that reference is used to call a method, the subclass version of the method is called. (See the example on shapes)  The output illustrates that the appropriate methods for each class are indeed invoked based on the type of the object to which shapes refers.  This is called dynamic binding or late binding.  However, if a program needs to perform a subclass- specific operation on a subclass object referenced by a superclass variable, the program must first cast the superclass reference to a subclass reference through a technique known as downcasting.  This enables the program to invoke subclass methods that are not in the superclass.
  • 46.  To know which subclass’s object (or any of subclass’s subclass objects) is stored in a supperclass reference, use instanceOf operator.  And if it is the type of the subclass in question, downcast it explicitly.  For Example if a Rectangle class had getDiagonal() method and if we want to use this method we must first downcast it. if(shap[1] instanceOf Rectangle) Rectangle r = (Rectangle)shapes[1];  We cannot treat a superclass object as a subclass object because a superclass object is not an object of any of its subclasses.
  • 47.  It is possible to display each shape’s type as a string. for(int i = 0;i<shapes.length;i++){ System.out.printf( “Shape %d is a %sn", i, shapes[ i] .getClass().getName()); }  The output is Shape 0 is a Circle Shape 1 is a Rectangle Shape 2 is a Circle
  • 48.  Polymorphism can also be achieved through method overriding and method overloading.  Overridden methods  are methods that are redefined within an inherited or subclass. They have the same signature and the subclass definition is used.  The implementation in the subclass overrides (replaces) the implementation in the superclass.  In other words an instance method in a subclass with the same signature (name, plus the number and the type of its parameters) and return type as an instance method in the superclass overrides the superclass's method.
  • 49. class Rectangle { private int x, y, w, h; public String toString() { return “x = “ + x + “, y = “ + y +“, w = “ + w + “, h = “ + h; } } class DecoratedRectangle extends Rectangle { private int borderWidth; public String toString() { return super.toString() + “, borderWidth = “ + borderWidth; } }
  • 50.  The argument list should be exactly the same as that of the overridden method.  The return type should be the same or a subtype of the return type declared in the original overridden method in the super class.  The access level cannot be more restrictive than the overridden method's access level. For example: if the super class method is declared public then the overridding method in the sub class cannot be either private or protected. However the access level can be less restrictive than the overridden method's access level.  Instance methods can be overridden only if they are inherited by the subclass.  Constructors cannot be overridden.
  • 51.  A method declared final cannot be overridden.  A method declared static cannot be overridden but can be re-declared.  If a method cannot be inherited then it cannot be overridden.  A subclass within the same package as the instance's superclass can override any superclass method that is not declared private or final.  A subclass in a different package can only override the non-final methods declared public or protected.  An overriding method can throw any uncheck exceptions, regardless of whether the overridden method throws exceptions or not. However the overridden method should not throw checked exceptions that are new or broader
  • 52.  We already have discussed method overriding, where a child class can override a method in its parent.  An overridden method is essentially hidden in the parent class, and is not invoked unless the child class uses the super keyword within the overriding method.  Calling overridden method from subclass using super class reference is referred to as virtual method invocation, and the methods are referred to as virtual methods.  All methods in Java behave in this manner, whereby an overridden method is invoked at run time, no
  • 53.  Method Overloading  Overloaded methods are methods with the same name signature but either a different number of parameters or different types in the parameter list.  Compiler automatically select the most appropriate method based on the parameter supplied.  Example public class MultiplyNumbers { public int Multiply(int a, int b) { return a * b; } public int Multiply(int a, int b, int c) { eturn a*b*c; } }
  • 54.  A Package (named collections of classes) can be defined as a grouping of related types(classes and interfaces) providing access protection and name space management.  Packages are used in Java in-order to prevent naming conflicts, to control access, to make searching/locating and usage of classes, interfaces, enumerations and annotations easier etc.  Java has numerous built in packages: java.io, java.lang, java.util …  Programmers can define their own packages to bundle group of classes/interfaces etc.  It is a good practice to group related classes
  • 55.  When creating a package, you should choose a name for the package and put a package statement with that name at the top of every source file that contains the classes and interfaces types that you want to include in the package.  The package statement should be the first line in the source file.  There can be only one package statement in each source file, and it applies to all types in the file.  It is common practice to use lowercased names of packages to avoid any conflicts with the names of classes, interfaces.  If a package statement is not used then the class and
  • 56.  If a class wants to use another class in the same package, the package name does not need to be used.  Classes in the same package find each other without any special syntax.  A class file can contain any number of import statements.  The import statements must appear after the package statement and before the class declaration.  Let us look at an example that creates a package called animals.
  • 57. package animals; interface Animal { public void eat(); public void travel(); } //------------------------------------------------------------------------- - package animals; public class MammalInt implements Animal{ public void eat(){ System.out.println("Mammal eats"); } public void travel(){ System.out.println("Mammal
  • 58. public static void main(String args[]){ MammalInt m = new MammalInt(); m.eat(); m.travel(); } }  Now you compile these two files and put them in a sub-directory called animals and try to run as follows: $ mkdir animals $ cp Animal.class MammalInt.class animals $ java animals/MammalInt Mammal eats Mammal travels
  • 59.  Here a class named Boss is added to the payroll package that already contains Employee.  The Boss can then refer to the Employee class without using the payroll prefix, as demonstrated by the following Boss class. package payroll; public class Boss{ public void payEmployee(Employee e) { e.mailCheck(); } }
  • 60.  If Boss was not in the payroll package, then use one of the following techniques for referring to a class in a different package.  The fully qualified name of the class can be used. For example: payroll.Employee  The package can be imported using the import keyword and the wild card (*). For example: import payroll.*;  The class itself can be imported using the import keyword. For example: import payroll.Employee;
  • 61.  Passing by value for primitive type value  the value is passed to the parameter  Passing by value for reference type value  the value is the reference to the object  Example public class TestPassObject { public static void main(String[] args) { radius 1 Circle3 myCircle = new Circle3(1); int n = 5; printAreas(myCircle, n); System.out.println("n" + "Radius is " + myCircle.getRadius()); System.out.println("n is " + n); }
  • 62. public static void printAreas(Circle3 c, int times) { System.out.println("Radius ttArea"); while (times >= 1) { System.out.println(c.getRadius() + "tt" + c.getArea()); c.setRadius(c.getRadius() + 1); times--; } } }  A reference type of Circle3 called c is passed to a function printAreas()
  • 63. public class BirthDate { private int year; private int month; private int day; public BirthDate(int newYear, int newMonth, int newDay) { year = newYear; month = newMonth; day = newDay; } public void setYear(int newYear) { year = newYear; } }
  • 64. public class Student { private int id; private BirthDate birthDate; public Student(int ssn, int year, int month, int day) { id = ssn; birthDate = new BirthDate(year, month, day); } public int getId() { return id; } public BirthDate getBirthDate() { return birthDate; } } BirthDate is returned
  • 65. public class Test { public static void main(String[]args{ Student student = new Student(111223333, 1970, 5, 3); BirthDate date = student.getBirthDate(); date.setYear(2010); // Now the student birth year is changed! } }