0% found this document useful (0 votes)
22 views

Part 3-Support Java 17 Certif - Inheritance and Records

Uploaded by

abdellahlotfi05
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)
22 views

Part 3-Support Java 17 Certif - Inheritance and Records

Uploaded by

abdellahlotfi05
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/ 43

Oracle Java 17 Developer Certification

Collections Arrays, Loops


Records

Modules
Inheritance Exception Handling
Generics
JDBC API
Class, Object Annotations
Interfaces Java Security

Java IO API
Java Concurrency & Multi Threading
Lambda Expressions Java Streams API
Mohamed Youssfi, Enseignant Chercheur ENSET Mohammedia, Université Hassan II de Casablanca Consultant R&D Ingénierie Logicielle
Reuse Parent Class Code through Inheritance
The purpose of inheritance is to reuse generic class behaviors and
state in subclass
• Superclass represents more generic, parent type
• Superclass define common attributes and behaviors
• Subclass represents a more specific, child type and extends the
parent type
• Subclass inherit all attributes and behaviors from their parents
• Subclass may define subtype-specific attributes and behaviors

public class Product {


private int id;
private String name;
public class Food extends Product {
public class Drink extends Product {
private BigDecimal price; private LocalDate bestBefore;
// Other Drink specific methods and variables
private Rating rating;
}
public LocalDate getBestBefore() {
public Rating getRating() { return bestBefore;
return rating; }
} // Other Food specific methods and variables
// Other generic methods and attributes
}
}
Pattern matching for instanceof
• Pattern matching allows common logic in a program, namely the conational extraction of
components from objects, to be expressed more concisely and safely;
Object obj = new String("Hello");
String result="";

• Before Pattern matching for instanceof


if(obj instanceof String){
1. A test : is obj a string
String s = (String)obj; 2. Declaration of new variable s
result = s.toUpperCase();
} 3. Casting of obj to String into variable s
• Using pattern matching for instanceof
• The phrase String s is the type pattern
if (obj instanceof String s){
result = s.toUpperCase(); • The instanceof operator matches the target obj to
} the type pattern as follows :
• if obj instanceof String, then it is cast to
if (obj instanceof String s){ String and the value is assigned to the variable s
String str = s.toUpperCase();
} else {
// s is out of scope here
}
Records
public class Point { Point class @Override
private final int x; public String toString() {
private final int y; return "Point{" +
public Point(final int x, final int y) { "x=" + x +
this.x = x; ", y=" + y +
this.y = y; '}';
} }
@Override
public boolean equals(Object o) { public int x() {
if (this == o) return true; return x;
if (o == null || getClass() != o.getClass()) return false; }
Point point = (Point) o;
return x == point.x && y == point.y; public int y() {
} return y;
}
@Override }
public int hashCode() {
int result = 31 * x; public record Point(int x, int y){ Point Record
int hash = result +y;
return hash; }
}
public record Point(int x, int y){ Point Record
}
Point p1=new Point(10,20); 10, 20
Point p2=new Point(10,20); Point[x=10, y=20]
System.out.println(p1.x()+", "+p1.y());
330
System.out.println(p1.toString());
System.out.println(p1.hashCode()); 330
System.out.println(p2.hashCode()); true
System.out.println(p1.equals(p2));
Constructors for Record classes
• Example of compact canonical • Example of compact canonical
constructor that validates its implicit constructor that normalizes its
parameters formal parameters
public record Range(int lo, int hi) { public record Rational(int num, int den) {
public Range { public Rational{
if(lo>hi){ int gcd = gcd(num,den);
int tmp = lo; num /= gcd;
lo = hi; den /= gcd;
hi=tmp; }
} private int gcd(int a, int b){
} int gcd = 1;
} for(int i=1; i <= a && i <= b; i++)
{
Range range= range = new Range(20,10); if(a% i==0 && b%i==0) • Equivalent to the conventional constructor
System.out.println(range.toString()); gcd = i;
} public record Rational(int num, int den) {
Range[lo=10, hi=20] return gcd; public Rational(int num, int den){
} int gcd = gcd(num,den);
} num /= gcd;
den /= gcd;
this.num = num;
Rational rational=new Rational(12, 16);
this.den = den;
System.out.println(rational.toString()); }
..
Rational[num=3, den=4] }
Practice for Lesson 6 (6.1)
package labs.pm.data;
import java.math.BigDecimal;

public class Drink extends Product {


public Drink(int id, String name, BigDecimal price, Rating rating) {
super(id, name, price, rating);
} Product p1 = new Product(101, "Tea", BigDecimal.valueOf(1.99));
} Product p2 = new Drink(102, "Coffee", BigDecimal.valueOf(1.88), Rating.THREE_STAR);
Product p3 = new Food(103, "Cake", BigDecimal.valueOf(1.12), Rating.TWO_STAR,
package labs.pm.data; LocalDate.now().plusDays(2));
Product p4 = new Product();
import java.math.BigDecimal; Product p5 = p3.applyRating(Rating.FOUR_STAR);
import java.time.LocalDate;
public class Food extends Product { System.out.println(p1);
private LocalDate bestBefore; System.out.println(p2);
System.out.println(p3);
public LocalDate getBestBefore() { System.out.println(p4);
return bestBefore; System.out.println(p5);
}
public Food(int id, String name, BigDecimal price, Rating rating, LocalDate bestBefore) { labs.pm.data.Product@5caf905d
super(id, name, price, rating); labs.pm.data.Drink@27716f4
this.bestBefore = bestBefore; labs.pm.data.Food@8efb846
} labs.pm.data.Product@2a84aee7
} labs.pm.data.Product@a09ee92
Practice for Lesson 6 (6.2)

@Override In Product Class @Override In Food Class


public String toString() { public String toString() {
return this.getClass().getSimpleName()+"{" + return super.toString()+", { bestBefore="+bestBefore+"}";
"id=" + id +
}
", name='" + name + '\'' +
", price=" + price +
", rating=" + rating.getStars() +
'}';
}

Product p1 = new Product(101, "Tea", BigDecimal.valueOf(1.99));


Product p2 = new Drink(102, "Coffee", BigDecimal.valueOf(1.88), Rating.THREE_STAR);
Product p3 = new Food(103, "Cake", BigDecimal.valueOf(1.12), Rating.TWO_STAR,
LocalDate.now().plusDays(2));
Product p4 = new Product();
Product p5 = p3.applyRating(Rating.FOUR_STAR);

System.out.println(p1);
System.out.println(p2); Product{id=101, name='Tea', price=1.99, rating=☆☆☆☆☆}
System.out.println(p3); Drink{id=102, name='Coffee', price=1.88, rating=★★★☆☆}
System.out.println(p4); Food{id=103, name='Cake', price=1.12, rating=★★☆☆☆}, { bestBefore=2023-09-13}
System.out.println(p5); Product{id=0, name='no name', price=0, rating=☆☆☆☆☆}
Product{id=103, name='Cake', price=1.12, rating=★★★★☆}
Practice for Lesson 6 (6.3)

Product p6 = new Drink(102, "Chocolate", BigDecimal.valueOf(1.88),


Rating.THREE_STAR);
Product p7 = new Food(103, "Chocolate", BigDecimal.valueOf(1.12), Rating.TWO_STAR,
LocalDate.now().plusDays(2));
System.out.println(p6.equals(p7));

false
Product p6 = new Drink(102, "Chocolate", BigDecimal.valueOf(1.88),
Rating.THREE_STAR);
@Override In Product Class Product p7 = new Food(102, "Chocolate", BigDecimal.valueOf(1.88),
public boolean equals(Object o) { Rating.TWO_STAR, LocalDate.now().plusDays(2));
if (this == o) return true; Product p8 = new Food(102, "Chocolate", BigDecimal.valueOf(1.88),
if (o == null || getClass() != o.getClass()) return false; Rating.TWO_STAR, LocalDate.now().plusDays(2));
Product product = (Product) o; System.out.println(p6.equals(p7));
return id == product.id && Objects.equals(name, product.name); System.out.println(p7.equals(p8));
}
false
true
@Override
public int hashCode() {
return Objects.hash(id, name);
}

false
Practice for Lesson 6 (6.3) : public class Drink extends Product {
//
public abstract class Product { @Override
public abstract Product applyRating(Rating newRating); public Product applyRating(Rating newRating) {
public LocalDate getBestBefore() { return new Drink(getId(), getName(), getPrice(), newRating);
return LocalDate.now(); }
} //
@Override }
public String toString() {
return this.getClass().getSimpleName()+"{" + public class Food extends Product {
id + " " + name + " " + price + @Override
" " + rating.getStars() + public BigDecimal getDiscount() {
" "+getBestBefore()+ LocalTime now = LocalTime.now();
'}’; return (now.isAfter(LocalTime.of(17,30)) && now.isBefore(LocalTime.of(18,30)))
} ? super.getDiscount() : BigDecimal.ZERO;
} }
@Override
public Product applyRating(Rating newRating) {
return new Food(getId(), getName(), getPrice(), newRating, bestBefore );
}
// @Override
// public String toString() {
// return super.toString()+", { bestBefore="+bestBefore+"}";
// }
}
Practice for Lesson 6 (6.3) :

Product p1 = new Drink(102, "Coffee", BigDecimal.valueOf(1.88), Rating.THREE_STAR);


Product p2 = new Food(103, "Cake", BigDecimal.valueOf(1.12), Rating.TWO_STAR, LocalDate.now().plusDays(2));
System.out.println(p1.toString());
System.out.println(p2.toString());
System.out.println("-----------");
Product p3 = p2.applyRating(Rating.FIVE_STAR);
System.out.println(p3.toString());
System.out.println("Discount="+p3.getDiscount());
if(p3 instanceof Food){
System.out.println("Best Before = "+((Food) p3).getBestBefore());
}
System.out.println("Best Before = "+p3.getBestBefore());

Drink{102 Coffee 1.88 ★★★☆☆ 2023-09-11}


Food{103 Cake 1.12 ★★☆☆☆ 2023-09-13}
-----------
Food{103 Cake 1.12 ★★★★★ 2023-09-13}
Discount=0
Best Before = 2023-09-13
Best Before = 2023-09-13
Practice for Lesson 6 (6.4) :
package labs.pm.data;
import java.math.BigDecimal;
import java.time.LocalDate;
public class ProductManager {
public Product createProduct(int id, String name, BigDecimal price, Rating rating, LocalDate bestFefore){
return new Food(id, name, price, rating, bestFefore);
}
public Product createProduct(int id, String name, BigDecimal price, Rating rating){
return new Drink(id, name, price, rating);
}
// Package restriction access
}
Product(int id, String name, BigDecimal price, Rating rating) {
this.id = id;
this.name = name;
// Package restriction access this.price = price;
Drink(int id, String name, BigDecimal price, Rating rating) { this.rating = rating;
super(id, name, price, rating); }
} /*
Product(int id, String name, BigDecimal price) {
// Package restriction access this(id,name,price, Rating.NOT_RATED);
Food(int id, String name, BigDecimal price, Rating rating, LocalDate }
bestBefore) { Product() {
super(id, name, price, rating); this(0, "no name", BigDecimal.ZERO);
this.bestBefore = bestBefore; }
} */
Practice for Lesson 6 (6.4) :
ProductManager productManager=new ProductManager();
Product p1 = productManager.createProduct(102, "Coffee", BigDecimal.valueOf(1.88),
Rating.THREE_STAR);
Product p2 = productManager.createProduct(103, "Cake", BigDecimal.valueOf(1.12), Rating.TWO_STAR,
LocalDate.now().plusDays(2));
System.out.println(p1.toString());
System.out.println(p2.toString());
System.out.println("-----------");
Product p3 = p2.applyRating(Rating.FIVE_STAR);
System.out.println(p3.toString());
System.out.println("Discount="+p3.getDiscount());
if(p3 instanceof Food){
System.out.println("Best Before = "+((Food) p3).getBestBefore());
}
System.out.println("Best Before = "+p3.getBestBefore());

Drink{102 Coffee 1.88 ★★★☆☆ 2023-09-11}


Food{103 Cake 1.12 ★★☆☆☆ 2023-09-13}
-----------
Food{103 Cake 1.12 ★★★★★ 2023-09-13}
Discount=0
Best Before = 2023-09-13
Best Before = 2023-09-13
Practice for Lesson 6 (6.5) : sealed, permits, dinal

public sealed abstract class Product permits Drink, Food { …. }

public final class Drink extends Product { …. }

public final class Food extends Product { …. }

ProductManager productManager=new ProductManager();


Product p1 = productManager.createProduct(102, "Coffee", BigDecimal.valueOf(1.88), Rating.THREE_STAR);
Product p2 = productManager.createProduct(103, "Cake", BigDecimal.valueOf(1.12), Rating.TWO_STAR, LocalDate.now().plusDays(2));
System.out.println(p1.toString());
System.out.println(p2.toString());
System.out.println("-----------");
Product p3 = p2.applyRating(Rating.FIVE_STAR); Drink{102 Coffee 1.88 ★★★☆☆ 2023-09-11}
System.out.println(p3.toString()); Food{103 Cake 1.12 ★★☆☆☆ 2023-09-13}
System.out.println("Discount="+p3.getDiscount()); -----------
if(p3 instanceof Food){ Food{103 Cake 1.12 ★★★★★ 2023-09-13}
System.out.println("Best Before = "+((Food) p3).getBestBefore()); Discount=0
}
Best Before = 2023-09-13
System.out.println("Best Before = "+p3.getBestBefore());
Best Before = 2023-09-13
Practice for Lesson 6 (6.6) : Sealed classes with Records
package labs.pm.optional;
package labs.pm.optional;
import labs.pm.data.Rating; import labs.pm.data.Rating;
import java.math.BigDecimal;
import java.math.BigDecimal;
public record Drink(int id, String name, BigDecimal import java.time.LocalDate;
price, Rating rating) {
public BigDecimal discount(){ public class RecordExample {
public static void main(String[] args) {
return BigDecimal.ONE; Drink d1 = new Drink(120, "Coffee", BigDecimal.valueOf(1.99), Rating.FIVE_STAR);
} Drink d2 = new Drink(120, "Coffee", BigDecimal.valueOf(1.99), Rating.FIVE_STAR);
} System.out.println("Drink 1 : "+d1);
System.out.println("Drink 1 : "+d2);
package labs.pm.optional; System.out.println("Is Drink 1 equals to Drink 2 :" + d1.equals(d2));
import labs.pm.data.Rating; System.out.println("Is Drink 1 the same object than the Drink 2 :" + (d1==d2));
import java.math.BigDecimal; Food f1 = new Food(320, "Tea", BigDecimal.valueOf(1.88), Rating.FOUR_STAR,
LocalDate.now());
import java.time.LocalDate;
System.out.println("Food 1 :"+f1);
System.out.println(f1.name()+" has discount of "+f1.discount()+" %");
public record Food(int id, String name, BigDecimal
price, Rating rating,LocalDate bestBefore) { }
public BigDecimal discount(){ }
return BigDecimal.TEN; Drink 1 : Drink[id=120, name=Coffee, price=1.99, rating=FIVE_STAR]
} Drink 1 : Drink[id=120, name=Coffee, price=1.99, rating=FIVE_STAR]
} Is Drink 1 equals to Drink 2 :true
Is Drink 1 the same object than the Drink 2 :false
Food 1 :Food[id=320, name=Tea, price=1.88, rating=FOUR_STAR, bestBefore=2023-09-12]
Tea has discount of 10 %
Practice for Lesson 6 (6.6) : Sealed classes with Records
public sealed class Souvenir implements Product permits CollectableItem {
package labs.pm.optional; private int id;
import java.math.BigDecimal; private String name;
public sealed interface Product permits Drink, Food, Souvenir { private BigDecimal price;
BigDecimal discount(); private Rating rating;
String name(); private String size;
}
public Souvenir(int id, String name, BigDecimal price, Rating rating, String size) {
public record Drink(int id, String name, BigDecimal price, Rating this.id = id; this.name = name; this.price = price; this.rating = rating;
rating) implements Product { this.size = size;
}
@Override
@Override
public BigDecimal discount(){ public BigDecimal discount() {
return BigDecimal.ONE; return BigDecimal.TEN;
} }
} @Override
public String name() {
public record Food(int id, String name, BigDecimal price, Rating return this.name;
rating,LocalDate bestBefore) implements Product { }
}
@Override
public BigDecimal discount(){ public non-sealed class CollectableItem extends Souvenir {
return BigDecimal.TEN; public CollectableItem(int id, String name, BigDecimal price, Rating rating, String size) {
} super(id, name, price, rating, size);
} }
}
Practice for Lesson 6 (6.6) : Sealed classes with Records

public class SealedExample {


public static void main(String[] args) {
Product p1 = new CollectableItem(11, "Spacial coffee", BigDecimal.valueOf(1.55), Rating.FIVE_STAR,"Big");
System.out.println(p1.name()+" has discount of : "+p1.discount()+ " %");
Product p2 = new Drink(123,"Tea", BigDecimal.valueOf(1.55),Rating.FIVE_STAR);
System.out.println(p2.name()+" has discount of : "+p2.discount()+ " %");
}
}

Spacial coffee has discount of : 10 %


Tea has discount of : 1 %

You might also like