ADS-Lecture 10 Subtype Polymorphism vs. HoFs

这篇讲座探讨了Java中的动态方法选择谜题,子类型多态和显式高阶函数的概念。讲解了静态方法、变量和继承的关系,以及如何通过实现Comparable接口和使用Comparator来实现多态比较。讨论了子类型多态的优势,例如避免在每个自定义类型中编写特定的比较函数,同时也指出了使用自定义比较接口可能存在的问题,如类型转换和接口未被广泛采用。文章还通过例子展示了如何根据特定比较函数来确定两个对象的大小。
摘要由CSDN通过智能技术生成

Lecture 10 Subtype Polymorphism vs. HoFs

Dynamic Method Selection Puzzle

Suppose we have two classes:

  • Dog: Implements bark() method.

  • ShowDog: Extends Dog, overrides bark method.

Summarizing is-a relationships, we have:

  • Every ShowDog is-a Dog

  • Every Dog is-an Object.

    • All types in Java are a subtype of Object.

The rules:

  • Compiler allows memory box to hold any subtype.

  • Compiler allows calls based on static type.

  • Overridden non-static methods are selected at run time based on dynamic type.

    • Everything else is based on static type, including overloaded methods.
Static Methods, Variables, and Inheritance

You may find questions on old exams, worksheets, etc. that consider:

  • What if a subclass has variables with the same name as a superclass?

  • What if subclass has a static method with the same signature as a superclass method?

    • For static methods, we do not use the term overriding for this.

These two practices above are called “hiding”.

  • It is bad style.

  • There is no good reason to ever do this.

  • The rules for resolving the conflict are a bit confusing to learn.

Subtype Polymorpgism

Subtype Polymorphism

The biggest idea of the next couple of lectures: Subtype Polymorphism

  • Polymorphism: “providing a single interface to entities of different types”

Consider a variable deque of static type a.k.a compile-time type Deque:

  • When you call deque.addFirst(), the actual behavior is based on the dynamic type a.k.a run-time type.

  • Java automatically selects the right behavior using what is sometimes called dynamic method selection.

Subtype Polymorphism vs. Explicit Higher Order Functions

Suppose we want to write a program that prints a string representation of the larger of two objects.

Explicit Hof Approach:

def print_larger(x, y, compare, stringify):
    if compare(x, y):
        return stringify(x)
    return stringify(y)

Subtype Polymorphism Approach:

def print_larger(x, y):
   if x.largerThan(y):
       return x.str()
   return y.str()

Sometimes called a “callback”.

The above two code blocks are written in python, just to make its meaning clearer.

DIY Comparison

Writing a General Max Function

Suppose we want to write a function max() that returns the max of any array, regardless of type.

public static Object max(Object[] items) {
   
  int maxDex = 0;
  for (int i = 0; i < items
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值