+ - 0:00:00
Notes for current slide
Notes for next slide

Classes abstractes i interfícies

Mateu Yábar Valles

1 / 18

Llicència

Pots copiar i redistribuir aquest material seguint la llicència Attribution-NonCommercial-ShareAlike 4.0 International CC BY-NC-SA 4.0, indicant-ne autors originals, l'origen (aquesta web), sense fins comercials i mantenint-ne aquesta la llicència

Autors:

2 / 18

Classe abstracte

  • En una relació d'herència entre classes, per tal d'evitar que una classe generalitzadora pugui ser instanciada direm que és una classe abstracte
  • És una classe que No es pot instanciar
abstract class ClasseAbstracte{
val atribut: Int = 0
abstract val atributAbstracte: Int
abstract fun metodeAbstracte()
fun metodeNoAbstracte() {
// Implementació TODO
}
}
3 / 18

Subclasse d'una classe abstracte

  • Les classes (no abstractes) que deriven d'una classe abstracte han d'implementar tots els mètodes abtractes de la classe pare.
  • Fent ús de la paraula clau override

    class Subclase : ClaseAbstracta() {
    override val atributAbstracte: Int = 10
    override fun metodeAbstracte() {
    println(atributAbstracte)
    }
    }
  • Les classes abstractes permeten l'herència sense ser open
4 / 18

Exemple 1

abstract sealed class Figure(val color: Color){
abstract fun paint()
// ...
}
abstract sealed class SomeClass{
abstract val name: String
}
5 / 18

Exemple 2

abstract class Attack {
val baseDamage: Int = 10
abstract fun execute(): String
}
class Headbutt : Attack() {
override fun execute(): String {
return "Cop de cap! ${baseDamage + 1}"
}
}
class Kick : Attack() {
override fun execute(): String {
return "Patada! ${baseDamage + 2}"
}
}
class Fireball : Attack() {
override fun execute(): String {
return "Bola de foc! ${baseDamage + 3}"
}
}
6 / 18

Data classes i herència

abstract class Resource {
abstract var id: Long
abstract var location: String
}
data class Book (
override var id: Long = 0,
override var location: String = "",
var isbn: String
) : Resource()
7 / 18

Interfície

  • Permeten que diferents classes no relacionades puguin tenir el mateix comportament.
  • Són com contractes que especifiquen les operacions, però no les implementen. Les classes que implementen una interfície en defineixen les operacions.
  • keywords:
    • interface - enlloc de classe
    • override - per implementar els atributs i mètodes abstractes
8 / 18

Exemple

  • Interfície
    • List
      val list1 : List<String> = ArrayList<String>()
      val list2 : List<String> = LinkedList<String>()
9 / 18

Interfície

interface Interficie1 {
val atributAbstracte : Int
val atribut : Boolean get() = p1 > 0
fun metodeAbstracte()
fun metode() { print("Mètode implementat")}
}
class Exemple : Interficie1, Interficie2 {
override val atributAbstracte: Int = 0
override fun metodeAbstracte() {
print("mètode de la interfície sobreescrit!")
}
}
10 / 18

Exemple 1

interface BcnTreeDataSource {
fun listTrees(): List<BcnTree>
}
class LocalBcnTreeDataSource():BcnTreeDataSource{
override fun listTrees(): List<BcnTree> {
TODO("Implement: Obtains trees from file")
}
}
class APIBcnTreeDataSource():BcnTreeDataSource{
override fun listTrees(): List<BcnTree> {
TODO("Implement: Obtains trees from url")
}
}
11 / 18

Exemple - ús

fun main(){
val USE_API = true
val bcnTreeDataSource : BcnTreeDataSource = if(USE_API) APIBcnTreeDataSource() else LocalBcnTreeDataSource()
val trees = bcnTreeDataSource.listTrees()
println(trees.count())
}
12 / 18

Exemple 2

interface Volador {
fun enlairar()
fun volar()
}
interface Carregador{
fun carregarPassatgers(passatger:Person)
fun carregarEquipatge(equipatge:Equipatge)
}
class Avio : Volador, Carregador {
override fun enlairar() { println("Cap amunt!") }
override fun volar() { TODO("Not yet implemented") }
override fun carregarPassatgers(passatger: Person) { TODO("Not yet implemented") }
override fun carregarEquipatge(equipatge: Equipatge) { TODO("Not yet implemented") }
}
class Anec (var race : String) : Volador{ // TODO}
class Person (var name : String, var age : Int): Carregador { //TODO}
13 / 18

Interfície comparable

  • comparable
  • Defineix classes que es poden comparar
    • Permet definir algoritmes d'ordenació genèrics
public interface Comparable<in T> {
public operator fun compareTo(other: T): Int
}
class MyModel : Comparable<MyModel>{
override fun compareTo(other: MyModel): Int { //TODO}
}
fun main(){
List<MyModel> list = mutableListof<MyModel>();
list.sort();
}
14 / 18

Exemple 1

data class BcnTree(val name : String) : Comparable<BcnTree>{
override fun compareTo(other: BcnTree) = name.compareTo(other.name)
}
list.sort()
15 / 18

Rectangle implementa Comparable

data class Rectangle(var length: Int, var width: Int) : Comparable<Rectangle> {
val area get() = length * width
override fun compareTo(other: Rectangle): Int {
var bigger = 0
if (this.area > other.area) bigger = 1
else if (this.area < other.area) bigger = -1
return bigger
}
}
fun main() {
var list = mutableListOf<Rectangle>(Rectangle(23, 4), Rectangle(3, 5), Rectangle(23, 4))
println(list.sort())
}
/* [Rectangle(length=3, width=5), Rectangle(length=23, width=4), Rectangle(length=23, width=4)] */
16 / 18

Functional SAM Interfaces

  • Una interficie que només té un mètode abstracte és una functional interface, o Single Abstract Method (SAM) interface.
public expect fun interface Comparator<T> {
public fun compare(a: T, b: T): Int
}
fun <T> MutableList<T>.sortWith(comparator: Comparator<in T>)
fun main() {
var values = mutableListOf<Rectangle>(Rectangle(23, 4), Rectangle(3, 5), Rectangle(23, 4))
values.sortWith(object : Comparator<Rectangle> {
override fun compare(x: Rectangle, y: Rectangle) = x.width - y.width
})
values.sortWith{a,b -> a.width - b.width}
}
17 / 18

Llicència

Pots copiar i redistribuir aquest material seguint la llicència Attribution-NonCommercial-ShareAlike 4.0 International CC BY-NC-SA 4.0, indicant-ne autors originals, l'origen (aquesta web), sense fins comercials i mantenint-ne aquesta la llicència

Autors:

2 / 18
Paused

Help

Keyboard shortcuts

, , Pg Up, k Go to previous slide
, , Pg Dn, Space, j Go to next slide
Home Go to first slide
End Go to last slide
Number + Return Go to specific slide
b / m / f Toggle blackout / mirrored / fullscreen mode
c Clone slideshow
p Toggle presenter mode
t Restart the presentation timer
?, h Toggle this help
Esc Back to slideshow