Showing posts with label cars. Show all posts
Showing posts with label cars. Show all posts

Tuesday, 11 October 2011

Java: Catching Exceptions and the Finally Block

Last post before we move on to the chapter about either more intricate processes (multiple things happening at once, basically) OR we can go right into the GUI material (Graphic User Interfaces, click on buttons to do things etc.). Either way doesn't matter to me, they're both going to get done, but which would you guys like to see first? I'll put up a poll later if I work out how, and I'll spend all of tomorrow either answering questions or bullshitting so you have time to vote on it!

For now, let's get into the material. Catching exceptions, first. Well, we've already done throwing, right, so naturally something needs to catch it. I think we've seen this in the Stack program way earlier, the try-catch block. How this works is, you have a series of statements (the body) that has some chance of triggering an exception throwing, and you stuff that inside a try block, which is just a compound statement preceded by

Monday, 10 October 2011

Java: Representing and Throwing Exceptions

To comments people: Sure I might be able to do all kinds of apps, but I'll look into it more when I like...can.
And no, I don't work as a programmer (yet), I'm barely ahead of what I post, so I still have a way to go :(

Guess how exceptions are represented in Java? Like everything else, pretty much, as objects! This actually allows information about what happened to cause an exception as well as where in the source code it happened, to be transferred easily around a program. A built-in Java class in the libraries contain quite a few exception classes, all of which are subclasses (direct or indirect) of the superclass
Throwable. Most exceptions are a subclass of Exception, itself being a subclass of Throwable (hence the indirect). There is another set of exceptions that you really don't want to come across, and those are of the class Error. These, however, are based more around internal errors, and really really should not happen. If it does, the only way to deal with it tends to be termination of the program.


So what do we do when an exceptional event occurs?

Saturday, 8 October 2011

Java: Exceptions: Kinds of Errors

Whoa, this is late, I overslept like crazy! And yes, I suppose with my new found knowledge I could do android apps Y'know, when I'm done with these last 3 chapters. I'll make a whole segment about it, where you vote for what you want made etc. But that's for the (near?) future, not now! :D

So basically, we're on the chapter dealing with exceptions now, and the basic idea is that an exception is an error, and occurs when shit goes bad. I paraphrase, but its much better to "throw" an exception, that is, to stop a program running when it encounters an error, than just simply leave a message and continue as if nothing went wrong. Primarily, this is because we would, without throwing the exception, be covering up the fact that a problem occurred. Further, without throwing an error, you're more than likely going to be forced to return a valid value that will cause problems elsewhere!

For instance, back to our Stack<Car>. Say we popped a value off the stack, but the stack is empty. Normally, in a fully functional program, we'd have safeguards stopping this from being possible, but then again, ideally, no errors would occur either. So we pop a value off an empty stack, using that value to perform some other piece of functionality. We'd get a "null" returned, most likely.
Now, if the stack was to say, create a setup of Cars, like, you only want 8 cars in a room, you're going to end up with an infinite amount of cars that have no object type. The room will never be created, because, while putting in "null", which is basically nothing, takes basically no time, values are going to keep popping off this empty stack, and it'll be such a goddamn mess. BUT, if you had error throwing in place, you'd be fine. The program would stop and tell you to fix your shit. Ideally, it wouldn't end the program unexpectedly, though, but first save all current data and whatnot so as to not lose current progress.

Convinced? Good.

Errors themselves can be put into a few different categories:

Syntax
Type
Logic
Run-Time


Let's go through them briefly, shall we?

Syntax Errors
These are easiest to deal with, I think. They are caused by the non-conformity of your source code with Java rules and regulations. A little order is a good thing in code! Missing brackets or a semicolon could cause this, or keywords in a wrong place etc. Your IDE should spot these as you type, so it's rarely an issue beyond figuring out why you're getting the error.

Type Errors
These tend to be caused by mismatching, you guessed it, types. For example, assigning the value "a" to something initialized as an integer. Or perhaps calling a method that the class of a certain object just doesn't have (calling pop() on a Car).


Logic Errors
These are very different to the first 2. These are errors in your algorithms or implementations of the algorithms in your code. These, unfortunately, cannot be detected by the Java compiler, since they only manifest when the program is running, and noticed when it doesn't end., for instance. Or computes the wrong value. Popping off an empty stack, as above, for instance. Or an infinite loop (while 1 is greater than 0, do...)
This is pretty much up to the programmer to find and deal with. Normally through exceptions, and just generally checking your loops etc.


Run-time Errors
Similar to logic errors, except not caused by the program being constructed poorly. Instead, this is caused by an event that occurred either totally unexpectedly (Why would you divide by 0?) or outside the range of conditions the program was designed to deal with (Write us a program that will give all the Fibonacci sequence until a maximum of the 15th term. User asks for a sequence 16 long). This is normally a question of handling user input well, since your users are idiots, probably, and can't be trusted at all, with anything.


The last 2 are normally the source of exceptions. Unexpected events that suck. Exceptions that aren't handled are the bane of everyone's existence. These normally end up in a not-fun termination of the program. Nothing saved, nothing completed, just all around bad mojo. Very annoying. Ideally, we'll want to recover the situation and soldier on. Failing that, save data before safely terminating.

Now that we got the basic concept, I think I'll get to work, so that's it for now..Questions welcome! Comment, follow, subscribe, share etc, and see you on Monday!


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

Thursday, 6 October 2011

Java: Inheritance IV

Today, we get to talk about the super keyword, and how static variables work with inheritance!


Super


Remember our Car had an int parameter, for whatever reason. Well if we had a constructor for Vehicle with an integer parameter that we wanted to use, our Car constructor would throw an error.. This is because a default constructor is looked for, but not found (we only have an integer parameter one). What we need to do instead is call the superclass constructor with either a parameter in the Car constructor, or some other value.






The super expression (heh) replaces the automatic call to the superclass constructor so the superclass constructor with the matching parameter is called instead. Just remember that if you are going to use super, it should be the first statement in your subclasses constructor.




Statics


Since static variables and methods are inherited, we should probably know how they work when inherited. Well, pretty much the same as always, 1 variable is shared between all instances of a class, including subclasses. It doesn't work in reverse though. A subclass is an extension of its superclass, but a superclass is not an extension of a subclass. Example:






...would lead to each new instance of Vehicle AND Car to increase the count, since Car uses the Vehicle constructor, but a similar counter inside Car would not increase for a Vehicle being created.




I'm tired now, so that's it for now..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 (fixed), and feel free to throw loads of criticism at us. 

Wednesday, 5 October 2011

Java: Inheritance III

Since it's hard to work with a bunch of the private variables from Vehicle, when in Car, but we don't want to make them public, in the name of encapsulation, and keeping the program....safe, I guess, there is another way that's supported! Private variables are pretty hard core, they, as we've seen, can't be used by anything but the class they're declared in, even in subclasses, which are just extensions. So instead, we use "protected". Like public and private, protected specifies the degree of encapsulation. Specifically, protected variables are usable by subclasses as well as any other classes within the same package. It's kind of like an in-between level of encapsulation!





Ta-da! No more error! So we have that idea down, I think we can fit in one more today, and that'll be on the constructors. Constructors are fairly straightforward for single classes, but when it comes to inheritance, how is everything coordinated? Java enforces some rules of construction to ensure a deterministic, as well as sensible, initialization:

a) After any parameter variables have been initialized, a call is immediately made to a superclass constructor before any other statements in the constructor body are executed. (This can be done explicitly with with "super" keyword, but we'll get to that tomorrow. Otherwise, it's done automatically).

b) All directly initialized instance variables are initialized and any initializer blocks evaluated, in the order they appear.

c) Statements in the subclass constructor are executed.

So, say with our Car, the class implemented via inheritance from Vehicle, creating a Car using the "new" operator (After giving it's constructor an integer parameter, just for display purposes):


This results in the Car constructor being called, which itself immediately calls the Vehicle constructor. Any directly initialized instance variables declared by Vehicle are now initialized, with statements in the Vehicle constructor body being executed. At this point, control returns to the Car constructor where direct initialization of instance and class variables declared in Car happens, followed by execution of the constructor.

What you want to take from this is less the technical info, but more: "Objects are initialized top down, from superclass to subclass."

Now we've got that in, I think it's time to relax, with the "super" keyword (and more!) coming tomorrow! So that's it for now..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 (fixed), and feel free to throw loads of criticism at us. 

Tuesday, 4 October 2011

Java: Inheritance II

Sorry for the late update, been sick again, but its passed!

To look at how inheritance is used, how it works and how its supported, we'll continue with the Car example we used yesterday. Since this is just for quick examples, don't expect me to have a fully functioning Car class by any stretch of the imagination, though.



I put the AirFilter and Thermostat classes (empty) inside the vehicles package just so I could show you this without a whole bunch of red lines everywhere! The point to take from this is, we have this Vehicle class, it contains a bunch of private elements that make up a vehicle, as well as an array to hold its location. I figured it would be as coordinates, but that really isn't important! Then, there's a bunch of public methods the class has, one of which is a constructor. Got it? Good.

Say now, we want to make a Car. It`s kind of like a Vehicle, but we have 4 wheels, a paint job, some headlights, whatever else. So we could just make another class from scratch, but if we were to do that (And we aren't), we'd notice a lot of similarities between the 2. Both would need to move, both would have air filters and thermostats and whatever else. The similarities are such that a Car is everything a Vehicle is, but more, as opposed to being just similar in some ways, and different in others, its just an extension. 

To make something a subclass of some other class, which is the superclass, we need to make to add in an "extends SuperClass" to the class declaration. As so:


Let's go through it bit by bit. First off, we have the class declaration. As you see, just a simple "extends Vehicle" is all we need. Car is now a subclass of Vehicle. The main method here is only for demo purposes. First, we create a Car object, and then we apply methods available to Vehicle on it. And that's all fine and dandy. Remember, the methods were all public. However, when we try to do something to one of the private variables in the Vehicle, we get an error message telling us as much.

Well, I could go on, but I'm finding it way easier to absorb information in smaller chunks, since there's more time to mull over each bit before being thrust onward, so that's it for now..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 (fixed), and feel free to throw loads of criticism at us.