Chap III Heritage Et Polymorphisme
Chap III Heritage Et Polymorphisme
JAVA
1
MEMBERS STATIC OF A CLASS.
■ In the example of the classCount, each object Account
possessed his own code and balance variables. The code
variables and balance are called variables of instances.
■ Objects of the same class can share the same variables which
are stored at the level of the class.This kind of variables, are
called static variables or variables of classes.
2
MEMBERS STATIC OF A CLASS.
■ Like an attribute, a method can be declared static, which means
it belongs to the class and is shared by all instances of that
class.
3
EXEMPLE package job;
■ Assuming we want to add a variable to the
Account class that stores the number of public class Account {
accounts created. Since the value of the // Variables of instances
private int code;
variable nbComptes is the same for all
private float balance;
objects, it will be declared static. Otherwise,
// Variable of class Or static private
it would be duplicated in each new object
static int nbAccounts;
created. public Account(float balance){
this.code=++nbAccounts;
this.balance=balance;
■ The value of nbComptes is initially set to 0, }
and during the creation of a new instance
(within the constructor), nbComptesis public void deposit(float mt){
balance+=mt;
incremented. We also use the value of
}
nbComptes to initialize the account code.
// Method to remove A Rising
public void withdraw(float mt){
Account balance-=mt;
-code : int
}
# balance : float // return the state of account
public String toString(){
-nbAccounts:int
return(" Code="+code+" Balance=" +balance);
+ Account(float balance) }
// returns the value of nbComptes
+ deposit(float mt):void
public static int getNbAccounts(){
+ withdraw(float mt):void return(nbAccounts);
+ toString():String 4
+ getNbComptes():int
APPLICATION OF TEST
package test;
import job.account;
public class Application {
System.out.println(Account.nbAccounts)
System.out.println(c1.nbAccounts)
}
}
5
Inheritance And
accessibility
6
Inheritance
■ In object-oriented programming, inheritance
provides a very efficient way to reuse code.
8
EXEMPLE
Assuming we want to create an application that allows us to manage different types of bank
accounts: simple accounts, savings accounts, and fee-based accounts.
9
DIAGRAMME DE
Account
CLASSES -code : int
# balance : float
-nbComptes : int
+ Compte ( )
+ deposit(float mt) : void
+ retirer (float mt) : void
+ toString() : String
public Account( ){
++nbAccounts;
code=nbAccounts;
this.balance=0;
}
public void deposit(float mt){
balance+=mt;
}
public void withdraw(float mt){
if(mt<balance) balance-=mt;
}
public String toString(){
return("Code="+code+" Balance="+balance);
}
} 11
Inheritance : EXTENDS
The class SimpleAccount is a class that inherits from the class
Account.
The class SimpleAccount inherits from the class Account, including all
its members except the constructor.
12
Inheritance: EXTENDS
■ If a class does not explicitly inherit from another
class, it implicitly inherits from the class Object.
super ();
this. overdraft= overdraft;
}
}
14
Method Overriding
When a class inherits from another class, it can override the inherited
methods.
In the overridden method of the derived class, we can call the method
from the parent class using the keyword super, followed by a dot and
the name of the method.
15
REDEFINITION OF THE METHODS
■ In this news class derived,we will redefine also there method ().
public class SimpleAccount extends Account {
private float overdraft;
// builder
// Redefinition of there method withdraw
public void withdraw(floatmt) {
if(mt+overdraft>balance)
balance-=mt;
}
// Redefinition of there method
public String toString () {
return("AccountSimple "+super.toString()+"
overdraft="+overdraft);
}
} 16
INHERITANCE IN FOCUS: INSTANTIATION
17
OVERLOADING
You can create an instance of the SimpleAccount class by calling one of the two constructors.
SimpleAccountcs1=newSimpleAccount(5000);
SimpleAccount cs2=new SimpleAccount(); 19
ACCESSIBILITY
20
CLASS ABSTRACT
■ An abstract class is a class that cannot be instantiated.
■ The Account class in our model can be declared abstract
to indicate to the compiler that this class cannot be
instantiated.
■ An abstract class is generally created to allow new
classes to be derived from it through inheritance.
public abstract class Account{
private int code;
protected float balance;
private static int nbAccounts;
// Builders
// Methods
} 21
THE METHODS ABSTRACT
■ An abstract method can be declared within an abstract
class.
■ An abstract method is a method that has no definition.
■ An abstract method must be redefined in derived classes.
■ Example:
We can add an abstract method named display() to the
Account class to indicate that all accounts must redefine
this method.
22
THE METHODS ABSTRACT
public abstract class Account {
// Members
…
// Method abstract
public abstract void display();
■ Example of an interface: 24
INTERFACES
public interface Solvable {
public void solver();
public double getSolde();
}
● Static members can be accessed directly by using the name of the class
that contains them.
■ The only members of a class that are accessible without instantiation are 29
static members.
WHO CAN :
● Private access is the most restrictive. It applies to the members of a class (variables,
methods, and inner classes).
● Elements declared as private are only accessible from within the class that contains them.
● This type of access is often used for variables that should only be modified or read
through a getter or setter.
Public:
A public member of a class can be accessed by any other class.
In UML, public members are indicated by the + sign.
Protected:
Members of a class can be declared protected.
In this case, access is limited to methods of classes that belong to:
■
SUMMARY: INHERITANCE
■ A class can inherit from another class using the extends keyword.
A class inherits all its members from another class except for the constructor.
■ The constructor of the derived class must always be defined.
■ The constructor of the derived class can call the constructor of the parent class
using super() with the parameter list.
■ When a class inherits from another class, it has the right to override the inherited
methods
■ In an overridden method, you can call the method of the parent class by writing
super followed by a dot and the name of the parent method (e.g.,
super.method()).
■ A constructor can call another constructor of the same class using this() with the
parameters of the constructor.
31
SUMMARY: ACCESSIBILITY
Abstract:
Final:
Static:
● Static members of a class belong to the class and are shared by all its objects.
● Static members are accessible by directly using the name of the class.
● Static members can be accessed without needing to create an instance of the class that
contains them.
● Static members are also accessible via instances of the class that contains them. 32
SUMMARY: ACCESSIBILITY
■ protected:
■ public:
33
TO DO
34
ACCOUNT.JAVA
PACKAGE JOB; // Getters and
Setters public int
public abstract class
getCode() { return
Account { code;
private int code; }
protected float balance; public float getBalance() {
private static int nbAccounts; return balance;
}
public Account(float s){ public static int getNbComptes()
{
code=++nbAccounts;
return nbAccounts;
this.balance=s; }
} }
public void withdraw(float mt){
if(mt<balance)balance-=mt;
}
public void deposit(float mt){
balance+=mt;
}
public String toString(){
return("Code="+code+"
Balance="+balance);
}
35
SIMPLEACCOUNT.JAVA
PACKAGE JOB; //Getters And Setters
public float getOverdraft() {
public final class SimpleAccount return Overdraft;
extends Account { }
private float Overdraft; public void setOverdraft( float
Overdraft) {
// Builders this.Overdraft = Overdraft;
public SimpleAccount( float s,float }
d){ }
super(s);
this.Overdraft=d
;
}
public SimpleAccount(){
super();
}
public void withdraw(float mt) {
if(balance+Overdraft>mt)
balance-=mt;
}
public String toString() {
return"Simple Account
"+super.toString()+
"Balance=" +balance;
}
36
SAVINGSACCOUNT.JAVA
PACKAGE JOB;
// Getters and Setters
public float getRate()
public class Savings Account extends { return rate;
Account { }
private float rate; public void setRate(float rate)
//Builders {
this.rate = rate;
public SavingsAccount() { }
this(0.6); }
}
38
APPLICATION TESTCOMPTE.JAVA
package test;
// Test of PaidAccount
import job.*; PaidAccount c3= new
PaidAccount(5000);
public class TestAccount { System.out.println(c3);
public static void main(String[] args) { c3.deposit(6000);
c3.remove(4000);
// TestthereclassAccountSimple
System.out.println(c3);
SimpleAccount
}
c1=newSimpleAccount(8000,4000);
}
System.out.println(c1.toString());
c1.deposit(3000);
c1.remove(5000);
c1.setOverdraft(5500);
System.out.println(c1.toString())
;
// Test the classAccountSavings
SavingsAccount
c2=newSavingsAccount(50000.5);
System.out.println(c2.toString());
c2.deposit(30000);
c2.remove(6000);
c2.calculInterets();
System.out.println(c2.toString())
;c2.setRate(6);
39
c2.calculInterets();
System.out.println(c2);
POLYMORPHISM
40
POLYMORPHISM
41
POLYMORPHISM
+ 5 (fruits) oranges
= 8 fruits
Fruit
weight:int
Fruit()
display():void
Apple Orange
43
INSTANTIATION AND LEGACY
public abstract class Fruit{ public class Orange extends Fruit
int weight; { public Orange(int p){
public Fruit(){ weight=p;
System.out.println("Creation of a System.out.println("creation of an
fruit"); Orange of"+weight+" grams ");
} }
public void display(){ public void display(){
System.out.println("It is A fruit"); System.out.println("It's an
} Orange");
} }
public void displayWeight(){
public class Apple extends Fruit{ System.out.println("the weight of
public Apple(int p){ the Orange is:"+weight+" grams");
weight=p; }
System.out.println("creation of an apple }
of "+weight+" grams ");
}
public void display(){ public class Polymorphism{
System.out.println("It is a apple"); public static void main(String[] args){
} Apple p=new Apple(72);
public void displayWeight(){ Orange o=new Orange(80);
System.out.println("The weight of the }
apple is:"+weight+" grams"); }
}
} 44
INSTANTIATION AND
LEGACY
■ The result
Creation of a fruit
Creation of a 72 gram apple
Creation of a fruit
creation of an orange of 80grams
45
OVERCASTING OF
THE OBJECTS
47
DOWNCASTING OF
OBJECTS
}
} 48
■ This statement indicates that the object f1, of type Fruit, is cast to Apple, and then
the displayWeight() method of the Apple object is called, which is correct.
49
LATE BINDING
■ In most programming languages, when the compiler encounters a method call, it must be able to
determine exactly which method is being referred to. The link between the call and the method is
established at compile time. This technique is called early binding.
■ Java uses this technique for calls to methods declared as final. The advantage of early binding is
that it allows for certain optimizations.
■ On the other hand, for methods that are not final, Java uses the technique of late binding. In
this case, the compiler does not establish the link between the call and the method until runtime.
This link is established with the most specific version of the method.
■ In our case, the method display() has three versions defined in the Fruit, Apple, and Orange
classes. Thanks to late binding, Java is able to determine, at runtime, which version of the
method will be called, which we can verify with the following program:
50
LATE BINDING
public class Polymorphism4{
public static void main(String[] args){
Fruit f1;
Fruit f2;
f1=new Apple(60);
f2=new Orange(40);
f1.display();
f2.display();
}
}
This program gives :
Creation of a fruit
Creation of a apple of 60 grams
Creation of a fruit
Creation of a orange of 40 grams
It is an apple
It is an Orange
51
The decision regarding which method to call is made at runtime based on the actual type of the object,
rather than the declared type of the reference.
ARRAYS AND
COLLECTIONS
52
PRIMITIVE ARRAYS
List 5 0
12 1
23 2
3
4
5
■ Primitive Arrays 6
■ Declaration : 7
8
❑ Example : Array of integers 9
■ int[]list; 10
■ A list is a handle intended to point to an array of integers
■ Array creation
❑ list = new int[11];
■ Handling of the elements from the array:
❑ list[0]=5; list[1]=12; list[3]=23;
❑ for(int i=0;i<list.length;i++){
System.out.println(list[i]);
53
}
theFruits
ARRAY OF OBJECTS
0
■ Statement : Apple 1
❑ Example : Array of objects Fruit weight=60 2
❑ Fruit[] theFruits; displayWeight() 3
4
■ Creation of the array
:Orange
❑ theFruits = new Fruit[5];
weight=60
■ Creation of the objects:
❑ theFruits[0]=new Apple(60); displayWeight()
❑ theFruits[1]=new Orange(100);
:Apple
❑ theFruits[2]=new Apple(55);
weight=60
■ Handling objects:
displayWeight()
for(int i=0;i<lesFruits.length;i++){
lesFruits[i].display();
if(theFruits[i] instanceOf Apple)
((Apple)Fruits[i]).displayWeight(); else
((Orange)Fruits[i]).displayWeight();
} 54
● ArrayList
● Vector
● Iterator
● HashMap
● Etc...
In this part of the course, we will only focus on how to use the collections: ArrayList, 55
Vector, Iterator, and HashMap.
COLLECTION
ARRAYLIST
■ ArrayList is a class from the java.util package that implements the List
interface.
■ Declaration of a collection of type List that should store objects of type
Fruit:
❑ List<Fruit> fruits;
■ Creation of there list:
❑ fruits=new ArrayList<Fruit>();
■ Add two objects of kind Fruit to the list:
❑fruits.add(new Apple(30));
❑ fruits.add(new Orange(25));
■ Calling the display() method on all objects in the list:
❑ Using the traditional for loop:
for(inti=0;i<fruits.size();i++){
fruits.get(i).display();
}
❑ Using the for-each loop
for(Fruit f:fruits)
f.display(); 56
■ Delete the second Object of there list
❑ fruits.remove(1);
EXAMPLE OF USE OF ARRAYLIST
import java.util.ArrayList;
import java.util.List;
public class App1 {
public static void main(String[] args) {
// Declaration of a list of type fruit
List<Fruit> fruits;
// Creation of the list
fruits=new ArrayList<Fruit>();
// Adding 3 objects Apple, Orange and Apple to the list
fruits.add(new Apple(30));
fruits.add(new Orange(25));
fruits.add(new Apple(60));
// Iterate through all the objects.
for(int i=0;i<fruits.size();i++){
// call the display method on each Fruit in the list
fruits.get(i).display();
}
for(Fruit f:fruits)
f.display();
57
COLLECTION
VECTOR
■ Vector is a class from the java.util package that works like ArrayList.
Declaration of a Vector that should store objects of type Fruit:
❑ Vector<Fruit> fruits;
■ Creation of there vector:
❑ fruits=new Vector<Fruit>();
■ Add two objects of type Fruit to the vector:
❑ fruits.add(new Apple(30));
❑ fruits.add(new Orange(25));
■ Calling the display() method on all objects in the list:
❑ Using the traditional for loop:
for(inti=0;i<fruits.size();i++){
fruits.get(i).display();
}
❑ Using the for-each loop
for(Fruit f:fruits)
f.display();
■ Delete the second Object of there list
❑ fruits.remove(1); 58
EXAMPLE OF USE OF VECTOR
import java.util.Vector;
public class App2 {
public static void main(String[] args) {
//Declaration of the vector
Vector<Fruit> fruits;
//Creation of vector
fruits= new Vector <Fruit>();
// Adding 3 objects Apple, Orange and Apple to the vector
fruits.add(new Apple(30));
fruits.add(newOrange(25));
fruits.add(new Apple(60));
//Iterate through all the objects.
for(int i=0;i<fruits.size();i++){
// call the display method on each Fruit in the vector
fruits.get(i).display();
}
for(Fruit f:fruits)
f.display();
}
59
}
COLLECTION OF KIND
ITERATOR
■ The Iterator collection from the java.util package is often used to display the
objects of another collection. In fact, it is possible to obtain an iterator from
any collection.
■ Example :
❑ Creation of a vector of Fruit.
Vector<Fruit> fruits=new Vector<Fruit>();
❑ Add fruits to to vector
fruits.add(new Apple(30));
fruits.add(new Orange(25));
fruits.add(new Apple(60));
❑ Creation of a Iterator from this vector
Iterator<Fruit> it=fruits.iterator();
❑ Browse the Iterator:
while(it.HasNext()){
Fruit f=it.next();
f.display();
}
■ Note that after traversing an iterator, it becomes empty.
60
COLLECTION OF KIND
HASHMAP
■ The HashMap collection is a class that implements the Map interface. This
collection allows you to create a dynamic array of objects of type Object that
are identified by a key.
■ Declaration and creation of a HashMap collection that contains fruits
identified by a key of type String:
❑ Map<String, Fruit> fruits=new HashMap<String, Fruit>();
■ Add two objects of kind Fruit: fruits
:Apple
key value
❑ fruits.put("p1", new Apple(40)); p1
❑ fruits.put("o1", new Orange(60)); o1
:Orange
■ To retrieve an object having For key "p1"
❑ Fruit f=fruits.get("p1");
❑ f.display();
■ Browse all the collection:
Iterator<String> it=fruits.keySet().iterator();
while(it.hasNext()){
String key=it.next();
Fruit ff=fruits.get(key);
System.out.println(key); 61
ff.display();
}