-1

I'm a newbie to Java. I came across these questions when I'm exploring the Java concepts. Is the Upcasting and Polymorphism are same? And I'm confused with these two terms.

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 ??

Polymorphism - Polymorphism means more than one form, same object performing different operations

Casting - Automatic type conversion

Could anyone please explain me the difference?

Aishu
  • 1,310
  • 6
  • 28
  • 52
  • No, polymorphism doesn't mean what you say. And java does not have any form of implicit casting. – M. Prokhorov Feb 12 '18 at 13:47
  • @M.Prokhorov - Implicit casting or Upcasting I mean – Aishu Feb 12 '18 at 13:48
  • 1
    java has implicit casting for primitive types, i.e. `int` -> `long` – esin88 Feb 12 '18 at 13:48
  • @esin88 - Java has Implicit casting of class type right. Link provided – Aishu Feb 12 '18 at 13:51
  • 1
    @esin88 - that is actually called "primitive widening conversion" by the JLS. Casting is the name for the syntax. Hence implicit casting is an oxymoron ... per JLS terminology. (Of course most programmers use it anyway ....) – Stephen C Feb 12 '18 at 13:52
  • And if you want the JLS reference: https://docs.oracle.com/javase/specs/jls/se9/html/jls-5.html (All of it!) – Stephen C Feb 12 '18 at 13:54

1 Answers1

1

The term Casting refers to expression where an object of a certain type gets assigned to a variable of other.

The following are implicit casting,

IWebdriver driver;

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

whereas the below one is explicit casting,

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

The term Polymorphism refers to the behavior of the object inside a variable.

For example,

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
Alanpatchi
  • 1,177
  • 10
  • 20