8/8/2019 Basic Object Oriented Principals Ppt
1/42
Object Oriented PrincipalsPart 1
8/8/2019 Basic Object Oriented Principals Ppt
2/42
Page 2
By the end of this Course, you should know:o Classes and Objectso Creating Objectso Constructors , Constructor Overloading and Constructor
chainingo Static Context vs. Non Static Contexto Attributes, Methods and Method Overloadingo Inheritanceo Method Overridingo Packages and Access Modifierso
Dynamic Bindingo Abstract Classes and Methodso Final Classes and Methodso Immutable classes and objects
Learning Objectives
8/8/2019 Basic Object Oriented Principals Ppt
3/42
Class
A class defines the specific structure of a given abstractiono what data it haso what methods it has,o how its methods are implemented.
The term Class is used to suggest that it represents all themembers of a given group (or class).o E.g. a SalesPerson class might represent all individuals in the
group of people selling cars at an automobile dealership.
Page 3
Name
CommissionRate
Cars Sold
SalesPerson(Sales Tracking System)
8/8/2019 Basic Object Oriented Principals Ppt
4/42
Object
A class defines the structure ofan entire collection of similarthingso e.g. anyone who is a Sales
Person
An object represents a specificinstance of the classo e.g. the sales person whose
name is Kevin, who has acommission rate of 15%.
The Class definition allows thecommon structure to be definedonce and reused when creatingnew objects that need thestructure defined by the class.
Page 4
Name
CommissionRate
Cars Sold
Sales Person(Sales Tracking System)
Com Rate =0.15
Cars sold = 10
Name =Kevin
Com Rate =0.12
Cars sold = 5
Name =Peter
8/8/2019 Basic Object Oriented Principals Ppt
5/42
Classes and Objects (Example)
class Box{int length; // fieldsint width;int height;public Box(int h, int w, int l) {length = l;width = w;height = h;}
}
Box b1=new Box(5, 5, 5);Box b2=new Box(2, 2, 10);Box b2=new Box(1, 2, 10);
b1
b2
b3
StackHeap
5
55
210
2
10
21
8/8/2019 Basic Object Oriented Principals Ppt
6/42
Using the new Operator
The new operatoro Allocates memory for a new instanceo Invokes the constructor to initialize the new instanceo Returns a reference to the instance
Box b1 = new Box(1,2,10);
Box
b1
Heap
Stack
8/8/2019 Basic Object Oriented Principals Ppt
7/42
Constructors 1(1)
A constructor is a special method for initializing a newinstance of a class
Can not make an object from a class without calling itsconstructor
class Box{int length;// attributesint width;int height;public Box() {// constructor
}}
8/8/2019 Basic Object Oriented Principals Ppt
8/42
Constructors 2(2)
The constructor name must match with the name of theclass
Constructor does not have a return type Default constructor
o
Constructor with no parameterso Automatically generated by the compiler (when there are no
custom constructors)
Copy Constructoro a constructor which takes one argument of the type of the
class (or a reference thereof)
Constructors can use any access modifiers Constructors are not automatically inherited.
8/8/2019 Basic Object Oriented Principals Ppt
9/42
Constructor Overloading
Multiple versions of the constructor, each having differentargument list
class Box{
int length;// fieldsint width;int height;public Box(int len) {// constructor with one parameterlength = len;width = len;height = len;}public Box(int h, int w, int l) { // constructor with three parameterlength = l;
width = w;height = h;}}
8/8/2019 Basic Object Oriented Principals Ppt
10/42
ConstructorChaining (within the sameclass)
One constructor calls the other constructor
class Box{int length;// fieldsint width;
int height;public Box(int len) {// constructor with one parameterthis(len,len,len);}
public Box(int h, int w, int l) { // constructor with three parameterlength = l;width = w;height = h;}}
8/8/2019 Basic Object Oriented Principals Ppt
11/42
Static Context vs. Non Static Context 1(3)
class Box{int length; // Non static fieldsint width;int height;static int noOfBoxObjects;// static fieldpublic Box(int h, int w, int l) {length = l;width = w;height = h;
noOfBoxObjects++;}}
Box b1=new Box(5, 5, 5);Box b2=new Box(2, 2, 10);Box b2=new Box(1, 2, 10);
b1
b2
b3
width =2length = 2height =10
width =1length = 2height =10
width =5length = 5height =5
noOfBoxObjects = 3
StackHeap
8/8/2019 Basic Object Oriented Principals Ppt
12/42
Static Context vs. Non Static Context 2(3)
class Box{int length; // Non static fieldsint width;int height;static int noOfBoxObjects;// static fieldpublic Box(int h, int w, int l) {length = l;width = w;height = h;
noOfBoxObjects++;}}
Box b1=new Box(5, 5, 5);System.out.println(b1.length);// Accessing the instance variablesSystem.out.println(Box.noOfBoxObjects);// Accessing the static variables
8/8/2019 Basic Object Oriented Principals Ppt
13/42
Static Context vs. Non Static Context 3(3)
Class
StaticContext
Memberswith thekeyword
Static
Non StaticContext
Memberswithout thekeyword
Static
8/8/2019 Basic Object Oriented Principals Ppt
14/42
8/8/2019 Basic Object Oriented Principals Ppt
15/42
8/8/2019 Basic Object Oriented Principals Ppt
16/42
Attributes, Constructors & Methods - Example
class Box{int length; // Attributesint width;int height;static int noOfBoxObjects;public Box(int h, int w, int l){// Constructor
length = l;width = w;
height = h;noOfBoxObjects++;
}
public int getVolume(){// Methodreturn length*width*height;}}
8/8/2019 Basic Object Oriented Principals Ppt
17/42
Constructors vs. Methods
Property Constructor Method
Name Always take the class name Can use the class name
Return Type No return type Must specify a return type.
Access modifiers Any valid access modifier Any valid access modifier
Overloading Allowed Allowed
Special Keywords Not allowed Allowed
Parameters Allowed Allowed
8/8/2019 Basic Object Oriented Principals Ppt
18/42
8/8/2019 Basic Object Oriented Principals Ppt
19/42
Methods Overloading 2(2)
class Box{
public int getVolume(){int volume = height * length * width;return volume;}
public void fillBox(){int vol = getVolume();System.out.println( Used + vol+ liters to fill the box);}
public void fillBox(int filledUpTo){int vol =getVolume();if(vol>=filledUpTo){System.out.println( Box is filled up to + filledUpTo + liters);}else{System.out.println( Exceeding the Box capacity);}}
}
8/8/2019 Basic Object Oriented Principals Ppt
20/42
Inheritance Hierarchy
Identify commonalities among a set ofentitieso The commonality may be of attributes,
behavior, or both
Those commonalities are organized intoa tree structured form
At the root of any sub tree are found allthe attributes and behavior common toall of the descendents of that root
This particular kind of tree structure isreferred to as ageneralization/specializationhierarchy orinheritance hierarchy
Ellipse
Shape
Polygon
Circle Rectangle
8/8/2019 Basic Object Oriented Principals Ppt
21/42
Inheritance
Extending Classeso In OOP inheritance is a way to form new classes using
classes that have already been defined
Super Classo The class from which the subclass is derived is called a
superclass (also called as base class orparent class)
Sub Classo A class that is derived from another class is called a subclass
(derived class, extended class, orchild class)
8/8/2019 Basic Object Oriented Principals Ppt
22/42
Identifying a valid Inheritance Hierarchy
Country
Region Car
Vehicle Computer
Mouse Circle
Shape
Simple rule to follow Is ao Region is a Country - Falseo Car is a Vehicle - Trueo Mouse is a Computer - False
o Circle is a Shape - True
8/8/2019 Basic Object Oriented Principals Ppt
23/42
Types ofInheritance hierarchies
Single type inheritance and multiple type inheritance Most of the languages do not support for the multiple type
inheritance directly Java , C#o Deadly diamond problem
C++ supports for multiple type inheritance Multiple inheritance can be simulated via multiple interface
inheritance and forwarding
Car
Vehicle Land Animal
Tiger
Carnivorous Animal
8/8/2019 Basic Object Oriented Principals Ppt
24/42
How to implement
class Shape{public double getArea(){System.out.println(Get the area);return 0;}}class Circle extends Shape{
private double radius;
public double getArea(){return 22/7 * radius * radius;}
}class Rectangle extends Shape{private double length;private double width;
public double getArea(){return length * width;}}
Circle
ShapegetArea()
Rectangle
8/8/2019 Basic Object Oriented Principals Ppt
25/42
Advantages ofInheritancehierarchies
Code Reuseo Allow a new class to re-use code which already existed in
another class
Specializationo The new class or object has data or behavior aspects that are
not part of the inherited class
Overridingo A class or object can replace the implementation of an
aspecttypically a behaviorthat it has inherited
8/8/2019 Basic Object Oriented Principals Ppt
26/42
Reference Variable Casting
Up-Castingo Assign the sub class
reference to a superclass referenceo Always safeo Implicit cast
Car
Vehicle
Van
Down-Castingo Assign the super class
reference to a sub classreferenceo Always not an safe
operationo Need an explicit cast
Car c=new Car();Vehicle h =c;
Van v=new Van();Vehicle h =v;
Van v1 = (Van)h;
Car c=new Car();String s = c;
8/8/2019 Basic Object Oriented Principals Ppt
27/42
Packages and AccessibilityLevels
Packageo Apackage is a grouping of related types providing access
protection and name space managemento Types refers to classes, interfaces, enumerations, and
annotation types
Why we do packaging?o To make types easier to find and useo To avoid naming conflictso Control access
package ifs.application.proj;import ifs.application.enterp.*;
class Project{
//codeCompany c;
}
package ifs.application.enterp;
class Company{
//code
}
8/8/2019 Basic Object Oriented Principals Ppt
28/42
Packages and AccessibilityLevels
Pkg A Pkg B
SuperA
SubA
NormalA
SubB
NormalB
Public Private Protected
DefaultModifiers:
8/8/2019 Basic Object Oriented Principals Ppt
29/42
ConstructorChaining (within Super class& Sub class)
class A{}class B extends A{public B(int x){}
}
class A{public A(){}}class B extends A{
public B(int x){}}
class A{public A(int x){}}class B extends A{
public B(int x){}}
class A{public A(int x){}}class B extends A{
public B(int x){super(x)}}
class A{public A(){}}class B extends A{
public B(){this(10)}public B(int x){}}
B b = new B(3); B b = new B(3); B b = new B(3); B b = new B(3); B b = new B();
Yes.Default no-argconstructor supplied.
Yes.User defined no-argconstructor.
Error! No explicit call of
the A() constuctor Default constructor
A() does not exist
Ok.Explicit call to base classconstructor.
Ok.Explicitly chained tooverloaded constructor.
8/8/2019 Basic Object Oriented Principals Ppt
30/42
8/8/2019 Basic Object Oriented Principals Ppt
31/42
Method Overriding 2(2)
public class Animal {public void eat(){System.out.println("Animal Eating");}}
public class cat extends Animal{
public void eat(){System.out.println("Cat Eating");}}
Animal
Cat
8/8/2019 Basic Object Oriented Principals Ppt
32/42
Overloading Vs Overriding
Overloaded Methods Overridden Methods
Arguments Must Change Must not change
Return Type Can change Can not change except for
covariant returns
Exception Can change Can reduce or eliminate. Mustnot throw new or broaderchecked exceptions
Access Can change Must not make more restrictive.(can be less restrictive)
Invocation By using reference type By using actual object type
8/8/2019 Basic Object Oriented Principals Ppt
33/42
8/8/2019 Basic Object Oriented Principals Ppt
34/42
Dynamic Binding 2(2)
Method Invocation Code Result
Animal a =new Animal();a.eat();
Cat c=new Cat();c.eat();
Animal ac=new Cat();ac.eat();
Cat c1=new Cat();c1.eat(meat);
Animal a2=new Animal();a2.eat(meat);
Animal ac1=new Cat();ac1.eat(meat);
8/8/2019 Basic Object Oriented Principals Ppt
35/42
Abstract Classes and Abstract Methods1(2)
Abstract class Incomplete Classo Can have one or more incomplete (abstract) methodso Cannot be used to instantiate objectso Normally used as base-classes in inheritance hierarchieso Derived classes called concrete classes must define the
missing pieceso Can have instances from the Derived classes
Abstract method Incomplete methodo Only the method signature is thereo Mark with the keyword abstract and a semicolon at the endo Implementation is missing
Does not know how to implement the method
8/8/2019 Basic Object Oriented Principals Ppt
36/42
Abstract Classes and Abstract Methods2(2)
abstract class Shape{public abstract double getArea();
}
class Circle extends Shape{
private double radius;
public double getArea(){return 22/7 * radius * radius;}
}
class Rectangle extends Shape{private double length;private double width;
public double getArea(){return length * width;}}
Circle
ShapegetArea()
Rectangle
8/8/2019 Basic Object Oriented Principals Ppt
37/42
Final Classes and Final methods 1(2)
Final Classo Prevents the class from being subclassedo Violate the whole object oriented notion of inheritance
So why would you ever mark a class final?
o If you need an absolute guarantee that none of the methods in thatclass will ever be overridden
Most of the classes in Java core libraries are finalo Example: String classo If the String class is not a final class, then the Java can not
guarantee how a String object would work on any given system
Final Methodso Prevent the method from being overridden in a sub classo Often used to enforce the API functionality of a method
8/8/2019 Basic Object Oriented Principals Ppt
38/42
Final Classes and Final methods 2(2)
abstract class Shape{public abstract double getArea();
}
final class Circle extends Shape{
private double radius;
public double getArea(){return 22/7 * radius * radius;}
}
class Rectangle extends Shape{private double length;private double width;
public final double getArea(){return length * width;}}
8/8/2019 Basic Object Oriented Principals Ppt
39/42
Immutable Objects 1(2)
Immutable Object
No operation can not change the instance variables of aninstance
Any operation that would normally cause such a change mustinstead return a new object with appropriately adjusted instancevariables
Instance variables may only be set when the object is firstcreated
Strings are immutable objects
8/8/2019 Basic Object Oriented Principals Ppt
40/42
Immutable Objects 2(2)
String s = new String("Alain");String s1=s;s = s.concat(Prost);
Alains1
Stack
s
Heap
AlainProst
8/8/2019 Basic Object Oriented Principals Ppt
41/42
8/8/2019 Basic Object Oriented Principals Ppt
42/42
End ofLesson
Top Related