Beginners Java Tutorial – Objects and Classes
November 24, 2008 at 11:10 am 1 comment
We also have some excellent Beginners Programming Java tutorials that use high quality narrated videos and practical working files to teach the fundamentals of programming in Java Beginners Java Tutorial Videos – Programming
Java Tutorial – Objects and Classes
This Java tutorial assumes some very basic Java knowledge, e.g. method syntax.
Objects are the key to building robust and efficient Java applications. When developing a large or complex system, developers begin the design process by dividing up the various project requirements into application components. These are ultimately represented by Objects within the application, and are implemented in code by Class declarations. While it might be difficult to perceive the advantages to this technique while you’re learning (and working on small projects), if you adopt the right practices at this stage, you will develop the skills required for professional Java development.
Creating Objects
In your Java IDE, create a new Project called MyFirstObject, with Main Class MyFirstObject (if you’re using Netbeans myfirstobject.MyFirstObject with myfirstobject as the package name). Inside your MyFirstObject Class enter the following:
//class declaration public class MyFirstObject { //main method public static void main(String[] args) { //code here will be executed when the program is run } }
Using Objects is a way of dividing up responsibility for the different parts of an application. You can do this in a variety of ways: for example, you can carry out some of your program’s tasks within separate methods, calling these from the main part of your code. Using Objects is similar to this, but each Object requires a Class declaration, which you create in a separate .java file.
The Objects that you may have already used, such as those representing Java datatypes String, Array etc also have their own Class declarations – these are built into the Java language itself, and although you can’t see the code, you can see an overview as part of the Java API (Application Programming Interface). The Objects that you define yourself will function in the same way – let’s create a simple example.
In your project, create a new Class called MyHelper, entering the following:
//class declaration public class MyHelper { //instance variable private int helperNum; //constructor method public MyHelper() { helperNum=1; } //public method public int getNumber() { return helperNum; } }
The above code is a simple Class declaration specifying the properties that any Object of the MyHelper Class will have – next we will create an ‘instance’ of the MyHelper Class within our Main Class, but first let’s look at the Class declaration.
Instance Variables
Instance variables represent any data that should be stored in every instance of your Object, meaning that every time you create a MyHelper Object it will contain a helperNum integer variable. Instance variables should always be private, so that their value cannot be changed except within the Class declaration itself – more on this later.
Constructor method
You can see that the constructor method looks the same as any other method, except that it doesn’t have a return type specified – this is because the constructor method is called when an Object of the Class is created (using the keyword ‘new’), and what it returns is – an Object of the Class. The constructor method should always have the same name as the Class. Within the constructor method, you carry out ‘initialisation’, meaning that you assign a value to your instance variables – when the constructor method has executed, none of your instance variables should be left without a value, as this can make your program unpredictable.
Public Method
The declaration contains one public method, ‘getNumber’, which can be called on any Object of the Class. Although the example may seem trivial, it is common to have methods which either set or return the value of an instance variable.
The reason for such methods relates to your instance variables being private. The basic principle underlying Object Oriented development is that your Objects have a ‘well-defined’ interface – this means that all access to the data contained within a Class should be through its methods. If the instance variables were public, external code would be free to change their values directly, which can be dangerous, since external code may not be aware of the implementation details for the Class. If you restrict all access to your instance variables, to the public methods in a Class, you can carry out any checks etc there to ensure that your data is not assigned invalid values.
Using your Class
Now go back to your Main Class and enter the following inside your main method:
//code here will be executed when the program is run //create a MyHelper object MyHelper mh = new MyHelper(); //call a method on it, assign the result to a variable int num = mh.getNumber(); //write the variable out for testing System.out.println(num);
Compile and run your program and you should see the number 1 written to standard output. You create an Object of your Class, and call methods on it, in exactly the same way as any other Object. From your main method, you can call any methods on the MyHelper Object that are declared as public inside the Class.
A Class may also have private methods that are for use within the Class only. For example, one of your public Class methods may involve complex or repetitive processing that you decide to separate out into its own method, calling this from the public method – in this case the separate method should be declared as private, as this method relates to the implementation of the Class itself, which external code should not have access to.
Object principles
If you’re new to Object Oriented development in general, it can help to think in terms of ‘black boxes’. One of the principles that makes Java suited to developing large projects, is the idea that any application developed in Java can in turn be used by anyone else as a component in another application. Many open source projects use Java, with people sharing resources that they have developed in the language.
For this approach to be feasible, it must not be necessary for someone using a component to have to understand all of the implementation details within it. So long as there is a ‘well-defined’ interface, you should be able to make use of external Java libraries and resources while knowing nothing about what goes on inside them – in the same way that you can use a String or Array without having to understand how it is implemented in the underlying code. In this approach, you can think of Objects as ‘black boxes’ – code external to the Class should be able to make use of it without having to be aware of the inner code. When you develop your own Objects, you should adopt the same principle – even if you’re developing an application single-handed, this approach makes for programs that are faster to build and easier to debug.
More on Classes
As a final note, you should be aware that you can have more than one constructor method in a Class, each one taking different parameters. In this case whichever method is called is dictated by what parameters are passed when an Object of the Class is created. To demonstrate, add a second constructor to your Class, beneath the existing one:
//class declaration public class MyHelper { //instance variable private int helperNum; //constructor method public MyHelper() { helperNum=1; } //second constructor - takes a parameter public MyHelper(int value) { helperNum=value; } //public method public int getNumber() { return helperNum; } }
Now add the following in your main method, after the existing code:
//create an object passing int parameter MyHelper mh2 = new MyHelper(2); int num2 = mh2.getNumber(); System.out.println(num2);
When you run your program, this time it should output 1 and then 2 for the new Object. Whichever constructor matches the type and number of parameters passed is the one that’s called during Object creation.
When using Objects in your programs, you should try to decide what the various Classes will be at the outset, by dividing up the different requirements that your project has, and assigning responsibility for these to your set of Objects.
Next Java Tutorial – Datatypes .
Entry filed under: Java. Tags: Java Programming, Java Tutorial.
1. Beginners Java Tutorial - Programming Part 1 « Video Training - Tutorials | November 24, 2008 at 11:11 am
[…] and enter your code within the main method to start with, and the rest will soon follow. Next Java tutorial – Objects and Classes . Possibly related posts: (automatically generated)Beginners ActionScript OOP Tutorial Part 2Source […]