0% found this document useful (0 votes)
24 views61 pages

Chap III Heritage Et Polymorphisme

Uploaded by

GAMER X
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views61 pages

Chap III Heritage Et Polymorphisme

Uploaded by

GAMER X
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 61

DESIGN AND PROGRAMMING ORIENTED OBJECT

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.

■ A static attribute of a class is an attribute that belongs to the


class And shared by all objects of this class.

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.

■ In UML notation, static members of a class are underlined

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 {

public static void main(String[] args) {

Account c1=new Account(5000);Account c2=newAccount(6000);


c1.pour(3000); c1.remove(2000);
System.out.println(c1.toString());

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.

■ Indeed, a class can inherit attributes and methods


from another class.

■ When inheritance can be used, it saves a lot of time


in terms of development and maintenance of appli
7
EXAMPLE OF ISSUE
■ Let's suppose we want to create an application that allows us to manage
different types of bank accounts: simple accounts, savings accounts, and
paid accounts.
■ All types of accounts are characterized by:

❑ A code and a balance.


❑ During the creation of an account, its code is automatically defined
based on the number of accounts created.
❑ An account can undergo deposit and withdrawal operations. For these
two operations, the amount of the transaction must be known.
❑ To consult an account, we can call its method toString().

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.

All types of accounts are characterized by:

● A code and a balance.


● When creating an account, its code is automatically defined based on the number of
accounts created.
● An account can undergo deposit and withdrawal operations. For both of these operations,
the amount of the transaction must be known.
● To consult an account, we can call its toString() method.

9
DIAGRAMME DE
Account
CLASSES -code : int
# balance : float
-nbComptes : int

+ Compte ( )
+ deposit(float mt) : void
+ retirer (float mt) : void
+ toString() : String

SimpleAccount SavingAccount PaidAccount


- overdraft : float - rate : float

+ SimpleAccount (float over) + SavingAccount (float rate) + PaidAccount ( )


+ withdraw (float mt) : void + calculateInterest () : void + deposit (float mt) : void
+ toString() : String + toString() : String + withdraw (float mt) : void
+ toString() : String
10
IMPLEMENTATION JAVA OF THERE
CLASS ACCOUNT
public class Account {

private int code;


protected float balance;
private static int nbAccounts;

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.

To define inheritance in Java, we use the keyword extends:

public class SimpleAccount extends Account {


}

The class SimpleAccount inherits from the class Account, including all
its members except the constructor.

In Java, a class can inherit from only one class

12
Inheritance: EXTENDS
■ If a class does not explicitly inherit from another
class, it implicitly inherits from the class Object.

■ The class Account inherits from the class Object.

■ The class SimpleAccount directly inherits from


the class Account and indirectly from the class
Object.
13
DEFINE THE BUILDER OF THERE CLASS
DERIVATIVE
■ The constructor of the derived class can call the constructor of the
parent class using the keyword super() followed by its parameters.

public class SimpleAccount extends Account{


private float overdraft;
//constructor
public SimpleAccount(float overdraft){

super ();
this. overdraft= overdraft;
}
}

14
Method Overriding

When a class inherits from another class, it can override the inherited
methods.

In our case, the class SimpleAccount inherits the withdraw()


method from the class Account. We need to override this method to
take into account the overdraft limit.

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

● When an instance of a class is created, the parent class is


automatically instantiated, and the object of the parent class is
associated with the created object through the reference
"super" injected by the compiler.

SimpleAccount cs=new SimpleAccount(5000);


● During instantiation, the inheritance between classes is
represented by a composition between an object of the
instantiated class and an object of the parent class that is
created implicitly.

17
OVERLOADING

■ In a class, you can define multiple constructors, each with


a different signature (different parameters). This is called
constructor overloading.
■ You can also overload a method, which means you can
define multiple methods with the same name in the same
class, each having different signatures. The signature of a
method refers to the list of arguments along with their
types.
■ In the SimpleAccount class, for example, you can add
another constructor without parameters. A constructor can
call another constructor of the same class using the
keyword this() with any necessary parameters.
18

OVERLOAD OF CONSTRUCTORS
public class SimpleAccount extends Account {
private float overdraft;
//First builder
public SimpleAccount(float overdraft){
super();
this.overdraft=overdraft;
}
//Second builder
public SimpleAccount(){
this(0);
}
}

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();

public class SimpleAccount extends Compte {


// Members

public void display(){
System.Out.println("balance="+balance+"Overdraft="
+Overdraft);
} 23
}
INTERFACES

■ An interface is a kind of abstract class that contains only abstract


methods.

■ In Java, a class inherits from a single class and can simultaneously


inherit from multiple interfaces.

■ We say that a class implements one or more interfaces.

■ An interface can inherit from multiple interfaces.

■ Example of an interface: 24
INTERFACES
public interface Solvable {
public void solver();
public double getSolde();
}

public class SimpleAccount extends Account implements Solvable {


private float Overdraft;

public void display() {


System.out.println("Balance = " + balance + " Overdraft = " + Overdraft);
}

public double getSolde() {


return balance;
}

public void solver() {


this.balance = 0;
}
}
25
CLASS OF KIND FINAL

■ A final class is a class that cannot be extended. In other


words, it is not possible to inherit from a final class.

■ The class CompteSimple can be declared final by writing:


public final class SimpleAccount extends Account{
private float Overdraft;
public void display() {
System.out.println("Balance="+balance+"
Overdraft="+Overdraft);
}
}
26
VARIABLES AND METHODS FINAL

❑ A final variable is a variable whose value cannot change. In other


words, it is a constant:
Example: final double PI = 3.14;

❑ A final method is a method that cannot be overridden in derived


classes.
Example: The deposit method in the following class cannot be
overridden in derived classes because it is declared as final
❑ public class Account {
private int code;
protected float balance;
private static int nbAccounts;

public final void deposit(float mt){


balance+=mt;
} 27
public void withdraw(float mt){
if(mt<balance)balance-=mt;
}
}
MEMBERS STATIC OF A CLASS

● Members (attributes or methods) of a class are elements that belong to


the class and are shared by all instances of that class.

● Static members are not instantiated when the class is instantiated.

● Static members can be accessed directly by using the name of the class
that contains them.

● Therefore, it is not necessary to create an instance of a class to use its


static members.
28
MEMBERS STATIC OF A CLASS
❑ Static members are also accessible through instances of the class that
contains them.
❑ Example of usage: double d = Math.sqrt(9);
❑ Here, we called the sqrt method of the Math class without creating any
instance. This is possible because the sqrt method is static.
❑ If this method were not static, we would first need to create an object of
the Math class before calling this method:

■ Math m=new Math();


■ double d=m.sqrt(9);

■ 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:

● the same package,


● the derived classes of these classes,
● and classes belonging to the same packages as the derived classes.

Default (Package) Access:


The default access, also known as package access, applies to classes, interfaces, variables,
and methods.
Elements with this access level are accessible to all methods of classes within the same 30
package.


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:

● An abstract class is a class that cannot be instantiated.


● An abstract method is a method that can be defined within an abstract class. It is a method that
does not have a definition, so it must be overridden in derived classes.
● An interface is a type of abstract class that contains only abstract methods.
● In Java, a class always inherits from a single class but can implement multiple interfaces.

Final:

● A final class is a class that cannot be derived from.


● A final method is a method that cannot be overridden in derived classes.
● A final variable is a variable whose value cannot change.
● The final keyword is used for two reasons: security and optimization.

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

❑ Java has of 4 levels of authorizations:


■ private :

■ protected:

■ public:

■ package (Authorisation by default)

33
TO DO

■ Implement the Account class.


■ Implement the SimpleAccount class.
■ Implement the SavingsAccount class.
■ Implement the FeeAccount class.
■ Create an application to test the different
classes.

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); }
}

public Savings Account( float


balance,float rate) {
super(balance);
this.rate=rate;
}
public void
calculateInterests(){
balance=balance*(1+rate/100);
}
public String toString() {
return"Savings Account
"+super.toString()+ " Rate="+rate;
}
37
PAIDACCOUNT.JAVA
PACKAGE JOB;

public class PaidAccount extends Account {


// Builder
public PaidAccount(float balance) {
super(balance);
}
public void deposit(float mt) {
super.deposit(mt);
}
public void withdraw(floatmt) {
super.remove(mt); super.remove(mt*5/100);
}
public String toString() {
return super.toString();
}
}

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

● Polymorphism allows objects to belong to


multiple categories at once.
● Indeed, we were all likely taught in school
that it's impossible to add apples and
oranges. But we can write the following
expression:
3 apples + 5 oranges = 8 fruits

41
POLYMORPHISM

The "over-casting" of objects:


● One way to describe the example of adding apples and oranges
would be to imagine that we say "apples and oranges," but that
we are actually handling them as if they were the same thing.

3 (fruits) apples

+ 5 (fruits) oranges
= 8 fruits

● This way of looking at things implies that apples and oranges


are "transformed" into fruits prior to establishing the problem.
This transformation is called over-casting.
42
INSTANTIATION AND
LEGACY

■ Let us consider this example

Fruit
weight:int
Fruit()
display():void

Apple Orange

Apple(int p) Orange (int p)


display():void display():void
displayWeight() displayWeight()

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

■ We observe that before creating an Apple, the


program creates a Fruit, as shown by the
execution of the constructor of this class. The
same thing happens when we create an Orange.

45
OVERCASTING OF
THE OBJECTS

■ Let us consider the following example:


public class Polymorphism2{
public static void main(String[] args){
// Overcasting implicit Fruit f1=new Orange(40);
🡪You create an object of the class Orange, but you store it in a
reference of type Fruit.

// Overcasting explicit Fruit f2=(Fruit)new Apple(60);


🡪You lose the object's original type during explicit upcasting, but
you can still access it if necessary.

// Overcasting implicit f2=new Orange(40);


}
} 46
UPCASTING OF
OBJECTS
■ An object of type Apple can be assigned to a handle of type
Fruit without any problem:
■ Fruit f1;
■ f1 = new Apple(60);
■ In this case, the Apple object is automatically converted to a
Fruit. We say that the Apple object is upcast to Fruit.
■ In Java, upcasting can be done implicitly. However, we can also
perform upcasting explicitly, even though it is not necessary.
■ Explicit casting is done by specifying the class to which we are
converting the object in parentheses. Example:

47
DOWNCASTING OF
OBJECTS

■ Let us consider the following


example
public class Polymorphisme3{
public static void main(String[]
args){ Fruit f1;
Fruit f2; ■ Erreur de compilation:
f1=new Apple(60); Polymorphisme3.java:5: cannot resolve symbol
f2=new Orange(40); symbol : method displayWeight ()
location: class Fruit
f1.displayWeight(); f1.displayWeight();
^
((Apple)f1).displayWeight(); 1 error

}
} 48

■ Solution : explicit downcasting


DOWNCASTING OF
OBJECTS
■ This message indicates that the object f1, which is of type Fruit, does not have the
method displayWeight(). This is true because this method is defined in the Apple
and Orange classes, not in the Fruit class.
■ In fact, even though the handle f1 points to an Apple object, the compiler does not
consider this assignment, and for it, f1is a Fruit. Therefore, you must explicitly cast
the f1 object, which is of type Fruit, to Apple.
■ This conversion is called downcasting, which refers to the conversion of an object
from a superclass to an object of a derived class.
■ In this case, downcasting must be done explicitly.
■ The compilation error can be avoided by writing the following syntax:
((Apple) f1).displayWeight();

■ 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

■ An array of objects is an array of handles


COLLECTIONS
A collection is a dynamic array of objects of type Object.
A collection provides a set of methods that allow:

● Adding a new object to the array


● Removing an object from the array
● Searching for objects based on criteria
● Sorting the array of objects
● Controlling the objects in the array
● Etc...

In a problem, arrays can be used when the array size is fixed.


In other cases, collections should be used.

Java provides several types of collections:

● 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();
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy