- Java 11 and 12:New Features
- Mala Gupta
- 382字
- 2021-07-02 12:26:59
Type inference with derived classes
In JDK 9 and other previous versions, you could define a variable of the base class and assign an instance of its derived class to it. The members that you could access using the variable were limited to the ones that were defined in the base class. This is no longer the case with var, since the type of the variable is inferred by using the specific type of the instance that is assigned to it.
Imagine a class Child extends a class Parent. When you create a local variable and assign it an instance of the Child class, the type of the variable is inferred as Child. This looks simple. The following is an example:
class Parent { void whistle() { System.out.println("Parent-Whistle"); } } class Child extends Parent { void whistle() { System.out.println("Child-Whistle"); } void stand() { System.out.println("Child-stand"); } } class Test{ public static void main(String[] args) { var obj = new Child(); obj.whistle(); obj.stand(); // type of obj inferred as Child } }
What happens if you assign the value of the obj variable using a method that can return an instance of the Child class or Parent classes? Here's the modified code:
class Parent { void whistle() { System.out.println("Parent-Whistle"); } } class Child extends Parent { void whistle() { System.out.println("Child-Whistle"); } void stand() { System.out.println("Child-stand"); } } class Test{ public static Parent getObject(String type) { if (type.equals("Parent")) return new Parent(); else return new Child(); } public static void main(String[] args) { var obj = getObject("Child"); obj.whistle(); obj.stand(); // This line doesn't compile } }
In the preceding code, the type of the instance returned by the getObject() method can't be determined before the code execution. During compilation, the type of the obj variable is inferred as Parent, the return type of the getObject() method. Since the Parent class doesn't define stand(), the main() methods fail to compile.
- 程序員面試筆試寶典(第3版)
- Vue.js設(shè)計(jì)與實(shí)現(xiàn)
- C++程序設(shè)計(jì)(第3版)
- CMDB分步構(gòu)建指南
- Python數(shù)據(jù)分析入門(mén)與實(shí)戰(zhàn)
- 匯編語(yǔ)言編程基礎(chǔ):基于LoongArch
- 軟件測(cè)試教程
- Unity 5.X從入門(mén)到精通
- 官方 Scratch 3.0 編程趣味卡:讓孩子們愛(ài)上編程(全彩)
- Java EE 8 and Angular
- Android編程權(quán)威指南(第4版)
- Microsoft XNA 4.0 Game Development Cookbook
- AI輔助編程Python實(shí)戰(zhàn):基于GitHub Copilot和ChatGPT
- 面向物聯(lián)網(wǎng)的Android應(yīng)用開(kāi)發(fā)與實(shí)踐
- 計(jì)算機(jī)輔助設(shè)計(jì)與繪圖技術(shù)(AutoCAD 2014教程)(第三版)