Skip to main content
4 of 4
edited title
Tulains Córdova
  • 39.6k
  • 13
  • 102
  • 157

Why instantiate an object to a base class rather than a specific subclass?

For example:

URL blogFeedUrl = new URL("http://manishmaharzan.com.np/getJSON/json.json"); HttpURLConnection connection = (HttpURLConnection) blogFeedUrl.openConnection(); connection.connect(); InputStream inputStream = connection.getInputStream(); Reader reader = new InputStreamReader(inputStream); int contentLength = connection.getContentLength(); char[] charArray = new char[contentLength]; reader.read(charArray); String responseData = new String(charArray); 

Here we could have created InputStreamReader instead for parent class Reader:

InputStreamReader reader = new InputStreamReader(inputStream); 

Or for another example when creating a SQLiteOpenHelper in an activity:

public class Helper extends SQLiteOpenHelper { … } public class DrinkActivity extends Activity { protected void onCreate(…) { … } SQLiteOpenHelper helper = new Helper(this); … } 

Instead of referencing the base class SQLiteOpenHelper here, why not create

Helper helper = new Helper(this); 

after all Helper extends SQLiteOpenHelper.

What is the benefit of coding it this way?

mhrzn
  • 235
  • 1
  • 3
  • 8