Base Java Language Structure

We’ll cover the following

  • Class
  • Object
  • Package
  • Inheritance
  • Object as Superclass
  • Exception Handling in Java
  • Checked Exceptions
  • Runtime Exceptions

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 .java extension. 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.

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.

Package

Java groups classes into functional packages.

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 called in.codingtimes.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, codingtimes.in and in this example the Java packages of this company starts with in.codingtimes.

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 package xmlreader you can distinguish between these classes by using the fully qualified name, e.g, xmlreader.Test or report.Test.

Inheritance

A class can be derived from another class. In this case this class is called a subclass. 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 in.codingtimes.base;

class MyBaseClass {

    public void hello() {
        System.out.println("Hello from MyBaseClass");
    }
}
package in.codingtimes.base;

class MyExtensionClass extends MyBaseClass {
}

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

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

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.

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 is null.

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;
}

That’s it!
You have successfully completed the post. Do Share : )

Peace Out!

Also Read – Java Cheatsheet


Check Out Deals on -> Amazon , Flipkart , Myntra , Adidas , Apple TV , Boat , Canva , Beardo , Coursera , Cleartrip , Fiverr , MamaEarth , Swiggy, KFC


Leave a Reply

Your email address will not be published.