Part 20: Exceptions in Java with real time Example.

Part 20: Exceptions in Java with real time Example.

Java Exceptions

An exception or exceptional event is a problem. This is getting up during the execution of a program. When an Exception happens the normal flow of the program is disrupted and the program  terminates unusually. This is not recommended, consequently, these exceptions are to be handled.An exception can occur for many different reasons. where an exception occurs?

  • A user has entered an invalid data.
  • A file that needs to be opened cannot be found.
  • A network connection has been lost in the middle of communications or the JVM has run out of memory.
  • Some of these exceptions are caused by user error, others by programmer error, and others by physical resources that have failed in some manner.
  • Based on these, we have three categories of Exceptions. You need to understand them to know how exception handling works in Java.

Checked exceptions:

A checked exception is checked or notified by the compiler at compilation-time. These are also called as compile time exceptions. These exceptions cannot simply be ignored. The programmer should take care of (handle) these exceptions. For instance, if use FileReader class in your program to read data from a file, if the file specified in its constructor doesn’t exist, then a FileNotFoundException occurs, and the compiler prompts the programmer to handle the exception.

Example:

import java.io.File;

import java.io.FileReader;

public class Example {

   public static void main(String args[]) {               

      File file = new File("C://file.txt");

      FileReader fr = new FileReader(file);

   }

}

Output

C:\>javac Example.java

Example.java:8: error: unreported exception Example; must be caught or declared to be thrown

FileReader fr = new FileReader(file);                      ^

1 error

Note: Since the methods read() and close() of FileReader class throws IOException, detect the compiler informs to handle IOException, along with FileNotFoundException.

Unchecked exceptions:

An unchecked exception is an exception occurs at the time of execution. These are also called as Runtime Exceptions comprise programming bugs example as logic errors or improper use of an API. Runtime exceptions are ignored at the time of compilation. For sample, if declared an array of size 5 in your program, and trying to call the 6th element of the array then an ArrayIndexOutOfBoundsExceptionexception occurs.

Example

public class Example

{  

   public static void main(String args[]) {

      int number[] = {1, 2, 3, 4};

      System.out.println(number[5]);

   }

}

Output

Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: 5

at Example.main(Unchecked_Demo.java:8)

Errors:

These are not exceptions at all though problems that stand up beyond the control of the user or the programmer. Errors are typically ignored in code because programmer can rarely do anything about an error. For case, if a stack overflow occurs, an error will ascend. They are also ignored at the time of compilation.

Exception Hierarchy

All kind of exception classes are subtypes of the java.lang.Exception class. The exception class is a subclass of the Throwable class. Other than the exception class there is another subclass called Error which is derived from the Throwable class. Errors are irregular conditions that happen in case of severe failures, these are not handled by the Java programs. Errors are generated to indicate errors generated by the runtime environment. Example: JVM is out of memory. Normally, programs cannot recover from errors.

The Exception class has two main subclasses: IOException class and RuntimeException Class. A list of most common checked and unchecked Java’s Built-in Exceptions. Exceptions Methods:

Following is the list of important methods available in the Throwable class.

  • getMessage(): Returns a detailed message about the exception that has occurred. This message is initialized in the Throwable constructor.
  • Throwable getCause():Returns the cause of the exception as represented by a Throwable object.
  • toString():Returns the name of the class concatenated with the result of getMessage().
  • printStackTrace():Prints the result of toString() along with the stack trace to System.err, the error output stream.
  • StackTraceElement [] getStackTrace(): Returns an array containing each element on the stack trace. The element at index 0 represents the top of the call stack, and the last element in the array represents the method at the bottom of the call stack.
  • Throwable fillInStackTrace(): Fills the stack trace of this Throwable object with the current stack trace, adding to any previous information in the stack trace.

Catching Exceptions

A method catches an exception using a combination of the try and catch keywords. A try/catch block is placed around the code that might generate an exception. Code within a try/catch block is referred to as protected code, and the syntax for using try/catch looks like the following:

Syntax

try {

// Protected code

} catch (ExceptionName e1) {

// Catch block

}

The code which is likely to to exceptions is placed in the try block. When an exception occurs, that exception occurred is handled by catch block associated with it. Every try block should be immediately followed either by a catch block or finally block.

A catch statement involves declaring the type of exception you are trying to catch. If an exception occurs in protected code, the catch block (or blocks) that follows the try is checked. If the type of exception that occurred is listed in a catch block, the exception is passed to the catch block much as an argument is passed into a method parameter.

Example

// File Name : ExcepTest.java

import java.io.*;

public class ExcepExample

 {
   public static void main(String args[]) {

      try {

         int a[] = new int[2];

         System.out.println("Access element three :" + a[3]);

      } catch (ArrayIndexOutOfBoundsException e) {

         System.out.println("Exception thrown  :" + e);

      }

      System.out.println("Out of the block");

   }

}

Output

Exception thrown  :java.lang.ArrayIndexOutOfBoundsException: 3

Out of the block

Multiple Catch Blocks

A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks looks like the following:

Syntax

try {

// Protected code

} catch (ExceptionType1 e1) {

// Catch block

} catch (ExceptionType2 e2) {

// Catch block

} catch (ExceptionType3 e3) {

// Catch block

}

The previous statements demonstrate three catch blocks, though  can have any number of them after a single try. If an exception occurs in the protected code, the exception is thrown to the first catch block in the list. If the data type of the exception thrown matches ExceptionType1, it gets caught there. If not, the exception passes down to the second catch statement. This continues until the exception either is caught or falls through all catches, in which case the current method stops execution and the exception is thrown down to the previous method on the call stack.

Example

Here is code segment showing how to use multiple try/catch statements.

try {

file = new FileInputStream(fileName);

x = (byte) file.read();

} catch (IOException i) {

i.printStackTrace();

return -1;

} catch (FileNotFoundException f) // Not valid! {

f.printStackTrace();

return -1;

}

Catching Multiple Type of Exceptions

Since Java 7, you can handle more than one exception using a single catch block, this feature simplifies the code.

catch (IOException|FileNotFoundException example) {

logger.log(example);

throw example;

The Throws/Throw Keywords

If a method does not handle a checked exception, the method must declare it using the throws keyword. The throws keyword appears at the end of a method’s signature. To throw an exception, either a newly instantiated one or an exception that just caught, by using the throw keyword. There is some key to understand the difference between throws and throw keywords, throws is used to postpone the handling of a checked exception and throw is used to invoke an exception explicitly.

The following method declares that it throws a RemoteException :

Example

import java.io.*;

public class classExample {

   public void deposit(double amount) throws RemoteException {

      // Method implementation

      throw new RemoteException();

   }

   // Rest of class definition

}

A method can declare that it throws more than one exception, in which case the exceptions are declared in a list separated by commas. For illustration, the following method declares that it throws a RemoteException and an InsufficientFundsException:

Example

import java.io.*;

public class classExample {

   public void withdraw(double amount) throws RemoteException,

      InsufficientFundsException {

      // Method implementation

   }

   // Rest of class definition

}

The Finally Block

The finally block follows a try block or a catch block. A finally block of code always executes, irrespective of occurrence of an Exception.By means of a finally block allows you to run any cleanup-type statements that you want to execute, no matter what happens in the protected code. A finally block appears at the end of the catch blocks and has the following syntax:

try {

// Protected code

} catch (ExceptionType1 e1) {

// Catch block

} catch (ExceptionType2 e2) {

// Catch block

} catch (ExceptionType3 e3) {

// Catch block

}finally {

// The finally block always executes.

}

Example

public class classExample{

   public static void main(String args[]) {

      int a[] = new int[2];

      try {

         System.out.println("Access element three :" + a[3]);

      } catch (ArrayIndexOutOfBoundsException e) {

         System.out.println("Exception thrown  :" + e);

      }finally {

         a[0] = 6;

         System.out.println("First element value: " + a[0]);

         System.out.println("The finally statement is executed");

      }

   }

}

This will produce the following result −

Output

Exception thrown  :java.lang.ArrayIndexOutOfBoundsException: 3

First element value: 6

The finally statement is executed

Note : A catch clause cannot exist without a try statement.

  • It is not obligatory to have finally clauses whenever a try/catch block is present.
  • The try block cannot be present without either catch clause or finally clause.
  • Any code cannot be present in between the try, catch, finally blocks.

try-with-resources

To use any resources alike streams, connections, etc. need  to close them explicitly using finally block. In the following program, reading data from a file using FileReader and closing it using finally block.

Example

import java.io.File;

import java.io.FileReader;

import java.io.IOException;

public class ReadDataExample {

   public static void main(String args[]) {

      FileReader fr = null;           

      try {

         File file = new File("file.txt");

         fr = new FileReader(file); char [] a = new char[50];

         fr.read(a);   // reads the content to the array

         for(char c : a)

         System.out.print(c);   // prints the characters one by one

      } catch (IOException e) {

         e.printStackTrace();

      }finally {

         try {

            fr.close();

         } catch (IOException ex) {                  

            ex.printStackTrace();

         }

      }

   }

}

Try with resources mentioned as automatic resource management, is a new exception handling mechanism was introduced in Java 7. It is an automatically closes the resources used within the try catch block. To use this statement need to declare the required resources within the parenthesis, and the created resource will be closed automatically at the end of the block. Following is the syntax of Try with resources statement.

Syntax

try(FileReader fr = new FileReader("file path")) {

   // use the resource

   } catch () {

      // body of catch

   }

}

Following is the program that reads the data in a file using Try with resources statement.

Example

import java.io.FileReader;

import java.io.IOException;

public class TryExample {

   public static void main(String args[]) {

      try(FileReader fr = new FileReader("E://file.txt")) {

         char [] a = new char[50];

         fr.read(a);   // reads the contentto the array

         for(char c : a)

         System.out.print(c);   // prints the characters one by one

      } catch (IOException e) {

         e.printStackTrace();

      }

   }

}

Following points are to be kept in mind while working with try with resources statement. In order to use a class with try statement it should implement AutoCloseable interface and the close() method of it gets invoked automatically at runtime.It allows or can declare more than one class in try-with-resources statement.

While declare multiple classes in the try block of try with resources statement these classes are closed in reverse order. Except the declaration of resources within the parenthesis everything is the same as normal try/catch block of a try block. The resource declared in try gets instantiated just before the start of the try-block. The resource declared at the try block is implicitly declared as final.

User-defined Exceptions

To create your own exceptions in Java. All exceptions must be a child of Throwable. To write a checked exception that is automatically enforced by the Handle or Declare Rule, need to extend the Exception class. If want to write a runtime exception, need to extend the RuntimeException class.

define own Exception class as below :

class MyException extends Exception {

}

In order to extend the predefined Exception class to create your own Exception. These are considered to be checked exceptions. The following InsufficientFundsException class is a user-defined exception that extends the Exception class, making it a checked exception. An exception class is like any other class, containing useful fields and methods.

Example

// File Name ExceptionExample.java

import java.io.*;

public class InsufficientFundsException extends Exception {

   private double amount;

   public InsufficientFundsException(double amount) {

      this.amount = amount;

   }

   public double getAmount() {

      return amount;

   }

}

To demonstrate using own user-defined exception, the following CheckingAccount class contains a withdraw() method that throws an InsufficientFundsException.

// File Name CheckAccount.java

import java.io.*;
public class CheckAccount {

   private double balance;

   private int number;
   public CheckAccount (int number) {

      this.number = number;

   }

   public void deposit(double amount) {

      balance += amount;

   }


   public void withdraw(double amount) throws InsufficientFundsException {

      if(amount <= balance) {

         balance -= amount;

      }else {

         double needs = amount - balance;

         throw new InsufficientFundsException(needs);

      }

   }

   public double getBalance() {

      return balance;

   }

   public int getNumber() {

      return number;

   }

}

The following BankDemo program demonstrates invoking the deposit() and withdraw() methods of CheckAccount.

// File Name BankDemo.java

public class BankExample {

   public static void main(String [] args) {

      CheckingAccount cA = new CheckingAccount(101);

      System.out.println("Depositing $500...");

      cA.deposit(500.00);

      try {

         System.out.println("\n Withdrawing $100...");

         c.withdraw(100.00);

         System.out.println("\n Withdrawing $600...");

         c.withdraw(600.00);

      } catch (InsufficientFundsException e) {

         System.out.println(" Sorry !, but you are short $" + e.getAmount());

         e.printStackTrace();

      }

   }

}


Output

Depositing $500…

Withdrawing $100…

Withdrawing $600…

Sorry!, but you are short $200.0

InsufficientFundsException

at CheckingAccount.withdraw(CheckAccount.java:25)

at BankExample.main(BankDemo.java:13)

Common Exceptions: In Java, it is possible to define two catergories of Exceptions and Errors. Apart them, JVM Exceptions are exceptions/errors exclusively or logically thrown by the JVM. For Instances: NullPointerException, ArrayIndexOutOfBoundsException, ClassCastException. Another exceptions namely programmatic Exceptions. These exceptions are thrown explicitly by the application or the API programmers. Examples: IllegalArgumentException, IllegalStateException.

Part 20: Exceptions in Java with real time Example.

Part 8: Java Polymorphism with its real time example code.

Java Polymorphism

Polymorphism means “many forms”, It is useful for code reusability: reuse attributes and methods of an existing class when you create a new class. It occurs when we have many classes that are related to each other by inheritance. Like we definite in the previous chapter; Inheritance lets us inherit attributes and methods from another class. Polymorphism uses those methods to perform different tasks. This allows us to perform a single action in diverse ways.

For example, think of a superclass called Tree that has a method called treeSound(). Subclasses of Tree could be SmallTree, MidSizeTree.  And they also have their own implementation of an tree sound:

Example
class Tree {
public void treeSound() {
System.out.println(“The tree makes a sound in wind”);
}
}
class SmallTree extends Tree {
public void treeSound() {
System.out.println(“The SmallTree can also makes a sound in wind”);
}
}
class MidSizeTree extends c {
public void treeSound() {
System.out.println(“The MidSizeTree can also makes a sound in wind”);
}
}

Remember from the Inheritance chapter that we use the extends keyword to inherit from a class.Now we can create Pig and Dog objects and call the animalSound() method on both of them:

Example
class Tree {
public void treeSound() {
System.out.println(“The tree makes a sound in wind”);
}
}
class SmallTree extends Tree {
public void treeSound() {
System.out.println(“The SmallTree can also makes a sound in wind”);
}
}

class MidSizeTree extends c {
public void treeSound() {
System.out.println(“The MidSizeTree can also makes a sound in wind”);
}
}
class Main {
public static void main(String[] args) {
Tree myTree = new Tree(); // create Tree obj
Tree mySmall = new SmallTree();// create SmallTree obj
Tree myMidSize = new MidSizeTree();// create MidSizeTree obj
myTree.treeSound();
mySmall.treeSound();
mymyMidSize.treeSound();
}
}

OUTPUT

The tree makes a sound in wind
The SmallTree makes a sound in wind
The MidSizeTree can also makes a sound in wind

Part 20: Exceptions in Java with real time Example.

Part 7: Java Inheritance with real time example

Java Inheritance

Subclass and Superclass contains in inheritance mainly. In Java, it is possible to inherit attributes and methods from one class to another.  It contains of two categories:

subclass (child) – the class that inherits from another class

superclass (parent) – the class being inherited from

To inherit from a class, use the extends keyword. In the example below, the Car class (subclass) inherits the attributes and methods from the Vehicle class (superclass):

Example

class Tree {
protected String leavesColor = “Green”;        // attribute
public void branch() {                    // method
System.out.println(“Tree !”);
}
}
class Fruits extends Tree {
private String fruitsName = “Mango”;    // attribute
public static void main(String[] args) {
// Create a myFruit object
Fruits myFruits = new Fruits();
// Call the () method (from the Vehicle class) on the myCar object
myFruits.branch ();
// Display the value of the brand attribute (from the Tree class) and the value of the fruitsName from the Fruits class
System.out.println(myFruits.branch + ” ” + myCar.fruitsName);
}
}

Did you notice the protected modifier in Vehicle? Here, set the brance attribute in Tree to a protected access modifier. If it was set to private, the Fruits class would not be able to access it. Why and when to Use “Inheritance”? It is useful for code reusability: reuse attributes and methods of an existing class when you create a new class.

The final Keyword

If you don’t want other classes to inherit from a class, use the final keyword:
If you try to access a final class, Java will generate an error:

final class Tree {

}
class Fruits extends Tree {

}
The output will be something like this:

Main.java:9: error: cannot inherit from final Tree
class Main extends Tree {
^
1 error)

Java inheritance refers to the capability in Java for one class to inherit from another class. In Java this is also called extending a class. One class can extend another class and thereby inherit from that class. When one class inherits from another class in Java, the two classes take on certain roles. The class that extends (inherits from another class) is the subclass and the class that is being extended (the class being inherited from) is the superclass. In other words, the subclass extends the superclass. Or, the subclass inherits from the superclass. Another commonly used term for inheritance is specialization and generalization. A subclass is a specialization of a superclass, and a superclass is a generalization of one or more subclasses.

Inheritance is a Method of Code Reuse:  Inheritance can be an effective method to share code between classes that have some traits in common, yet allowing the classes to have some parts that are different.

Class Hierarchies

In java, Superclasses and subclasses form an inheritance structure which is also called a class hierarchy. At the top of the class hierarchy you have the superclasses. At the bottom of the class hierarchy you have the subclasses. A class hierarchy may have multiple levels, meaning multiple levels of superclasses and subclasses. A subclass may itself be a superclass of other subclasses etc.

Java Inheritance Basics

When a class inherits from a superclass, it inherits parts of the superclass methods and fields. The subclass can also override (redefine) the inherited methods. Fields cannot be overridden, but can be “shadowed” in subclasses. How all this works is covered later in this text.

What is Inherited?

When a subclass extends a superclass in Java, all protected and public fields and methods of the superclass are inherited by the subclass. By inherited is meant that these fields and methods are part of of the subclass, as if the subclass had declared them itself. protected and public fields can be called and referenced just like the methods declared directly in the subclass.

Fields and methods with default (package) access modifiers can be accessed by subclasses only if the subclass is located in the same package as the superclass. Private fields and methods of the superclass can never be referenced directly by subclasses. They can, however, be referenced indirectly via methods reachable from the subclass e.g default (package), protected and public methods. Constructors are not inherited by subclasses, but a subclass constructor must call a constructor in the superclass. This will be explained in detail in a later section.

Java Only Supports Singular Inheritance

The Java inheritance mechanism only allows a Java class to inherit from a single superclass (singular inheritance). In some programming languages, like C++, it is possible for a subclass to inherit from multiple superclasses (multiple inheritance). Since multiple inheritance can create some weird problems, if e.g., the superclasses contain methods with the same names and parameters, multiple inheritance was left out in Java.

Declaring Inheritance in Java

In Java inheritance is declared using the extends keyword. You declare that one class extends another class by using the extends keyword in the class definition. Here is Java inheritance example using the extends keyword:

public class Tree {
protected String color = null;
public void colorSet (String colors) {
this.color = colors;
}
}
public class Fruits extends Tree {
int numberOftree = 0;
public String getNumberOftree() {
return this. numberOftree;
}
}

The Fruits class in this example extends the Tree class, meaning the Fruits class inherits from the Tree class. Because the Fruits class extends the Tree class, the protected field numberOftree from the Tree class is inherited by the Fruits class. When the numberOftree field is inherited, it is accessible inside a Fruits instance. The numberOftree field is not actually being referenced from the Fruits class in the code above, but it could if we wanted to. Here is an example that shows how that could look:

public class Fruits extends Tree {
int numberOftree = 0;
public String getNumberOfTrees() {
return this. numberOftree;
}
public String getnumberOftrees () {
return this.numberOftree;
}
}

The referencing happens inside the getnumberOftree () method. In many cases it would have made sense to place the getnumberOftree () method in the Tree class where the numberOftree field is located. I just placed the getnumberOftree () method in the Fruits class to show that it is possible.

Inheritance and Type Casting

It is possible to reference a subclass as an instance of one of its superclasses. For instance, using the class definitions from the example in the previous section it is possible to reference an instance of the Fruits class as an instance of the Tree class. Because the Fruits class extends (inherits from) the Tree class, it is also said to be a Tree. Here is a Java code example:

Fruits    f     = new Fruits ();
Tree tree = f;

First a Fruits  instance is created. Second, the Fruits  instance is assigned to a variable of type Tree. Now the Tree variable (reference) points to the Fruits  instance. This is possible because the Fruits class inherits from the Tree class.Because, it is possible to use an instance of some subclass as if it were an instance of its superclass. That way, you don’t need to know exactly what subclass the object is an instance of. You could treat e.g. Fruits instances as Tree instances.

The process of referencing an object of class as a different type than the class itself is called type casting. You cast an object from one type to another.

Upcasting and Downcasting

You can always cast an object of a subclass to one of its superclasses. This is referred to as upcasting (from a subclass type to a superclass type).

It may also be possible to cast an object from a superclass type to a subclass type, but only if the object really is an instance of that subclass (or an instance of a subclass of that subclass). This is referred to as downcasting (from a superclass type to a subclass type). Thus, this example of downcasting is valid:

Fruits    f     = new Fruits ();
// upcast to Tree
Tree tree = f;
// downcast to f again
Fruits    f     = (Fruits)tree;

However, the following downcast example is not valid. The Java compiler will accept it, but at runtime when this code is executed the code will throw a ClassCastException.

Truck   truck   = new Truck();
// upcast to Tree
Tree tree = truck;
// downcast to f again
Fruits    f     = (Fruits) tree;

The Truck object can be upcast to a Tree object, but it cannot be downcast to a Fruits object later. This will result in a ClassCastException.

Overriding Methods

In a subclass you can override or redefine the methods defined in the superclass. Here is a Java method override example:
public class Tree {
String treePlate = null;
public void setLicensePlate(String treePlate) {
this. treePlate = treePlate;
}
}
public class Fruits extends Tree {
public void settreePlate (String treeP) {
this.treePlate = treeP.toLowerCase();
}
}

Notice how both the Vehicle class and the Car class defines a method called settreePlate (). Now, whenever the settreePlate () method is called on a Fruits object, it is the method defined in the Fruits class that is called. The method in the superclass is ignored.

To override a method the method signature in the subclass must be the same as in the superclass. That means that the method definition in the subclass must have exactly the same name and the same number and type of parameters, and the parameters must be listed in the exact same sequence as in the superclass. Otherwise the method in the subclass will be considered a separate method.

In Java you cannot override private methods from a superclass. If the superclass calls a private method internally from some other method, it will continue to call that method from the superclass, even if you create a private method in the subclass with the same signature.

The @override Annotation

If you override a method in a subclass, and the method is accidently removed or modified in the superclass, the method in the subclass no longer overrides the method in the superclass. But how do you know? It would be nice if the compiler could tell you that the method being overridden no longer overrides a method in the superclass, right?

This is what the Java @override annotation is for. You place the Java @override annotation above the method that overrides a method in a superclass. Here is Java @override example:

public class Fruits extends Tree {
@Override
public void settreePlate (String treeP) {
this.treePlate= treeP.toLowerCase();
}
}

Calling Superclass Methods

If you override a method in a subclass, but still need to call the method defined in the superclass, you can do so using the super reference, like this:

public class Fruits extends Tree {
public void settreePlate (String treeP) {
super.settreePlate (treeP);
}
}

In the above code example the method settreePlate() in the Car class, calls the settreePlate() method in the Tree class. You can call superclass implementations from any method in a subclass, like above. It does not have to be from the overridden method itself. For instance, you could also have called super.treePlate() from a method in the Car class called updatetreePlate() which does not override the settreePlate() method.

The instanceof Instruction

Java contains an instruction named instanceof. The instanceof instruction can determine whether a given object is an instance of some class. Here is a Java instanceof example:

Fruits f = new Fruits ();
boolean isFruits = f instanceof Fruits;

After this code has been executed the isFruits variable will contain the value true.
The instanceof instruction can also be used determine if an object is a instance of a superclass of its class. Here is an instanceof example that checks if a Car object is an instance of Vehicle:

Fruits f = new Fruits ();
boolean isTree = f instanceof Tree;

Assuming that the Fruits class extends (inherits from) the Tree class, the isTree variable will contain the value true after this code is executed. A Fruits object is also a Tree object because Fruits is a subclass of Vehicle.
As you can see, the instanceof instruction can be used to explore the inheritance hierarchy. The variable type used with the instanceof instruction does not affect its outcome. Look at this instanceof example:

Fruits f = new Fruits ();
Tree tree = f;
boolean isFruits  = tree instanceof Fruits;

Even though the tree variable is of type Tree, the object it ends up pointing to in this example is a Fruits object. Therefore the tree instanceof Fruits instruction will evaluate to true. Here is the same instanceof example, but using a Truck object instead of a Fruits object:

Truck truck = new Truck();
Tree tree = truck;
boolean isFruits = tree instanceof Fruits;

After executing this code the isFruits will contain the value false. The Truck object is not a Fruits object.

Fields and Inheritance

As mentioned earlier, in Java fields cannot be overridden in a subclass. If you define a field in a subclass with the same name as a field in the superclass, the field in the subclass will hide (shadow) the field in the superclass. If the subclass tries to access the field, it will access the field in the subclass. If, however, the subclass calls up into a method in the superclass, and that method accesses the field with the same name as in the subclass, it is the field in the superclass that is accessed. Here is Java inheritance example that illustrates how fields in subclasses shadow (hides) fields in superclasses:

public class Fruits extends Tree {
int numberOftree = 0;
public String getNumberOfTrees() {
return this. numberOftree;
}
public String getnumberOftrees () {
return this.numberOftree;
}
}
public class Tree {
String treeP = null;
public void settreeP(String treePlate) {
this. treePlate = treePlate;
}
public String getTreeP() {
return treeP;
}
}
public class Fruits extends Tree {
protected String treeP = null;
@Override
public void setTreeP(String tp) {
super.setTreeP(tp);
}
@Override
public String getTreeP () {
return super.getTreeP();
}
public void updateTreeP(String tp){
this.TreeP = tp;
}
}

Notice how both classes have a TreeP field defined. Both the Tree class and Fruits class has the methods setTreeP() and getTreeP(). The methods in the Fruits class calls the corresponding methods in the Tree class. The result is, that eventually both set of methods access the treeP field in the Tree class.

The updateTreeP() method in the Car class however, accesses the treeP field directly. Thus, it accesses the treeP field of the Fruits class. Therefore, you will not get the same result if you call setTreeP() as when you call the updateTree() method.

Look at the following lines of Java code:
Fruits f = new Fruits ();
f.setTreeP(“123”);

car.updateTreeP(“abc”);

System.out.println(“tree p: ” + f.getTreeP ());

This Java code will print out the text 123.

The updateTreeP () method sets the license plate value on the TreeP field in the Fruits class. The getTreeP() method, however, returns the value of the TreeP field in the Tree class. Therefore, the value 123 which is set as value for the TreeP field in the Vehicle class via the setTreeP() method, is what is printed out.

Constructors and Inheritance

The Java inheritance mechanism does not include constructors. In other words, constructors of a superclass are not inherited by subclasses. Subclasses can still call the constructors in the superclass using the super() contruct. In fact, a subclass constructor is required to call one of the constructors in the superclass as the very first action inside the constructor body. Here is how that looks:

public class Tree {
public Tree() {
}
}
public class Fruits extends Tree{
public Fruits() {
super();
//perform other initialization here
}
}

Notice the call to super() inside the Car constructor. This super() call executes the constructor in the Vehicle class. You may have seen Java classes where the subclass constructors did not seem to call the constructors in the superclass. Maybe the superclass did not even have a constructor. However, the subclass constructors have still called superclass constructors in those case. You just could not see it. Let me explain why: If a class does not have any explicit constructor defined, the Java compiler inserts an implicit non arg constructor. Thus, a class always has a constructor. Therefore, the following version of Vehicle is equivalent to the version shown just above:
public class Tree {

}

Second, if a constructor does not explicitly call a constructor in the superclass, the Java compiler inserts an implicit call to the no-arg constructor in the superclass. That means that the following version of the Car class is actually equivalent to the version shown earlier:
public class Fruits extends Tree {
public Fruits () {
}
}

In fact, since the constructor is now empty, we could leave it out and the Java compiler would insert it, and insert an implicit call to the non arg constructor in the superclass. This is how the two classes would look then:
public class Tree {

}

public class Fruits extends Tree{

}

Even though no constructors are declared in these two classes, they both get a no-arg constructor, and the no-arg constructor in the Fruits class will call the no-arg constructor in the Vehicle class.

If the Tree class did not have a no-arg constructor, but had another constructor which takes parameters, the Java compiler would complain. The Fruits class would then be required to declare a constructor, and inside that constructor call the constructor in the Vehicle class.

Nested Classes and Inheritance

The same Java inheritance rules apply to nested classes. Nested classes which are declared private are not inherited. Nested classes with the default (package) access modifier are only accessible to subclasses if the subclass is located in the same package as the superclass. Nested classes with the protected or public access modifier are always inherited by subclasses.

Here is a nested class inheritance example:
class FruitsClass {
class MyFruitsClass {
}
}

public class MyFruitsSubclass extends MyFruitsClass {
public static void main(String[] args) {
MyFruitsSubclass subclass = new MyFruitsSubclass();
MyFruitsClass nested =  subclass.new MyFruitsClass ();
}
}

Notice how it is possible to create an instance of the nested class MyFruitsClass which is defined in the superclass (MyFruitsClass) via a reference to the subclass (MyFruitsSubclass). Final Classes and Inheritanc. A class can be declared final. Here is now that looks:
public final class MyFruitsClass {
}

A final class cannot be extended. In other words, you cannot inherit from a final class in Java.

Part 20: Exceptions in Java with real time Example.

Part 5: Encapsulation in Java with real-time example

What is OOP in Java?

OOP (Object oriented programming) refers to a programming methodology based on objects instead of just functions and procedures. In this blog, guide how to do encapsulation in java program.

What are the main feature of OOP?

  • Encapsulation:

Encapsulation is Combination of data and function in a single unit.  This is use to hide the implementation details from user. That is why is also known as “data Hiding“ for this hiding approach. The main method for data invoke is setter and getter method.

  • Inheritance:

Inheritance is a process by which object of any class have access of other classes data and  methods or all the properties. It is a mechanism in which one object acquires all the properties and behaviors of a parent object. Derived class known as child class. The class that inherits from another class · The base class namely parent class. In the class being inherited from.

  • Polymorphism :

Polymorphism refers the ability to take more than one form. And the most common use of polymorphism in OOP is, when a parent class reference is used to refer to a child class object.  Any Java object that can pass more than one is considered to be polymorphic.

  • Abstraction :

Abstraction in OOP able to  hides implementation details in class. It can also be referred to as modeling and is nearly conjuncted to the ideas of theory and design.

Now discuss about Encapsulation in java:

Encapsulation( known as data hiding) is a mechanism of wrapping the variables and methods together as a single unit. No outside class can access private data member or variable of other class. That is variables of a class hidden from other classes. In order to invoke that variable and method, one can be accessed only through the getter setter methods provided by current class. This way data can only be accessed by public methods thus making the private fields and their implementation hidden for other classes.
Encapsulation achieve −

  1. Declare the variables of a class as private.
  2. Provide getter and setter methods in public (modify and view the data values).
  3. Java encapsulation keep related fields and methods together in order to easy to code and read.

It control the values of data fields.

For example,
class Encap{
private int counts;

public void setCounts(int counts) {
if (counts >= 0) {
this.counts = counts;
}
}
}

Here, counts variable private and applying logic inside the setCounts() method. Can be achieved data hiding using encapsulation. In the above example, if change the length and breadth variable into private, then the access to these fields is restricted.

Following is an example of Encapsulation in Java :

public class MySelf
{
private String name;
private String deptName;
private int age;

public String getName()
{
return name;
}
public String getdeptName()
{
return deptNamename;
}
public int getAge() {
return age;
}

public void setName(String name)
{
this.name = name;
}
public void setdeptName(String dName)
{
this.dName = dName;
}
public void setAge(int age)
{
this.age = age;
}

}

Following MySelf class, if any class wants to access the variables(Name,Age,deptName) should access them through these getters(i.e getName() ,getdName(),getAge()) and setters(i.e setName(),setdName(),setAge()).

The variables of the MySelf class can be accessed using the following program −
public class UseMySelfClass
{
public static void main(String args[])
{
MySelf myself= new MySelf ();
myself.setName(“Harun”);
myself.setdeptName(“ICE”);
myself.setAge(22);

System.out.print(“Name : ” + myself.getName());
System.out.print(“Dept-Name : ” + myself.getdeptName());
System.out.print(” Age : ” + myself.getAge());
}
}

This will produce the following result −

Output

Name : Hello

Dept-Name : ICE

ICE Age : 22

Advantages of encapsulation:

Encapsulation use improves flexibility and re-usability. For instance, In the above  implemented code of void setName(String name) ,void setAge(int age) and setdeptName(String dName) can be changed at any point of time. Since the implementation is wholy hidden for other classes, yet they would still  access the private field Name using the same methods (setName(String name) and getName()). Therefore, the code can be maintained at any point of time without breaking the classes that uses the code. This improves the re-usability of the class.

The fields can be made read-only, if don’t define setter methods in the class. In other saying, field can be write-only, if don’t define the getter methods in the class, such as,

getName() // provides read-only access
setName() // provides write-only access

Example, If class have only a field or variable that  don’t want to be changed, simply define the variable as private and instead of setter, getter. Both just need to define the get method for that variable. As the set method is not present there is no way an outside class can modify the value of that field.

User would know update a field by calling set method and to read a field call get method. set and get methods activity hidden from user.

See more Topic on Java OOP with real-time example

Nested class in JAVA with EXAMPLES

What is the defference between String, StringBuffer and StringBuilder.

Java Interface tutorials with Example.

JAVA abstract class with EXAMPLES

What Does Method Signature Mean in Java?