Professional Documents
Culture Documents
Chapter 3 (OOP Principles)
Chapter 3 (OOP Principles)
M
methods operate on the data, as M Class
2
1
opposed to users of the class
accessing the fields directly. Fields/Data
It is a the technique which
involves making the fields in a M
4
M3
class private and providing
access to the fields via public
methods.
Encapsulation
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.
The main benefit of encapsulation is the ability to
modify our implemented code without breaking the
code of others who use our code.
Encapsulation Example
public class EncapTest{ public void setAge( int newAge){
private String name; age = newAge;
private String idNum; }
private int age; public void setName(String
public int getAge(){ newName){
return age; name = newName;
} }
public String public void setIdNum( String newId)
getName(){ {
return name; idNum = newId;
} }
public String }
getIdNum(){
return idNum;
}
Encapsulation, example
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{
Out Put:
public static void main(String args[]){
Name : James Age : 20
EncapTest encap = new EncapTest();
encap.setName("James");
encap.setAge(20);
encap.setIdNum("12343ms");
System.out.print("Name : " + encap.getName()+ " Age : "+
encap.getAge());
}
}
Data Abstraction
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.
Inheritance
Object-oriented programming (OOP): allows you to
derive new classes from existing classes. This is called
inheritance.
protected Members
Methods
Attributes
Public Members
Methods
Inheritance…
extends.
Syntax
modifier class SubclassName extends SuperclassName
{
//body
}
Example
public class Mammal extends Animal
{
//body
}
Inheritance…
The inheritance relationship is transitive: if class x
extends class y, then a class z, which extends class x,
will also inherit from class y.
public class Animal{ …}
public class Mammal extends Animal{…}
public class Reptile extends Animal{…}
public class Dog extends Mammal{…}
Inheritance …
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.
public Student() {
name = “”;
}
public Student(String s) {
name = s;
}
public String getName(){
return name;
}
}
class Animal {
public int numberOfLegs;
public void talk() {
System.out.println("Hello");
}
}
Inheritance Example…
class Dog extends Animal {
public int numberOfFleas;
public Dog() {
numberOfLegs = 4;
numberOfFleas = 10;
}
public void bark() {
System.out.println("Woof woof");
}
public void scratch() {
if (numberOfFleas > 0) numberOfFleas--;
}
}
Inheritance Example…
Dog d=new Dog();
d.bark();
d.scratch();
System.out.println(d.numberOfFleas);
d.talk();
System.out.println(d.numberOfLegs);
Super keyword
When extending a class you can reuse the
immediate superclass constructor and overridden
superclass methods by using the reserved word
super.
30
Constructor Chaining
public Faculty() {
System.out.println("(4) Faculty's no-arg constructor is invoked");
}
}
//*********************************************************************
class Employee extends Person {
public Employee() {
this("(2) Invoke Employee’s overloaded constructor");
System.out.println("(3) Employee's no-arg constructor is invoked");
}
public Employee(String s) {
System.out.println(s);
}
}
//
************************************************************************
class Person {
public Person() {
System.out.println("(1) Person's no-arg constructor is invoked");
}
}
32
animation
public Employee(String s) {
System.out.println(s);
}
}
class Person {
public Person() {
System.out.println("(1) Person's no-arg constructor is invoked");
}
}
33
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty();
}
Invoke Faculty
public Faculty() {
constructor
System.out.println("(4) Faculty's no-arg constructor is invoked");
}
}
public Employee(String s) {
System.out.println(s);
}
}
class Person {
public Person() {
System.out.println("(1) Person's no-arg constructor is invoked");
}
}
34
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty();
}
public Faculty() {
System.out.println("(4) Faculty's no-arg constructor is invoked");
}
}
Invoke Employee’s no-
class Employee extends Person {
public Employee() { arg constructor
this("(2) Invoke Employee’s overloaded constructor");
System.out.println("(3) Employee's no-arg constructor is invoked");
}
public Employee(String s) {
System.out.println(s);
}
}
class Person {
public Person() {
System.out.println("(1) Person's no-arg constructor is invoked");
}
}
35
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty();
}
public Faculty() {
System.out.println("(4) Faculty's no-arg constructor is invoked");
}
}
Invoke Employee(String)
class Employee extends Person { constructor
public Employee() {
this("(2) Invoke Employee’s overloaded constructor");
System.out.println("(3) Employee's no-arg constructor is invoked");
}
public Employee(String s) {
System.out.println(s);
}
}
class Person {
public Person() {
System.out.println("(1) Person's no-arg constructor is invoked");
}
}
36
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty();
}
public Faculty() {
System.out.println("(4) Faculty's no-arg constructor is invoked");
}
}
Invoke Employee(String)
class Employee extends Person { constructor
public Employee() {
this("(2) Invoke Employee’s overloaded constructor");
System.out.println("(3) Employee's no-arg constructor is invoked");
}
public Employee(String s) {
System.out.println(s);
}
}
class Person {
public Person() {
System.out.println("(1) Person's no-arg constructor is invoked");
}
}
37
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty();
}
public Faculty() {
System.out.println("(4) Faculty's no-arg constructor is invoked");
}
}
public Employee(String s) {
System.out.println(s);
}
}
38
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty();
}
public Faculty() {
System.out.println("(4) Faculty's no-arg constructor is invoked");
}
}
public Employee(String s) {
System.out.println(s);
}
}
class Person {
public Person() { Execute println
System.out.println("(1) Person's no-arg constructor is invoked");
}
}
39
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty();
}
public Faculty() {
System.out.println("(4) Faculty's no-arg constructor is invoked");
}
}
public Employee(String s) {
System.out.println(s);
}
}
Execute println
class Person {
public Person() {
System.out.println("(1) Person's no-arg constructor is invoked");
}
}
40
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty();
}
public Faculty() {
System.out.println("(4) Faculty's no-arg constructor is invoked");
}
}
public Employee(String s) {
System.out.println(s);
}
}
class Person {
public Person() { Execute println
System.out.println("(1) Person's no-arg constructor is invoked");
}
}
41
animation
Trace Execution
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty();
}
public Faculty() {
System.out.println("(4) Faculty's no-arg constructor is invoked");
}
}
public Employee(String s) {
System.out.println(s);
}
}
class Person {
public Person() {
System.out.println("(1) Person's no-arg constructor is invoked");
}
}
42
Inheritance Example
Inheritance Example…
Inheritance Example…
Inheritance Example…
Super keyword….
You can also use super to refer to a hidden field.
Example:
java.lang.System, java.lang.Math
and java.lang.String.
Writing Final Classes and Methods…
A final method cannot be overriden by subclasses.
This is used to prevent unexpected behavior from a
subclass altering a method that may be crucial to the
function or consistency of the class.
You might wish to make a method final if the
method has an implementation that should not be
changed.
All methods in a final class are implicitly final.
Some of these states and behaviors are the same for all
graphic objects—for example: position, fill color, and
moveTo.
Abstraction Example…
An Abstract Class Example
interface Animal {
public void eat();
public void travel();
}
Implementing Interfaces
public class Mammal 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[]){ Output:
Mammal m = new Mammal(); Mammal eats
m.eat(); Mammal travels
m.travel();
}
}
Extending Interfaces
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);
}
Extending Interfaces…
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
public interface Hockey extends Sports, Event
Inheritance (cont’d)
subclass superclass
or extends or
derived class base class
78
Inheritance (cont’d)
In Java, a subclass can extend only one superclass.
In Java, a subinterface can extend several
superinterface
In Java, a class can implement several interfaces —
this is Java’s form of multiple inheritance.
79
Inheritance (cont’d)
An abstract class can have code for some of its
methods; other methods are declared abstract
and left with no code.
An interface only lists methods but does not
have any code.
80
Inheritance (cont’d)
Inheritance plays a dual role:
A subclass reuses the code from the superclass.
A subclass (or a class that implements an interface)
inherits the data type of the superclass (or the
interface) as its own secondary type.
81
Abstrac vs Interface
Unlike interfaces, abstract classes can contain fields
that are not static and final, and they can contain
implemented methods.
shapes[ i].getClass().getName());
}
The output is
Shape 0 is a Circle
Shape 1 is a Rectangle
Shape 2 is a Circle
Polymorphism…
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.
Method overriding example
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;
}
}
Method overriding Rules
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 overriding method in the subclass
cannot be either private or protected.
Method overriding Rules
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.
Method overriding Rules…
A subclass within the same package as 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.
Polymorphism…
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) {
return a*b*c;
}
}
Package
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.