Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android Build a Blog Reader Android App Getting Data from the Web Getting JSON Data from an HTTP Request

Jose Andrade-Sinning
seal-mask
.a{fill-rule:evenodd;}techdegree
Jose Andrade-Sinning
Python Web Development Techdegree Student 12,676 Points

When do I construct using "new" or another object?

http://teamtreehouse.com/library/build-a-blog-reader-android-app/getting-data-from-the-web/getting-json-data-from-an-http-request-2

I'm on the Android Development lesson for Gettiing JSON Data from an HTTP Request and a question came to mind as I'm not able to distinguish between the different way one can construct an object and this is preventing me from getting comfortable with android development.

I noticed that there are a few ways to construct an object:

Case A: When a object is constructed using the keyword new with the same name for the object as the constructor. (This is the most simple one) Case B: where you don't need a constructor because the object is static (Case B). (is this correct?) Case C: The are other times where both the word new is omitted and a method with a different name from the object is used Case D: and lastly, where the word new is used and a different name from the object are used which further complicates the picture for me.

I'm confused with this because I had originally thought there was only one way (case A) to construct an object so I want to know what is the reason behind having different ways of constructing these object.

Here is a snippet from the code that I'm working on where I found a lot of that.

HttpURLConnection connection = (HttpURLConnection) treehouseURL.openConnection(); // case C

InputStream inputStream = connection.getInputStream(); // case C

Reader reader = new InputStreamReader(inputStream); // case D

char[] charArray = new char[10]; // case A

String responseData = new String (charArray); // case A

```java

3 Answers

Ben Jakuben
STAFF
Ben Jakuben
Treehouse Teacher

Great answer by Liam Peters! And a great question. Let's see if we can clear it up a little more.

Case C

InputStream inputStream = new InputStream();
inputStream = connection.getInputStream(); 

The first line creates a new InputStream object and stores it in the inputStream variable.

Line 2 reassigns that variable to a 2nd InputStream object that is created within the getInputStream() method and returned as the result of that method. When the variable is reassigned, the one you created on line 1 is thrown away (and will eventually be collected as garbage).

The reason we wouldn't want to do this is in case InputStream objects take up a lot of memory. It's just twice the memory will be needed for 2 objects. Even though it will eventually be cleaned up automatically, it's inefficient and we want to avoid it.

Case D

The short answer is I probably should have used InputStreamReader instead of Reader to make it more clear. :)

D1: Hopefully we can talk through this in a way that makes sense. Let's revisit this example:

Reader reader = new InputStreamReader(inputStream); // case D

InputStreamReader (the child class) inherits from Reader (the parent class). That means that InputStreamReader is a Reader, just like each of my sons is a Jakuben. Other subclasses are also Readers.

We can assign like this for that reason. InputStreamReader is at least equivalent to Reader, and as you mentioned it does have even more. We only need a Reader later in the code, so any Reader will do.

Now if we try it the other way, we'll have a problem:

InputStreamReader inputStreamReader = new Reader(); // error!

Because InputStreamReader has "more", if we try to use an InputStreamReader method that isn't from the Reader parent, then we will get an exception.

Also, this line would fail because the Reader class is an "abstract" class. Abstract classes are meant to be subclassed, and we always use subclasses of it.

But when is this appropriate?

Because Reader is an abstract class, it defines behaviors that will be consistent among its children. Sometimes we want code that will be accepting of different children. In our blog reader app, perhaps we could read from an InputStreamReader or another subclass, CharArrayReader, which works slightly differently in terms of the "more" things that it does.

We are only calling the read() method from the Reader. So it doesn't matter to our code if read() works on an input stream or an array of chars. Perhaps we would have an if statement earlier in the code that would set the reader variable to either in InputStreamReader or a CharArrayReader based on the choice a user makes.

Let's stop here and pause for understanding and further questions. :)

Glad I didn't confuse you too much!

Ok Jose, this is a really good question.

I'm going to assume that you're comfortable with Case A. - It's the fundamentals of object oriented programming! You create a new object to represent, keep track of, and do work on, some information.

Secondly, Static classes. Case B. This can be confusing until you think of it like this. Static just means that there can only ever be one of these and so using a constructor (new) would be a bit pointless (You don't need to make a new one, because there is only ever one!) Static classes are really useful, because you don't need to pass references to a specific object around your application.

So an example of Case A and Case B working together nicely would be a DVD player and DVD's (Virtual, of course)

An individual DVD would be case A

class DVD{
    //Case A
    private String title;
    private String director;
    private int runtime;

    public DVD(String title, String director, int runtime){
        this.title = title;
        this.director = director;
        this.runtime = runtime;
    }

    public String getDirector(){
        return director;
    }

    public String getTitle(){
        return title;
    }

    public int getRuntime(){
        return runtime;
    }
}

Whereas a DVD player could be static if all it had were methods that do work on a DVD such as

class DVDPlayer{
    // Case B
    public static String DVDtoString(Dvd dvd){
        return dvd.getTitle()+" was directed by " +dvd.getDirector() + " and has a runtime of " + getDurationString(dvd.getRuntime);
    }

    private static String getDurationString(int seconds) {
        int hours = seconds / 3600;
        int minutes = (seconds % 3600) / 60;
        seconds = seconds % 60;
        return twoDigitString(hours) + " : " + twoDigitString(minutes) + " : " + twoDigitString(seconds);
    }

}

Your confusion with Case C is that it's really just a hidden version of Case A. Within connection.getInputStream() there will be a call to instantiate a new Input stream using the new keyword.

Case D is an example of something called Polymorphism. The Java tutorial document on which is actually pretty good.

Hope that isn't all that confusing and I've cleared something up for you!

Jose Andrade-Sinning
seal-mask
.a{fill-rule:evenodd;}techdegree
Jose Andrade-Sinning
Python Web Development Techdegree Student 12,676 Points

Liam,

Thanks for your quick reply, Case A and B make sense now and this is clear to me. Would you please expand on Case C and Case D as this is still not very clear. Let me tell you what I understand and where some of my confusion is.

**Case C questions: **

InputStream inputStream = connection.getInputStream(); // case C

c1. If I was to initialize and construct this object the following way, would that have worked?

InputStream inputStream = new InputStream();
inputStream = connection.getInputStream(); 

c2. This case C sounds to me like a shortcut to construct an object, is this it? or would that throw an error because the system thinks I'm constructing an object twice under the same variable?

**Case D questions: **

Reader reader = new InputStreamReader(inputStream); // case D

Ok, I read the link you provided but unfortunately there they don't have any examples of usage similar to the one I showed here. I now understand more this concept of extending object, but some questions still remain.

D1. Does polymorphism allow us to use the constructor of a child object that extends the parent object to construct the parent object? In other words, what was done in case D was to take an object that extended its own type because it had a constructor that took an InputStream as a parameter. D2. Why then wasn't this initialized this way:

InputStreamReader reader = new InputStreamReader(inputStream); 

Wouldn't the object created out of the child object still have the same methods and attributes as its parent and more?

note: I call parent the main object that is at the root and any other that is created from it using extend I call child. Not sure if this is the right terminology, but I hope you understand.

Is it always case with "get" methods (methods names starting with get) to do the same constructing thing like getInputStream (create automatically new instances)?

No certainly not. In fact most get methods you'll encounter won't accept any arguments at all. getX() or getY() are simply good encapsulated ways to access properties of an object