Java - Upcasting Vs Polymorphism

时间:2018-02-12 13:42:43

标签: java

我是Java的新手。当我探索Java概念时,我遇到了这些问题。 Upcasting and Polymorphism是否相同?我对这两个术语感到困惑。

interface IWebdriver{
void closeBrowser()
}

Public class ChromeDriver implements IWebdriver{

public void closeBrowser(){
//Implementation
}
}

Public class FirefoxDriver implements IWebdriver{

public void closeBrowser(){
//Implementation
}
}

Public class InternetExplorerDriver implements IWebdriver{

public void closeBrowser(){
//Implementation
}
}

Main(){
IWebdriver driver;

driver = new ChromeDriver(); // Polymorphism or Upcasting ??
driver = new FirefoxDriver(); // Polymorphism or Upcasting ??
driver = new InternetExplorerDriver(); Polymorphism or Upcasting ??

}

driver = new ChromeDriver();// Polymorphism or Upcasting ??

slash command - 多态性意味着不止一种形式,同一对象执行不同的操作

Polymorphism - 自动类型转换

有人可以解释一下我的区别吗?

1 个答案:

答案 0 :(得分:1)

术语Casting指的是表达式,其中某种类型的对象被分配给其他的变量。

以下是隐式转换,

IWebdriver driver;

driver = new ChromeDriver(); // implicit cast
driver = new FirefoxDriver(); // implicit cast
driver = new InternetExplorerDriver(); // implicit cast

而下面的是明确的施法,

IWebdriver driver;
... // some operations here
ChromeDriver chromeDriver = (ChromeDriver) driver; // explicit cast

术语Polymorphism是指变量内对象的行为

例如,

IWebdriver driver;

if(case ==1) 
    driver = new ChromeDriver();
else 
    driver = new FireFoxDriver();

driver.closeBrowser(); // this call's behavior changes according to what object is assigned to the variable 'driver' and call that object's closeBrowser() behavior