Inheritance II and Midterm Review (Discussion 5) (Kế thừa trong lập trình hướng đối tượng) - Christine Zhou

UN
Uni24h
0 lượt tải
9
0

Nội dung tài liệu

Trang 2

Agenda - Announcements - Inheritance Practice - 4. Midterm Review on Worksheet - 2. Reduce on Worksheet

Trang 3

Announcements - Field hiding is in scope! Same as static lookup - Sorry for the mix-up. We’ll go over this today - Midterm is tomorrow 8-10PM. Room assignments on Piazza - Go to right rooms! - Best of luck! - HW3 is due Friday 11:59PM - Get started on the project! - Discussion survey: tinyurl.com/disc5cz

Trang 4

Inheritance Rules - For non-static methods: - During compilation: If static type has the method, it compiles. Otherwise check parent, parent… Compile time error if no more parent and still haven’t found the method. - During runtime: Run the method in the dynamic type. Otherwise check parent, parent... - For static method: - During compilation: Same as non-static - During runtime: Run the method found during compilation (don’t look at the dynamic type!) - Always look at the dynamic type when running methods, unless the method is static! - For fields: - Use same procedures as static method lookup - Look in the static type for the field and use the field that you eventually find

Trang 5

Field Hiding - If you have a variable of the same name in the static and dynamic type, then this is called “field hiding/shadowing”. It’s possible for the field in the static type to “hide/shadow” the field in the dynamic type. - Field hiding is not good practice!

Trang 6

Example public class Animal { public class Dog extends Animal public class Runner { public String x = “Animal”; { public static void main(String[] args) public String x = “Dog”; { public static void staticM() { Animal a = new Dog(); System.out.println(“A static”); public static void staticM() { System.out.println(a.x); } System.out.println(“D static”); a.nonStaticM(); } a.staticM(); public void nonStaticM() { System.out.println(“A public void nonStaticM() { Animal.m1(a); nonStatic”); System.out.println(“D } } nonStatic”); } public static void m1(Animal a) { } System.out.println(“A m1”); a.nonStaticM(); } } }

Trang 9

Reduce Write a method reduce, which uses a BinaryFunction interface to accumulate the values of a List of integers into a single value. BinaryFunction can operate (through the apply method) on two integer arguments and return a single integer. Write two classes Adder and Multiplier that implement BinaryFunction. Then, fill in reduce and main, and define types for add and mult in the space provided.

Hiển thị 9 trang đầu. Tải tài liệu để xem đầy đủ.

Bình luận (0)

Đăng nhập để tham gia bình luận

Chưa có bình luận nào. Hãy là người đầu tiên!