Page 1 of 1

Basic Java for Beginners 3 Intro to structure, methods, classes, and scope Rate Topic: ***** 3 Votes

#1 NeoTifa  Icon User is online

  • Whorediot
  • member icon





Reputation: 2733
  • View blog
  • Posts: 15,809
  • Joined: 24-September 08

Posted 02 August 2010 - 07:10 AM

*
POPULAR

Basic Java for Beginners part 3 by NeoTifa

~~~~~~~~~~~~~~Index~~~~~~~~~~~~~~~

Part 1.) Introduction
Part 2.) Review on Program Structure
Part 3.) Basic Method Building
Part 4.) Basic Class Building and Inheritance
Part 5.) Scope

~~~~~~~~~~~~~~~Part 1~~~~~~~~~~~~~~
Introduction:

Hello again, and thanks for reading this far in my series. Yes, this used to be called “Basic Java for N00blets”, but others think that it is considered “unprofessional”, so I changed it. Don’t worry though, it’s still the same great content provided by me, your favorite author. :D (Same great product, different packaging!)

In this tutorial, I’m covering four main topics: program structure, methods, classes, and scope (no, not the mouthwash). These are very important (so is mouthwash), as classes and methods make up, well, your entire program (and prevent gingivitis), so I think it’s about time you know exactly what is going on here. Alright, let’s get started shall we?

~~~~~~~~~~~~~~~~Part 2~~~~~~~~~~~~~~
Review on Program Structure:

If you’ve read my first “Basic Java for N00blets” tutorial, you’ll notice how I decided to start with basic programming structure. Most books and classes wouldn’t do that, as students “might get confused”, but I think they would get just as confused looking at the Hello, world! program without having the slightest idea of what’s going on first. But I, being a student of programming myself, understand how difficult to understand what is going on when you first start a course. Knowing the basics of the structure, we are going to now delve more deeply into this topic.

As I’ve said before, the basic structure of a program is such:
class {
	method 1 {
	}
	method 2 {
	}
	...
	method n {
	} 
} 



Now get ready, because I’m going to blow your mind!
/******************************************
* This class is part of a program that does ___. 
* The purpose of this class is to ______.
* @author NeoTifa
* @date 25 Mar 2010
* @custom wonkey donkey
*******************************************/

package userpackage;

import import1.*;
import import2.*;
...
import importN.*;

class {

	//class variables
	type variable1 = “”;
	type variable2 = “”;
	...
	type variable = “”;

	//class constants
	final type variableC1 = “”;
	final type variableC2 = “”;
	...
	final type variableCN = “”;

	//constructors
	/**************************************************
	* This constructor is a no-arg constructor that does ___.
	* @param none
	**************************************************/
	no-arg constructor () {
		//code
	} //end no-arg constructor

	/*************************************************
	* This constructor has ____ arguments, and does ______.
	* @param param1 description
	* @param param2 description 
	* ......
	* @param paramN description
	**************************************************/
	constructor1(params) {
		//code
	} //end constructor1

	/*************************************************
	* This constructor has ____ arguments, and does ______.
	* @param param1 description
	* @param param2 description 
	* ......
	* @param paramN description
	**************************************************/
	Constructor2(params) {
		//code
	} //end constructor2

	.........

	/*************************************************
	* This constructor has ____ arguments, and does ______.
	* @param param1 description
	* @param param2 description 
	* ......
	* @param paramN description
	**************************************************/
	constructorN(params) {
		//code
	} //end constructorN

	//methods
	/*************************************************
	* This method has ____ arguments, and does ______.
	* @param param1 description
	* @param param2 description 
	* ......
	* @param paramN description
	* @return return description
	**************************************************/
	method1(params) {
		//code
	} //end method1

	/*************************************************
	* This method has ____ arguments, and does ______.
	* @param param1 description
	* @param param2 description 
	* ......
	* @param paramN description
	* @return return description
	**************************************************/
	Method2(params) {
		//code
	} //end method2

	..........

	/*************************************************
	* This method has ____ arguments, and does ______.
	* @param param1 description
	* @param param2 description 
	* ......
	* @param paramN description
	* @return return description
	**************************************************/
	methodN(params) {
		//code
	} //end method

} //end class



Whew! This is pretty much what any basic program/class file will look like essentially. I know, there is a lot, so I am going to break it down. Documentation is an essential part to your program, and can/will help you a LOT on down the road. I wrote a completely separate tutorial for it (as it is that important) located here. All parts of your program should be very well documented so when the heir to your success needs to update your code or something, they will know what’s going on.

We already covered that a program basically looks like this:
class {
	method 1 {
	}
	method 2 {
	}
	...
	method n {
	} 
} 



but now that we have more classes besides main, we should learn how custom classes are designed. In the expanded version above, there is something called a constructor. These are like methods that call themselves when a class is instantiated, depending on the input you put in the parameters, but I’ll explain those more in depth later. The constructors usually are at the beginning of the class after any class-wide variables and/or constants. After the constructors come the methods.
accessor class ClassVariable {

	variables
	constants

	accessor  ClassVariable(params) {
		//code
	} //end constructor

	accessor [static] return method1(params) {
		//code
	} //end method1

	accessor [static] return method2(params) {
		//code
	} //end method2

} //end class



This is the most basic representation that I can think of for a class. This is how our box class would look:

public class Box {

	// private so no other class can change the values directly
	// Initiated to 0 to prevent any possible null pointer errors. Silly stuff really.
	private double width = 0; 
	private double height = 0;
	private double length = 0; 

	public Box() {
	} // End no-arg constructor

} // End Box class


p.s. This code does nothing yet :) To call it, you would just instantiate it like you would any other built in class.
Box b = new Box();
This will create a Box b and instantly call the constructor, which does nothing as it is empty.

~~~~~~~~~~~~~~~~~Part 3~~~~~~~~~~~~~~~~~~
Basic Method Building:

As you know, methods are reusable bits of code encapsulated into perfect bite-size chunks for easy use. They are super easy to make. In this tutorial, I’m going to make a class called Box, and it is going to get the dimensions of the box and calculate the volume. Therefore, in this section, I’m going to make a method called calculateVolume for an example.

To create a method, you would follow the following template:
 accessor [static] return method1(params) {
	//code
} //end method1



Accessor refers to the “visibility” of a method, meaning who can use it. There are three options: private, public, and protected. Private means that only methods in the same class can access it, public means that it’s free game, and protected means only members, another name for methods, from the same package can access it. The return is what data type the method returns. If it doesn’t return a value, then you would just simply put a void there. After that comes a method name variable. These have the same naming rules as a regular variable, and you generally start them in lower case and make the first letter of words uppercase (i.e. calculateVolume). The parentheses hold parameters of any type. All code for this method goes in between curly brackets {}.

Inside the curly brackets is where all the magic happens. Any set of instructions that could be included in the functionality of that method should go in there. When the method is called, it does everything inside those curly brackets, from the opening bracket until it reaches the closing one. After it is done, the computer goes back to where it was before the method was called, and continues on, kinda like those 2 funky rows in the periodic table.

Now, as for those parameters, these are general catchers for any type of data you wish to manipulate. Inside the parentheses you declare a variable type, then a generic name for the variable. The variable name can be w or it could be width or anything, because inside the method you need take the variable caught by the parameter and assign it to a permanent variable. You can either make a variable inside the method or use one already defined earlier in the class. Our box example would look something like this:
public int setLength(double length) {
this.length = length;	// this.length refers to this class’s length variable
} // End setLength method



If you use the same variable name as one defined in the class already you will have to use the this keyword. Above, I used the same name to show you how it’s done. Just type this.variableName when you want to refer to an instance of something in current class you are in, and it’s not restricted to the data types either.

You can have as many parameters as you want, all you have to do is used commas to separate them. In fact, you can have several methods by the same name but with different parameters. This is called overloading. The computer will know which one you wanted to call by seeing the parameters you passed to it. getVolume(int l, int w, int h) is different from getVolume(double l, double w, double h) which is different from getVolume(int l, double w, long h). The best practice is to make several similar methods to cover every possible scenario (error handling).

If you have a return type other than void, you have to have a return somewhere in the method, preferably at the very end. All you need to do with this is simply type return variable;. Now, placement of the return is important, as if you have it inside a loop, the compiler will tell you that it still doesn’t have a return statement because it could potentially never be reached. In this case, just put a generic return outside the loop at the end of the method just in case.
...
	if(condition a) {
		return x;
	}
	else if(condition B)/> {
		return y;
	}
	else {
		return z;
	}
return w;


This is acceptable. Here’s another example:
public double calculateVolume() {
	double volume = length * width * height;	// Using the classes variables
	return volume;
} // End calculateVolume method



To call a method, just type in the class’s variable with a period and the method’s name with its parameters. If it has a return, you will want to catch the value returned or display it or else it will get lost.
// In a main or test class
Box b = new Box();
int volume = b.calculateVolume();


This of course would just return 0 but hey, it’s a form example.

~~~~~~~~~~~~~~~~Part 4~~~~~~~~~~~~~~~~~
Basic Class Building and Basic Inheritance:

In the program structure review section above, I covered the basic format of a class, but here is a more detailed structure with some inheritance.

access class ClassB extends ClassA implements InterfaceC {

	access ClassB(params) {
		//c0d3z
	} // end constructor
	//methods

} // end ClassB



Now don’t be freaked out by the “extends and implements” stuff, as that’s super simple. Earlier I mentioned that when you instantiate a class, you are calling the constructor with the appropriate arguments. If you don’t put any arguments in the parenthesis when you instantiate, then the compiler will call the no-arg constructor, which should give some very basic default instructions. However, if you do not declare a no-arg constructor, the compiler sort of “makes” one for you, meaning it just does absolutely nothing, just to avoid throwing you any errors. Just like methods, constructors can be overloaded as well. In fact, it is advisable to. Here’s an example of what our Box might look like now:

public class Box {

	private double length;
	private double width;
	private double height;

	public Box() {
		this.length = 1;
		this.width = 1;
		this.height = 1;
	} // end no-arg constructor

	public Box(double length, double width, double height) {
		this.length = length;
		this.width = width;
		this.height = height;
	} // end constructor

	public double calculateVolume() {
		int volume = length * width * height;
		return volume;		// You could also write return length * width * height; 
	} // end calculateVolume

} // end Box 



See, making classes is super easy. “But Neo!” you say. “What if I want to make a more elaborate copy of a class without copy-pasting?!” Well, you’re in luck! That’s what inheritance is for! Just like your family tree, Java classes generally have several branches coming from them. In fact, without you having to declare it as such, your classes automatically extend from the Object class! Each time a class extends something, it has access to its parent’s methods, and you can even add methods to make it more customized. A good example would be ... say... JLabel.

Object -> Component -> Container -> JComponent -> JLabel

I’m not going to go into detail on inheritance yet, but I thought you should see that there is more to a class header than just the basics. I’ll actually cover it in detail in another tutorial.

~~~~~~~~~~~~~~Part 5~~~~~~~~~~~~~
Scope:

Personally, I prefer winterfresh flavor by Crest, but everybody is different. Oh wait, nevermind. :P

A variable’s scope depends on where you declare a variable (we are talking non-static of course). If you declare a variable at the top of a class, then the variable can be accessed by all the methods. However, if you declare it within a method, you can only use that variable inside that method. Remember how in for loops you say for(int i = 0; i < x; i++) {}? This is basically creating a loop variable that is only relevant in that loop. If you try to access i after the loop is over, your compiler will throw a fit because there is no i outside that loop! Some people declare the looping variables outside the loop, though I think that is a waste of memory, because as soon as you’re done with the loop the variable deletes itself (referred to as garbage collection, garbage keep, or other such variations).

When I first was learning about scope, I liked to think of it like those Venn diagram graphs, where you would have the outer, most general, circle, then a few more specific circles. These more specific circles were still in the same classification as the bigger circle, yet with its own properties (another name for variables/members). And even within those more specific circles would be even smaller, more specific circles, etc. etc. etc. Kinda reminds you of inheritance, doesn’t it?

This also applies to methods. If you’re trying to access another class’s method, and it’s not static, you need to put the class name in front, so as to say “that class’s method...” (ie. Box.calculateVolume()) You can only do this, however, if that method or member is declared as public (or protected). If it is private, only that class can use them.

Going even further, you can access any class’s methods and members as long as they are public or protected and in the same package. If they are not in the same package, you have to put an import statement at the beginning, and name which class/classes you’re going to be using. This is why when you want to do GUI you need to import javax.swing.*;. If you’re using several, it might be smart to just put a wildcard (*) symbol in there. The only way you can use another package’s stuff is if it is public. Declaring something protected prevents another package from looking at and using your stuff.

The access hierarchy kinda looks like this:

package A {
	class A { package A
		method A { package A and class A
			loop A { package A, class A, and method A} // loop A
			loop B { package A, class A, and method A, but not loop A} // loop B
		} // method A
	class B { package A
		method A { package A and class B} // method A
		method B { package A and class B} // method B
} // package A

package B {
	ditto
} // package B



Well, that’s about it for this tutorial. Hope it comes in handy. I think the next tutorial might be like polymorphism or something. Idk. ^__________^

Is This A Good Question/Topic? 8
  • +

Replies To: Basic Java for Beginners 3

#2 kowwok  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 21
  • View blog
  • Posts: 583
  • Joined: 20-November 09

Posted 02 August 2010 - 11:09 AM

Nice job on the third installment :)
Was This Post Helpful? 0
  • +
  • -

#3 NeoTifa  Icon User is online

  • Whorediot
  • member icon





Reputation: 2733
  • View blog
  • Posts: 15,809
  • Joined: 24-September 08

Posted 02 August 2010 - 11:38 AM

Thanks!
Was This Post Helpful? 0
  • +
  • -

#4 KingCuddles  Icon User is offline

  • D.I.C Regular

Reputation: 176
  • View blog
  • Posts: 496
  • Joined: 20-December 08

Posted 02 August 2010 - 02:04 PM

Links to the first two because I am tooo lazy and too tired to look for them?

:D
Was This Post Helpful? 0
  • +
  • -

#5 NeoTifa  Icon User is online

  • Whorediot
  • member icon





Reputation: 2733
  • View blog
  • Posts: 15,809
  • Joined: 24-September 08

Posted 02 August 2010 - 05:41 PM

Really?#1 and #2 They were both on this page. -___-
Was This Post Helpful? 1
  • +
  • -

#6 Guest_catch*


Reputation:

Posted 03 August 2010 - 04:17 AM

I liked "N00blets" better :) Very good job anyway!
Was This Post Helpful? 1

#7 NeoTifa  Icon User is online

  • Whorediot
  • member icon





Reputation: 2733
  • View blog
  • Posts: 15,809
  • Joined: 24-September 08

Posted 03 August 2010 - 10:34 AM

I do too, but the mods were getting bum hurt about it.
Was This Post Helpful? 0
  • +
  • -

#8 Elcric  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 102
  • View blog
  • Posts: 453
  • Joined: 02-May 09

Posted 03 August 2010 - 11:42 AM

Re: The most beautiful language?

NeoTifa, "Watch out!"

My favorite opera!

:rockon:

Excellent tutorial series!
Was This Post Helpful? 0
  • +
  • -

#9 NeoTifa  Icon User is online

  • Whorediot
  • member icon





Reputation: 2733
  • View blog
  • Posts: 15,809
  • Joined: 24-September 08

Posted 03 August 2010 - 04:19 PM

Oh I see. Thanks. It's actually mine too.
Was This Post Helpful? 0
  • +
  • -

#10 desukase  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 9
  • Joined: 04-September 10

Posted 06 September 2010 - 04:35 PM

Love the tutorial, as I'm very much a n00blet. I'd like to see some more tutorials from you soon. :3

But, as a beginner, I've some hard time understanding some of these concepts. Even though I get most of it, for some reason or another, some of this stuff just flies over my head. *whoosh*

I have learned a bunch from your tutorials, though, so thanks a bunch. :D
Was This Post Helpful? 1
  • +
  • -

#11 NeoTifa  Icon User is online

  • Whorediot
  • member icon





Reputation: 2733
  • View blog
  • Posts: 15,809
  • Joined: 24-September 08

Posted 09 September 2010 - 06:38 AM

Thank you for the positive feedback. What part goes whoosh past you?
Was This Post Helpful? 0
  • +
  • -

#12 desukase  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 9
  • Joined: 04-September 10

Posted 28 September 2010 - 05:05 PM

Well, a lot of it at first, naturally, seeing as how I've only recently started playing around with Java on my own outside of class. Personally, I'm not very good at reading out information, but experimentation works just swell for me. I've tried out extremely basic classes and methods (adding parameters together and returning the sum...), and now I'm starting to get how it all works. But this got me off the ground, along with another class/method tutorial that's a great supplement to this one [this]. Maybe it's the simplicity of locke's tutorial and example, but whatever.

But I've got most of the stuff in this tutorial down by now. So thanks for getting me up on my feet. ;D
Was This Post Helpful? 0
  • +
  • -

#13 NeoTifa  Icon User is online

  • Whorediot
  • member icon





Reputation: 2733
  • View blog
  • Posts: 15,809
  • Joined: 24-September 08

Posted 01 October 2010 - 11:20 AM

What?! Someone else's tutorial was simpler than mine?!?!?! fffffffffuuuuuuuuuuuu ;__; My dreams have been shattered.

So what about reading out information don't you get? Formatting? Printing to a file? Printing to a printer? Printing to console?
Was This Post Helpful? 0
  • +
  • -

#14 desukase  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 9
  • Joined: 04-September 10

Posted 09 October 2010 - 02:46 PM

I meant "getting information from reading something" by "reading out information," not anything related to reading stuff from files (although I plan on working on that later). But that's probably because I learn better by looking at and manipulating actual code. Considering how my AP Computer Science class hasn't even touched classes and methods, save for quick mentions when we covered strings and what we could do with them, it took a lot of experimentation on my part. We're a quarter into the school year and I'm amazed that we still haven't covered something as important to Java as classes and methods. >:|

As for suggestions on improving the tutorial now that I (think I) understand the topic, more than a few examples for using multiple classes and methods would be great. I think you should at least put in full code of that Box class and whatever main class it's used in, since you only put in the code for the full Box class and nothing else. But really that's the only problem I can see with this tutorial. The other tutorial I mentioned in my previous post did something similar, but it didn't exactly have a "full" code, so I looked around in the snippets until this made the object-oriented-ness of Java and the idea of classes and methods clear as night and day for me (I swear, it was like I was suddenly enlightened or something). It's just some basic instantiating and method-using, so that shouldn't be too hard to insert into your tutorial, hm? ;P

This is pretty unorganized, but it's a great resource for learning about a whole bunch Java's little functions. It's helped me figure out how to use arrays, especially, and I'm sure you can take a look at that for ideas for future tutorials. ;D
Was This Post Helpful? 0
  • +
  • -

#15 NeoTifa  Icon User is online

  • Whorediot
  • member icon





Reputation: 2733
  • View blog
  • Posts: 15,809
  • Joined: 24-September 08

Posted 19 October 2010 - 08:21 AM

You mean Scanner then? I covered it in Part 2. This was just a basic look at classes. I'm going to delve further into the topic with my polymorphism tutorial I'm working on.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1