Skip to main content
3 of 4
removed excessive white-space and other small improvements

Why instantiate an object to a Base class rather than a specific Sub class?

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