Base Java language structure

 


4. Base Java language structure

4.1. Class

A class is a template that describes the data and behavior associated with an instance of that class.

A class is defined by the class keyword and must start with a capital letter. The body of a class is surrounded by {}.

package test;

class MyClass {

}

The data associated with a class is stored in variables ; the behavior associated to a class or object is implemented with methods.

A class is contained in a text file with the same name as the class plus the .javaextension. It is also possible to define inner classes, these are classes defined within another class, in this case you do not need a separate file for this class.

4.2. Object

An object is an instance of a class.

The object is the real element which has data and can perform actions. Each object is created based on the class definition. The class can be seen as the blueprint of an object, i.e., it describes how an object is created.

4.3. Package

Java groups classes into functionalpackages.

Packages are typically used to group classes into logical units. For example, all graphical views of an application might be placed in the same package calledcom.vogella.webapplication.views.

It is common practice to use the reverse domain name of the company as top level package. For example, the company might own the domain, vogella.com and in this example the Java packages of this company starts withcom.vogella.

Other main reason for the usage of packages is to avoid name collisions of classes. A name collision occurs if two programmers give the same fully qualified name to a class. The fully qualified name of a class in Java consists of the package name followed by a dot (.) and the class name.

Without packages, a programmer may create a Java class called Test. Another programmer may create a class with the same name. With the usage of packages you can tell the system which class to call. For example, if the first programmer puts the Test class into package report and the second programmer puts his class into packagexmlreader you can distinguish between these classes by using the fully qualified name, e.g, xmlreader.Test orreport.Test.

4.4. Inheritance

A class can be derived from another class. In this case this class is called asubclass. Another common phrase is that a class extends another class.

The class from which the subclass is derived is called a superclass.

Inheritance allows a class to inherit the behavior and data definitions of another class.

The following codes demonstrates how a class can extend another class. In Java a class can only extend a maximum of one class.

package com.vogella.javaintro.base;

class MyBaseClass {

    public void hello() {
        System.out.println("Hello from MyBaseClass");
    }
}
package com.vogella.javaintro.base;

class MyExtensionClass extends MyBaseClass {
}

4.5. Object as superclass

Every object in Java implicitly extends the Object class. The class defines the following methods for every Java object:

  • equals(o1) allows checking if the current object is equal to o1

  • getClass() returns the class of the object

  • hashCode() returns an identifier of the current object

  • toString() gives a string representation of the current object

4.6. Exception handling in Java

In Java an exception is an event to indicate an error during the runtime of an application. So this disrupts the usual flow of the application’s instructions.

In general exceptions are thrown up in the call hierarchy until they get catched.

exception throw callstack

4.7. Checked Exceptions

Checked Exceptions are explicitly thrown by methods, which might cause the exception or re-thrown by methods in case a thrown Exception is not caught.

So when calling methods, which throw checked Exceptions the Exceptions have either to be caught or to be re-thrown.

public void fileNotFoundExceptionIsCaughtInside() {
    try {
        createFileReader();
    } catch (FileNotFoundException e) {
        logger.error(e.getMessage(), e);
    }
}

public void fileNotFoundExceptionIsReThrown() throws FileNotFoundException {
    createFileReader();
}

public void createFileReader() throws FileNotFoundException {
    File file = new File("/home/Documents/JavaTraining.txt");

    // creating a new FileReader can cause a FileNotFoundException
    new FileReader(file);
}

Checked Exceptions are used when an error can be predicted under certain circumstances, e.g., a file which cannot be found.

4.8. Runtime Exceptions

Runtime Exceptions are Exceptions, which are not explicitly mentioned in the method signature and therefore also do not have to be catched explicitly.

The most famous runtime exception is the NullPointerException, which occurs during runtime, when a method is invoked on an object, which actually isnull.

public void causeANullPointerException() {
    String thisStringIsNull = getMessage(false);

    // because the thisStringIsNull object is null
    // this will cause a NullPointerException
    thisStringIsNull.toLowerCase();
}

public String getMessage(boolean messageIsAvailable) {
    if(messageIsAvailable) {
        return message;
    }

    return null;
}

Comments

Popular posts from this blog

How to Hack WhatsApp Chats

Installation of Java

Integrated Development Environment