Java Working With Class
Java Working With Class
Written by Ian Elliot   
Thursday, 18 August 2016
Article Index
Java Working With Class
Hands-on example
Why class and objects?
MathExample

 javacovericon

A Simple Example

To see how it all works, we need an example that not only demonstrates how the Java language works to let you create classes and objects, but something that demonstrates why you might go to the trouble of using it.

Consider for the moment that you need to perform some complicated calculations. You could just write a set of functions, one for each calculation, but in many cases it would be better to group them together so that they could be used as properties and methods of an object.

For example, suppose you needed to work with circles drawn on a graphic display. Then it makes sense to create a class that encapsulate all of the things you might want to do with a circle.

Start a new project called MathExample.

Add a new class called Circle.

The basic properties of a circle are its position x,y and its radius r - so let's add these as properties to the Circle class:

 public class Circle{
    public double x;
    public double y;
    public double r;

 

They are public and so accessible from outside of the class.

The data type double is a double precision number.

We also need to use the value of the constant Pi and there is no reason why we should make this available to the outside world so it can be private:

private double Pi=3.14159;

As well as storing the size and position of the circle it would be useful to have the ability to discover the circumference and so we add a public circumference method:

public double circumference(){
        return 2*Pi*r;
    }

In the same way it would be nice to discover the area of the circle - so lets add an area method. But to do this we need to compute r squared. Let's add a private squared function that simply returns the square of any number:

private double square(double a) {
        return a * a;
    }

 

You could argue that square was sufficiently useful to make public but in the spirit of hiding how the calculations are performed we can also chose to make it private.

Finally the area function is:

public double area() {
        return Pi * square(r);
    }

 

The complete list for the class is:

public class Circle {
    public double x;
    public double y;
    public double r;
    private double Pi = 3.14159;

    public double circumference() {
        return 2 * Pi * r;
    }
    private double square(double a) {
        return a * a;
    }

    public double area() {
        return Pi * square(r);
    }
}

 

Now let's write a main function that makes use of the class:

 

public static void main(String[] args) {
    Circle circle = new Circle();
    circle.r = 10.5;
    circle.x = 0;
    circle.y = 0;
    double circ = circle.circumference();
    double area = circle.area();
    System.out.println(circ);
    System.out.println(area);
 }

This starts off by creating a circle object from the class.

Notice that we have the problem of finding a suitable name for the class and the object - they can't both be called Circle.

This is a standard problem of class based object oriented languages and there are many ways around it. One is to always start a class name with an uppercase letter and use lowercase for objects.

So in our example the class is Circle and the object is circle - remember Java is case sensitive. In practice this name problem isn't as big in real life programming  as it is in examples because you generally have more specific names ready to use for instances of a class - bigcircle, bluecircle, offsetcircle and so on.

After creating the circle object we set its radius and position and then use its methods to get the circumference and area which are displayed in the output window.

Notice you can create any number of circles now you have the Circle class and each one is independent of the others and will compute its own area and circumference.

This is just one of the reasons object-oriented programming is a good idea - there are many more more sophisticated reasons for using it.

Before ending this chapter, I should add that our example doesn't do things in the best possible way.

There are better ways to do things. For example, instead of using public variables as properties it is better to use methods to acces private variables. That is instead of letting users of the class directly access x,y an r we would introduce accessor functions like getX and setX. This is so standard in Java that giving direct access to member variables is almost never encountered. However when you are learning Java you need to know how things actually work. We will return to get and set methods later. 

There's still a lot to learn  about classes and objects, including constructors, inheritance and more.

These ideas are the subject of later chapters.

 

 

Modern Java
With NetBeans And Swing

covericon

Contents

  1. Getting started with Java

    In chapter 1 we tell you how to get started with modern Java development in the shortest possible time. The approach uses NetBeans and Swing and all of the resources used are free to download and use.

  2. Introducing Java - Swing Objects
    In the second chapter of our beginner's guide to Modern Java we find out more about objects by exploring the Swing framework with a simple hands-on example.

  3. Writing Code

    Using ifs and loops is one of the most difficult parts of learning how to program. Our beginners introduction to Java reaches the part all programmers have know and know well - how to write code.

  4. Command Line Programs
    Command line programming means doing things in the simplest possible way. We take a careful look at how data types and code build a program.

  5. User Interface - More Swing
    Finding out how to create a User Interface (UI) using the Java Swing library is not only a useful skill, it also is an ideal way to learn about objects and to make sure that the ideas really have sunk in.

  6. Working With Class
    The Swing components have provided an easy approach to the idea of objects, but there comes a time when you have to find out how to create your own. In this part of Modern Java, we look at the standard ideas of object-oriented programming.

  7. Java Class Inheritance
    Working with classes and objects is a very sophisticated approach to programming. You can't expect to absorb all of its implications in one go. We have already looked at the basics of class and objects. Now we need to look at encapsulation, constructors, overloading and inheritance.

  8. Java Data Types - Numeric Data 
    After looking at some of the advanced ideas of classes and objects we need to return to some simpler topics to make our understanding complete. We need to look more closely at data and, to get things moving, numeric data. 

  9. Java Data Types - Arrays And Strings
  10. Building a Java GUI - Containers
    In this chapter we get to grips with the idea of a container that is used to host components to build a user interface. We also find out how the Swing GUI Builder generates code to make it all much easier. 
  11. Advanced OOP - Type, Casting, Packages
  12. Value And Reference 
  13. Events

 

 

To be informed about new articles on I Programmer, install the I Programmer Toolbar, subscribe to the RSS feed, follow us on, Twitter, Facebook, Google+ or Linkedin,  or sign up for our weekly newsletter.

 

blog comments powered by Disqus



Last Updated ( Thursday, 18 August 2016 )
 
 

   
RSS feed of all content
I Programmer - full contents
Copyright © 2016 i-programmer.info. All Rights Reserved.
Joomla! is Free Software released under the GNU/GPL License.