Getting Started with Java: Classes

Author: Ronald S. Holland
Total Application Works

To visit my site

HOME] Consulting Design Maintenance Project Testing Training Turnkey Java C++ SQL HTML JavaScript C#

To contact us

© 2002 - 2017 All Rights Reserved Total Application Works

  • Tell a friend about this site (copy and paste the following HTML page into a file (e.g., using Notepad).)

  • <html>
    <title>Example of a link </title>
    <a href="">
    Java: Introduction to Classes </a>


Java, as a programming language, is widespread and can be found on nearly all computers. This tutorial assumes that you have some prior programming experience. It is not intended to be a comprehensive discussion on Java or programming. As we ease into Java, we will briefly discuss the concept of classes. But first, what is a Java?

What is Java?

Java is a programming language and computing platform first released by Sun Microsystems in 1995. There are lots of applications and websites that will not work unless you have Java installed, and more are created every day. Java is fast, secure, and reliable. From laptops to datacenters, game consoles to scientific supercomputers, cell phones to the Internet, Java can found everywhere!

Let's consider the class of automobile, which contains the set of all automobiles. A sampling might be:

  • Acura TL
  • BMW 5 series
  • Buick Century
  • Ford Explorer
  • Honda Pilot
  • Mazda6
  • Toyota Avalon
  • Toyota Highlander
  • Volvo S60
  • etc.
The set/get methods usually will be the only way to modify the variables in this structure, and they are usually the only way to access the variables in a class. By allowing only a class to access the data makes the programs more modular; the principle itself is called encapsulation. This allows the implementation to change more easily because only the class itself should have to rely on the changes. For example, a set method might be setCruise_Control().

In real-life, complex objects are often built from smaller, simpler objects. This process, in Java is called object composition. For example, a car is built using a:

metal frame,
  • Turn on
  • turn off
  • Shift to 1st
  • Shift to 2nd
  • Shift to 3rd
  • Shift to neutral
  • Shift to reverse
steering wheel,
  • Turn left
  • Turn right
  • Go straight
wind shield,
  • Apply
  • Release
electronic stability control,
  • counter oversteer
  • counter understeer
cruise control,
bucket seats,
digital clock,
AM/FM radio,
CD Changer,
gear shifter,
and a large number of other parts./b>
Figure 1: Object composition and methods


A class is a template from which individual objects are created. If we were to implement Figure 1 as a class, it might look something like:

 * Automobile Class - this is pseudocode and as 
 * such, it is not compilable.

class Automobile extends JFrame {   
        // Declare member types
   Metal_frame    mf ;
   Ignition       ign ;
   Engine         eng ;
   Tires          tires ;
   Transmission   trans ;
   Steering_Wheel sw  ;
   Wind_shield    ws  ;
   Brakes         brakes ;
   ABS            abs ;
   CruiseControl  cc ;
   DigitalClock   dc :

   public Automobile  {

public static void main(String[] args) {
   Automobile auto ;    

   retrun 0 ;
Figure 2: Automobile Class

We will explore a class in more detail in the next section.

What is a class?

A class is an expanded concept of a data structure: instead of consisting of only data, it can contain both data and functions/methods. An object is an instantiation of a class. If you were to compare classes to primitive data, such as int variables, a class would be the data type (int) and an object would be the variable. Classes are generally declared using the keyword class which is followed by the name of the class. For an example, see the following format:


import javax.swing.JOptionPane ;


public class Employee {

   private String myName ;
   private String myTitle ;
   private String myHireDate ;
   private double mySalary ;

   public Employee(String name, String title, String hireDate, double salary)  {
      myName      = name ;
      myTitle         = title ;
     myHireDate = hireDate ;
      mySalary    = salary ;

   public Employee(String name,  double salary) {
      myName = name ;
      mySalary = salary ;

   public String getName() {
      return myName ;

   public String getTitle() {
      return myTitle ;

   public String getHireDate() {
      return  myHireDate ;

   public double getSalary() {
      return mySalary;

   public void raiseSalary(int percent) {
      mySalary = mySalary +
         percent * 0.03 * mySalary;

   public void setSalary(double salary) {
      mySalary = salary;

   public String toString() {
      return "Name: " + getName() +
             ", Salary: " + getSalary();

   public void setTitle( String title ) {
      myTitle         = title  ;

   /** ***********************************************
    *  Function: showIn( String mess , String title )
    *    1- The purpose of this method is to display the
    *       menu using a JOptionPane - show calculator options.
   public String showIn( String mess , String title ) {
      String ret  ;

      ret = JOptionPane.showInputDialog( null ,
                   mess ,
                   title ,
                   JOptionPane.PLAIN_MESSAGE ) ;

      return ret ;

public static void main(String[] args) {
      String msg , ret  ;
      Employee Jim = 
         new Employee("James Stewart",  "Junior Programmer", "March 17, 2016" , 55000.0 );
      msg = "Jim's salary: " +  Jim.getSalary()  + "\n" ;
      Jim.raiseSalary( 1 ) ;
      msg = msg + "Jim's salary: " +  Jim.getSalary()  + "\n" ;
      Jim.raiseSalary( 1 ) ;
      msg = msg + "Jim's salary: " +   Jim.getSalary()  + "\n" ;
      Jim.setSalary( 60000.0 ) ;
      Jim.setTitle("Associate Programmer" ) ;
      msg = msg + "Jim's salary: " + Jim.getSalary() + " Title " + Jim.getTitle()  + "\n" ;
      ret    =  Jim.showIn( msg ,  "James' Salary " ) ;

      Employee jlo = 
         new Employee("Jennifer Lopez",  "Junior Programmer", "March 17, 2016" , 55000.0) ;
      msg = "jlo's salary: " + jlo.getSalary()  + "\n" ;
      msg = msg + "jlo's salary: " +  jlo.getSalary()  + "\n" ;
      jlo.raiseSalary( 1  );
      msg = msg + "jlo's salary: " +  jlo.getSalary()  + "\n" ;
      ret    =  jlo.showIn( msg ,  "Jennifer Lopez' Salary " ) ;

      Employee lake = 
         new Employee("Winter Flaws", 50000.00) ;
       msg =  "lake's salary: " +   lake.getSalary()  + "\n" ;
      ret    =  lake.showIn( msg ,  "Winter Flaws' Salary " ) ;

      Employee wayne = 
         new Employee("Drew Person", 47000.0);
       msg =  "Drew's salary: " +   wayne.getSalary()  + "\n" ;
      ret    =  wayne.showIn( msg ,  "Drew Person's Salary " ) ;


Jim's salary: 55000.0
Jim's salary: 56650.0
Jim's salary: 58349.5
Jim's salary: 60000.0 Title Associate Programmer
jlo's salary: 55000.0
jlo's salary: 56650.0
jlo's salary: 58349.5
lake's salary: 50000.0
Name: Winter Flaws, Salary: 50000.0
Name: Drew Person, Salary: 47000.0
Figure 3: Program using class

In Figure 4, you will note that the format for declaring a class is:

class class_name {
      declare variables
      declare variables
      declare variables

      define methods  
Figure 4: Declaring a class

In the above Figure 4, access to the data and methods is restricted by the following access specifiers:

  • Public members are accessible from any point the object is visible. There are some parts of the class are supposed to be available to anyone using the class; these parts are designated public class functions. Think of a class as though it were an appliance like a computer: the public parts of the class correspond to the parts of the computer that you can use/touch on an everyday basis, such as the:
    • keyboard,
    • on/off button,
    • screen,
    • mouse,
    • etc.
    The items you normally don't touch that might be considered protected/private are the:
    • motherboard,
    • RAM,
    • disk drive,
    • memory,
    • functions that read/write to the RAM,
    • functions that read/write to the internal disk drive,
    • etc.

    Consider some of these different access restrictions for a moment. Why would we want to declare something private instead of public? The idea is that some parts of the class are intended to be encapsulated/internal to the class. This allows us to implementing encapsulated features. If we consider the SQRT key on a calculator, the key pad is public and the SQRT code is private/protected. This corresponds to the protected or private parts of the class, the things that are necessary for the class to function, but that nobody who uses the class should need to know how it is coded. The great thing about this separation is that it makes the class easier to use (who would want to use a calculator where you had to be well aware of programming to know exactly how all of the functions work in order to use it?) The key idea is to separate the interface you use from the way the interface is supported and implemented.

    Classes usually contains a function: a constructor . The syntax for a constructor is simple: the class name denotes a constructor (e.g., Employee()). The constructor is used to initialize variables. If it turns out that you don't need to actually perform any initialization, then you can allow the compiler to create a "default constructor" for you.

    The constructor is automatically called when the programmer creates an instance (see Figure 4 above) of the class. The only time a destructor is called is when the instance of the class is no longer needed, either when the program ends, this is when the class reaches the end of scope, or when its memory is deallocated using delete. Please note that neither constructors nor destructors return arguments! This means you do not want to (and cannot) return a value in them.

    Other Classes

    Other types of classes to consider are:

    1. An inner class in Java
      • An inner class or nested class is a class which is declared inside the class or interface.
    2. An static class in Java
      • A static class is basically an inner class in Java. Java doesn't allow you to create top-level static classes; only nested (inner) static classes.
    3. An anonymous class in Java
      • An anonymous class is defined and instantiated in a single succinct expression using the new operator.
    4. An abstract class in Java
      • An An abstract class is a class which can’t be instantiated (you cannot create the object of abstract class),
    5. An Sinleton class in Java
      • Helps us to keep only one instance of a class at any time. The purpose of singleton is to control object creation by keeping private constructor.
    6. An local class in Java
      • Local classes are classes that are defined in a block, which is a group of zero or more statements between balanced braces.
    7. An adapter class in Java
      • An adapter class provides the default implementation of all methods in an event listener interface.
        1. ActionListener - This interface is used for receiving the action events.
        2. ComponentListener - his interface is used for receiving the component events.
        3. ItemListener - This interface is used for receiving the item events.
        4. KeyListener - This interface is used for receiving the key events.
        5. MouseListener - This interface is used for receiving the mouse events.
        6. TextListener - This interface is used for receiving the text events.
        7. WindowListener - This interface is used for receiving the window events.
        8. AdjustmentListener - This interface is used for receiving the adjusmtent events.
        9. ContainerListener - This interface is used for receiving the container events.
        10. MouseMotionListener - This interface is used for receiving the mouse motion events.
        11. FocusListener - This interface is used for receiving the focus events.

    What is the class destructor?

    A destructor is a special member function of a class that is executed whenever an object of it's class goes out of scope or whenever the delete expression is applied to a pointer to the object of that class. How does the class destructor peform in Java? There is no class destructor in Java. Instead, in Java, garbage means unreferenced objects.

    Garbage Collection is process of reclaiming the runtime unused memory automatically. In other words, it is a way to destroy the unused class objects.

    To do so, we were using free() function in C language and delete() in C++. But, in java it is performed automatically. So, java provides better memory management..


    This tutorial is intended to be an introduction, and as such, is far from being an exhaustive description. In this tutorial, you have learned the basics of a:

    • Class;
    • class definition;
      • All class members are private by default.
    • class declaration;
    • access specifiers;
    • access specifier restrictions;
    • constructors and destructors;
    • instantiation;



    adapter class

    abstract data type

    anonymous class?


      object-oriented programming, a class is an extensible program-code-template for creating objects, providing initial values for state (member variables) and implementations of behavior (member functions or methods).


      because it is a Class method that returns an object of its type, it is also called a convenience method. Instances methods operate on instances of classes (ie, "objects"). Class methods are associated with classes (most languages use the keyword static for these guys).

    object composition

      object composition (not to be confused with function composition) is a way to combine simple objects or data types into more complex ones.


      is the hiding of information in order to ensure that data structures and operators are used as intended and to make the usage model more obvious to the developer.

    event handling


      In object-oriented programming, inheritance is when an object or class is based on another object (prototypal inheritance) or class (class-based inheritance), using the same implementation (inheriting from an object or class) specifying implementation to maintain the same behavior (realizing an interface; inheriting behavior).


      Override InitInstance to initialize each new instance of your application running under Windows. Typically, you override InitInstance to construct your main window object and set the CWinThread::m_pMainWnd data member to point to that window.

    Inner class

      class Outer_Example {
         int num;
         // inner class
         private class Inner_Example {
            public void print() {
               System.out.println("This is an inner class");
         // Accessing he inner class from the method within
         void display_Inner() {
            Inner_Example inner = new IInner_Example();
      public class My_class {
         public static void main(String args[]) {
            // Instantiating the outer class 
            Outer_Example outer = new Outer_Example();
            // Accessing the display_Inner() method.


      The creation of an instance is called instantiation. In object-oriented programming (OOP), an instance is a concrete occurrence of any object, existing usually during the runtime of a computer program.

    Local class

      public class LocalClassExample {
          public static void validatePhoneNumber (
             public static void validatePhoneNumber  (
                // Start of local class 
                class PhoneNumber {
          public static void main(String... args) {
              validatePhoneNumber("123-456-7890", "456-7890");


      interface A_Interface
         public void method1();
         public void method2();
      class My_Class implements A_Interface
        public void method1()
            System.out.println("implementation of method1");
        public void method2()
            System.out.println("implementation of method2");
        public static void main(String arg[])
            A_Interface obj = new XYZ();
            obj. method1();


      is a programming paradigm using "objects" – data structures consisting of data fields and methods together with their behaviors – to design applications and computer programs


      is a compact and informal high-level description of the operating principle of a computer program or other algorithm. It uses the structural conventions of a programming language, but is intended for human reading rather than machine reading.

    Singleton class

      public class CarParts {
          public static class Wheel {
              public Wheel() {
                  System.out.println("Wheel created!");
          private static CarParts() {
              System.out.println("Car Parts object created!");


      Designates a simple rectangle and displays the given text centered in the rectangle. The text is formatted before it is displayed. Words that would extend past the end of a line are automatically wrapped to the beginning of the next centered line.

    Static Class



      is a unique class or pattern that can be used to build other software code.

HOME] Consulting Design Maintenance Project Testing Training Turnkey Java C++ SQL HTML JavaScript C#

© 2002 - 2017 All Rights Reserved Total Application Works