Showing posts with label objects. Show all posts
Showing posts with label objects. Show all posts

Thursday, 22 September 2011

Java: Question + Removing Old Objects

    Let's start off today with a question from the comments! (I'm not sure if you guys generally go back to older posts to check them, and wanted to make sure it got answered for you).
Question: Is Java a multipurpose language; ie GUI's, buttons, ect - what are it's main functions besides interactive http - or correct my noobness - maybe give some insight into its major functions, and why Java over other languages? Such as Perl, ect.
     Java has a billion uses, and yes, it has GUI (Graphic user interface) functionality with buttons and the works, separate frames, what have you. This was more or less the last thing I wanted to get into on the subject of Java though, I wanted to focus more on functionality and understanding objects, classes and their relationships to one another, as well as errors and, to a small degree, memory usage. But it will come!
    For interactive http, you're thinking of JavaScript, this is actually a completely separate language to Java, much more simple, much different syntax. I'll also be in the process of learning this. You can actually use some java applets or something in browsers, but I'll just assume you meant JavaScript, 'cause I don't know anything about applets (yet?).
   
    The main reason to use Java is simply it's power. Object oriented programming is pretty awesome, the use and re-use of certain classes based on context allow for very flexible programs to be made, with few limitations. Compared to some of the other big languages, C and C++ especially, Java holds about the same power with, would you believe it, fewer complexities. The biggest one I can think of right now is pointers. We spoke about these last post, but in C, you actually need to work with the value of the pointer, not just the variable that holds it, and it all gets really messy really quick.
    Another great thing about Java is, since it uses a Virtual Machine (JVM, you might recognize this), it's essentially portable, the program needn't be recompiled to work on each operating system you want it on. AS LONG AS THAT SYSTEM HAS A VIRTUAL MACHINE INSTALLED. This is the primary downside, as far as I can see. Globally usable, but only if you have the (I've been told) bulky JVM on the machine in question. This isn't really a problem in a lot of cases, but still.
    I don't know enough of Perl to comment on why to choose Java over it, unfortunately, but I'm new to everything, so there.

I have adequately answered all your questionsssss

    Onto the actual post! Once an object has outlived its usefulness, there's got to be a way to remove it, to conserve space. If not, then a large program can very easily become overrun with useless information that just bogs it down. An object is considered to be unneeded when there's no variable holding a reference to it, so, when it's unreachable. Luckily, this garbage collection is dealt with by the Java run-time system. So why mention it? Well, garbage collection can happen during the running of the program, but there is no guarantee as to how often this occurs, so an unreachable object could stay in memory for much longer than you might be comfortable with. If your program is small enough, the garbage collection will probably just never occur, but there's not a lot of cases where that'll still be an issue, unless you're running a couple hundred of these small programs at a time.
    A lot f the time, it's possible for an object to be collected without having to worry about it's individual elements/instance variables. If the instance variable references another object, that object will be garbage collected given nothing else refers to it. Yay, chain reactions. But, to allow a programmer some control over object removal, there's a method you can declare in the object's class called "finalize", which is called prior to an objects removal through garbage collection.
    Typically, this method will do all the work required to free resources held by an object that won't be properly managed by the garbage collector. It could be used to close a network connection that would otherwise remain open, or make sure the information in an object is safely written to a file, instead of lost forever. finalize() is an ordinary method in every regard, except for it being automatically called on garbage collection, and as such isn't subject to special rules or regulations like the constructors were.\
Note: use "public void finalize()" as the method signature, or it won't be called!

    Finally, it should be noted that automatic garbage collection does not perform garbage collection or call any finalize methods on termination of the program. While this can't be changed, the ability to ensure everything is properly terminated is important enough to warrant a method to support the behavior. Namely:

System.runFinalize();


....which as you might be able to guess, runs all pending finalize methods. Another useful function you might want is:

System.gc();


...which forces garbage collection to happen right the hell then, instead of having to wait for it. Garbage collection generally makes things a lot easier, since, for the most part, you don't need to worry about details regarding what to delete and when. The penalty we pay for this functionality is a small overhead due to garbage collection taking up system resources, but it's a small price to pay (dun dun duuuun).


That's it for tonight.Questions welcome! Comment, follow, subscribe, share etc, and see you tomorrow!


    And as part of a shameless plug for a friend, if you're interested in classic movies/books/music, visit his site here, and feel free to throw loads of criticism at us. 


















Wednesday, 21 September 2011

Java: Objects & References

    We're now familiar with the idea that (should be) variables act as containers that hold representations of values. Haven't looked into how this principle applies to objects, even though we've been able to use them with no problem. While objects represent actual values, they're not stored inside the variable, but rather, the variable holds a reference. The reference acts as a pointer, or an arrow, telling the program where the object is.
I'm an artist!

    Variables of a class type therefore hold as their representation a reference to the object that's stored elsewhere. We give types to variables to indicate what kind of object they can reference, such as "public int x;" can only reference integers.
    A single object with multiple references to it is said to be shared. This can be a good thing, makes a good program if you can utilize it well, but there is a risk that one part of the program will change a certain part of an object such that it fails in respect to another part of the program. This can be minimized by building the class correctly the first time around to make it hard to misuse etc.

    An important issue for reference variables is that the lifetime of the variable is completely separate to the lifetime of the object it references. So like, even if you're out of scope of some variable that's referencing an object, the object itself still exists.

    Just to recap (because I'm more or less confused at this point.), a primitive-type variable (int, float, char etc) holds a representation of some abstract value, but a variable of some class type (String, ArrayList, what have you) holds a reference (pointer) to the actual object which is stored elsewhere.


I think I earned a short one today, so that's it for tonight. Comment, follow, subscribe, share etc, and see you tomorrow!


    And as part of a shameless plug for a friend, if you're interested in classic movies/books/music, visit his site here, and feel free to throw loads of criticism at us. 

Tuesday, 20 September 2011

Java: Object Initialization

    So yesterday we (I) spoke (typed) about overloading, which is, in  a nutshell, having a bunch of methods with the same name take different parameters, so depending on what a user enters for those parameters, the method called differs to accommodate them. Today, we get to talk about initializing objects!


    We know that the correct initialization of variables is a pretty big deal, and this holds true for object initialization, too. Once created, an object needs to be initialized to a known, valid state. Java already makes sure that all an object's instance variables are initialized, but its the programmer's (your) responsibility to make sure the initial state of the object is actually valid with respect to the intended purpose of that object.


    The creation of a new object is a 2-stage process that's triggered by use of the "new" operator, which we've already seen a bunch. 


1. First, memory needs to be allocated for the object (where does it go, otherwise?). This is taken care of by the Java run-time system, though, so not something you need to worry about.


2. Next, the new object needs to be initialized (I'm getting sick of that word, too, don't worry).  This is where all the instance variables of the object are all set to known values, as well as miscellaneous stuff that needs to be taken care for the object to work, such as opening a file.


    During the second step, there're three potential mechanisms for the programmer to use:


1. Direct Instance Variable Initialization
2. Constructors
3. Instance Initializers


And each one gets their own subsection!


Direct Instance Variable Initialization
    
    Instance variables can be initialized directly, as we're familiar with
Any instance variable declared with an initialization expression is immediately initialized when the new object is created. Simple, but it comes with limitations. Specifically, only a single expression can be used to provide the initial value, and it can't make use of any variables not yet initialized. You can declare an instance variable without it being explicitly initialized, in which care it takes a default value (0 or 0.0 for numerical variables and characters, false for boolean, and for classes, null). As with local variables, explicitly initializing the variable is a good idea, and luckily, direct initialization isn't the only way to do it. An instance variable with no direct initialization can still be explicitly initialized using a constructor.


Constructors


    A constructor is declared within a class as any other method, but has the specific purpose of initializing the state of a new object. Statements in the method body can assign values to instance variables, create other objects and open files, along with any other operation you might need done. When a constructor terminated, the object should be in a valid state and be ready to use.


    Being a special type of method, a constructor is subject to special rules, the biggest being the constructors name is exactly the name of the class, and doesn't have the preceding return-value attached to it. Example time!








    Note an array list is declared, but not initialized, until we get to the constructor.


    Constructors are pretty cool, they can have actual parameters, so you can control how variables are initialized, and they can be overloaded, which is awesome. In this, they're pretty much methods, without the return value (even though they may as well be void). 
Terminology: A constructor that takes no parameters is called a default constructor.


    Calling a constructor is automatic as part of the "new" operator, and every time you call an object with an empty parameter list, the default constructor is called. This wasn't an issue for us before, despite our lacking constructors, but the Java system will create a default constructor (empty bodied) for us if this is the case, quashing the problem.


Instance Initializers


    There are some cases we can come across where we need a statement sequence to get what we need. We could just put this sequence into a constructor, but this could get annoying if you're overloading them and thus need to repeat the code a bunch of times, so Java gave use this mechanism. An instance initializer associates a block of code directly with a single instance variable. The block is just a compound statement and follows directly after the variable declaration. Here, have another example:




    (Yes, you can call classes within themselves, but that's not important, I'm just lazy).  Look at that. Hell, if you wanted to, you could combine this with instance initialization and have a whole mess of stuff you would probably only find useful in a limited scope. Still, it's there, and therefore good to know about.




That was lengthy. My fingers hurt, so that's it for tonight. Comment, follow, subscribe, share etc, and see you tomorrow!


    And as part of a shameless plug for a friend, if you're interested in classic movies/books/music, visit his site here, and feel free to throw loads of criticism at us. 






Thursday, 15 September 2011

Java: The Stack Object & Class

    Continuing from yesterday's post, we need to group all this stuff together, all the methods and variables into 1 unit (the object). This still isn't enough if we need more than 1 stack, how would we separate data between them? Well, we'd need to create a second object. This can be annoying to do, especially if a large number of stacks is required, or the data within the object becomes too cumbersome. So what now? We should probably work with some kind of template! Make everything easier, make everything faster, good times. And that's exactly what a class amounts to. A template.

    So let's look at an outline for a template for stacks, based on yesterday's quick specifications!
    This is very rudimentary, as you can see, but it provides an outline for the class quite nicely. We see what functions still need to be worked on (At this point, all of 'em). Within this class body (each class should ideally be it's own file, due to object oriented yadda yadda), we have the class scope. Public methods and variables can be accessed from outside this scope, such as a case where the class is used as a cog in a larger machine of a program, while private denotes....privacy. Only this class may use the methods and alter variables flagged as such. This is surprisingly useful, when you want to use helper functions to perform a various amount of smaller tasks as part of a larger function, keeping only the umbrella function public. Stuff like that.


    This looks alright, I hope? Well, it isn't, but you should understand what's going on in the actual code at this point. HOWEVER. What happens if we try to look at the top value when there isn't one there? (Hint, the compiler hates you and throws errors at you). Another, seemingly less important task to take care of is the line:

    int size = stack.size();


....which we not only use twice, but never actually use the result, and instead need to subtract from it each time. An easier way to do this is create a helper method, something like, getLastIndex(), but easier to type out. This method would ideally run the above line, then return that value minus 1. This could save time, making both functions that use it 1 line long:


    public void pop() {
        stack.remove( stack.getLast() );
    }


    So let's see if you can create the helper function, and find some way to deal with the potential breaking that happens when you try to pop/top an empty stack. I'll post a quick solution next time and  that's it for tonight. Comment, follow, subscribe, share etc, and see you tomorrow!

    And as part of a shameless plug for a friend, if you're interested in classic movies/books/music, visit his site here, and feel free to throw loads of criticism at us. 

Wednesday, 14 September 2011

Java: Classes and Objects (Intro)

    Classes and objects! We've used these, and you should probably be able to use them on your own (simply using them doesn't take much effort), but now we get to go into a little more detail, yay us. We need this to create our own objects and classes to get our OOP on (that's object oriented programming). 
    Properly done, Java programs of any size should be object oriented, since among this approaches strengths is the ability to design/build programs reliably, allowing for much better support when it comes to maintenance or program expansion. Another huge strength is the ability to reuse classes elsewhere, across wildly varied programs, and even in different parts of a program with little hassle.
    Remember with our I/O code, we had some buffered reader/writers, and FileInput etc? Those were all classes that are available to make coding easier, so you can see how it could be helpful. Why reinvent the wheel?
    Various concepts need to be looked at to understand the whole OOP thing fully, since it's hard to fully get your head around. Among these are abstract data types (ADT), objects, classes and instantiation. So, yeah, that's what we'll be working on.

    An ADT specifies a new data type by defining values that belong to the type as well as the operations that are applicable to that type (methods). An implementation of the type specified by the ADT can be created using variables to provide a representation of the ADT's values, and procedures to implement operations. Using these tools on their own is a pain in the ass though, so it's better when there's actual support for making an ADT, with a compiler that error checks it.

    As an example, we'll be using a stack object. Stacks use a FILO system (That is, first in, last out) to manage accessing it's elements. For a visual representation, just imagine stacking...anything. Plates, CDs, trays. The first item on the stack, that is, on the bottom, will be the last one to leave, being pushed further back in the queue by any new items being stacked on top.
    A stack of data items functions in essentially the same way, so to implement one, we'll probably need several methods! (Planning is good!)

1.    push      - Pushing a value onto the stack is just placing a data item on top
2.    pop        - Popping a value off the stack is the removal of a data item.
3.    get         - A method for returning the value of the item at the top, without actually removing it!
4.    isEmpty - A method to test if the stack has any values left on it. This is so you don't try to pop a value that doesn't exist, causing all kinds of commotion.

    Anything else? I don't think so, but if I'm missing anything, leave a comment. Otherwise, these methods as part of some container class (some data structure we can use) should serve us well. But using variables within the methods we're using is worth nothing, their scope is for the methods only. This means they don't actually exist outside the method. We need something with a global scope, so we can just declare variables outside the methods, but still within the class.

    This has been very wordy today, and I'm tired now, so that's it for tonight. Comment, follow, subscribe, share etc, and see you tomorrow!

    And as part of a shameless plug for a friend, if you're interested in classic movies/books/music, visit his site here, and feel free to throw loads of criticism at us. 
      Also, a bunch of the text is more or less straight from the textbook mentioned in earlier posts since I'm crud at writing.