Wednesday, June 16, 2021

Java OOPs: Encapsulation

Chapter

Java Encapsulation

Encapsulation is the process of wrapping data into a single unit. We can think of encapsulation as a multivitamins capsule. Multivitamins has lots of various vitamins packed in a single capsule.

By using encapsulation, we can achieve data hiding, as the name implies, data hiding is the process of hiding certain data. It can also help us manage and control data for security and flexibility.

Most of the time, we use setters and getters to handle data that comes in and out. Getters and setters are methods that set or get data. For convenience, we name those methods with a prefix "get" for getters and "set" for setters. This example demonstrates encapsulation.

//This class encapsulates main method
public class SampleClass{
   
  
  public static void main(String[]args){
  
   PersonnalInfo myInfo = new PersonnalInfo("B.Ghosts",
                              "123456","246810","Programming");
   System.out.println();
   
   System.out.println("Name: " + myInfo.getName());
   System.out.println("Getting Public Key...");
   System.out.println("Public Key: " + myInfo.getPublicKey());
   System.out.println("Getting Hobby...");
   System.out.println("Hobby: " + myInfo.getHobby());
   System.out.println();
   
   System.out.println("Setting new public key...");
   myInfo.setPublicKey("246810","654321");
   System.out.println("Getting Public Key...");
   System.out.println("Public Key: " + myInfo.getPublicKey());
   System.out.println("Setting hobby...");
   myInfo.setHobby("Playing Games");
   System.out.println("Hobby is set!");
   System.out.println("Getting Hobby...");
   System.out.println("Hobby: " + myInfo.getHobby());
   
  }
}

//This class encapsulates fields(variables),
//methods, etc.
final class PersonnalInfo{
  //If we don't want anyone to
  //directly access class fields
  //then make them private.
  private String name;
  private String publicKey;
  private String privateKey;
  private String hobby;
  
   PersonnalInfo(String name,String publicKey,String privateKey,
                 String hobby){
    
    System.out.println("Creating personnal information of "
                       + name);
    this.name = name;
    System.out.println("Locking public key...");
    this.publicKey = lockKey(publicKey);
    System.out.println("Locking private key...");
    this.privateKey = lockKey(privateKey);
    this.hobby = hobby;
    System.out.println(name + " personnal information has been"+
                       +" created!");
  }
  
  //getters
  public String getName(){ return name; }
  public String getPublicKey(){ return unlockKey(publicKey); }
  public String getHobby(){ return hobby; }
  
  //setters
  public void setPublicKey(String privateKey,String newKey){
   
    if(unlockKey(privateKey).equals(this.privateKey)){
      System.out.println("Private key is matched with"
                        +" the current private key!");
      System.out.println("Changing current public key with"
                         +" the new one...");
      publicKey = lockKey(newKey);
      System.out.println("Public key has been changed"+
                         " successfully!");
    }
    else
      System.out.println("Private key doesn't match the"
                         +" current private key.");
    
  }
  public void setHobby(String hobby){
    this.hobby = hobby;
  }
  
  
  //extra methods for securty
  private String lockKey(String key){
     System.out.println("Verifying Key...");
     System.out.println("Key Signature is valid!");
     System.out.println("Locking Key...");
     System.out.println("Key Locked!");
     return key;
  }
  
  private String unlockKey(String key){
    System.out.println("Unlocking Current Key...");
    System.out.println("Key Unlocked!");
    return key;
  }
}
In the above example, we can set or get data in the class by using getters and setters method. We can see that the variables are more secure because users can't just change the variable values directly. They are required to use the methods that the class provided in order to manipulate data in the class.

Tuesday, June 15, 2021

Java Tutorial: Interface

Chapters

Java Interface

Note: Understanding of inheritance is required to understand this topic.
If a class is the blueprint of an object then interface is the blueprint of a class. Some folks call interface as "meta-class". Like standard class, interface can use the this and super keyword. Interface is a special type of class in java. Interface, like abstract class, provides abstraction. Let's create an example to demonstrate interface.
public class SampleClass{

  public static void main(String[]args){
  
    MyTV myTV = new MyTV();
    myTV.power();
    myTV.adjustLight(10);
  }
}

//interface
interface Controls{
  //interface variables, they're
  //default public and final
  //public and final keywords
  //can be omitted in interface
  //variables
  int LIGHT_LVL = 100;
  boolean POWER_STATE = true;
  
  //interface methods, they're
  //default public and abstract
  //the abstract and public
  //keywords can be omitted in
  //interface methods
  void adjustLight(int level);
  void power();
}

//use the implements keyword to implement
//an interface to a class
class MyTV implements Controls{
  private int lightLvl;
  private boolean isOff;
  
  MyTV(){
    lightLvl = LIGHT_LVL;
    isOff = POWER_STATE;
  }
  
  @Override
  public void adjustLight(int level){
  
    if(isOff){
      System.out.println("Can't adjust brightness because "+
                         "TV is off...");
      return;
    }
  
    System.out.println("Current brightness: "
                       + lightLvl + "%");
    System.out.println("Adjusting brightness by: "
                       + level + "%");
    lightLvl -= level;
    if(lightLvl < 0)
       lightLvl = 0;
    
    System.out.println("Current brightness: "
                       + lightLvl + "%");
  }
  
  @Override
  public void power(){
    if(isOff){
      isOff = false;
      System.out.println("power is on...");
    }
    else{
      isOff = true;
      System.out.println("power is off...");
    }
      
  }
}
Variables that are declared in an interface are implicitly public,static and final; Methods that are declared in an interface are implicitly public and abstract. public,static and final can be omitted in interface variables; abstract and public can be omitted in interface methods.

Once a class implements an interface with abstract methods, that class needs to define those abstract methods. Don't forget to follow the rules of method overriding when overriding an abstract method.

Differences Between Abstract Class and Interface

Abstract class and interface are used to achieve abstraction. Though, these two have differences:

1.) Abstract class fields can be final or non-final at the discretion of programmers whereas interface fields are final by default.

2.) Abstract class fields can be static or non-static at the discretion of programmers whereas interface fields are static by default.

3.) Abstract class fields can have different access modifier whereas interface fields are public by default.

4.) abstract keyword can be omitted in abstract methods in interface whereas abstract methods in abstract class need to explicitly include the abstract keyword.

5.) Abstract class has constructor whereas interface doesn't.

6.) Interface can have default methods whereas abstract class can't.

When To Use Interface And Abstract Class

1.) If you want to achieve full abstraction where all methods are abstract or close to full abstraction then, it's preferrable to use interface due to its properties. If you want to achieve partial abstraction then, it's preferrable to use abstract class.

2.) You may wanna use interface if you're building a complex abstraction. We can take advatange of java's multiple inheritance support to interfaces to create a complex type of abstraction.

3.) If you want your fields to have different access modifiers or you want to mix final and non-final fields then, use abstract class.

4.) Use interface if you want an implementation that can be used by any class in your project.

Inheritance Between Interfaces

We can use the extends keyword to subclass an interface by another interface. However, unlike in classes, a parent interface can subclass multiple interfaces by using a comma-separated list.
public class SampleClass{

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

interface SystemMenuDefaults{
  String SCAN_INTERLACE = "Interlace";
  String SCAN_PROGRESSIVE = "Progressive";
}

interface ScreenControls{

  void adjustResolution();
  void scanMode(String scanType);
}

//an interface extending one interface
interface PeripheralControls extends ScreenControls{

  void moveUpAlternative();
  void moveDownAlternative();
}

//an interface extending two interfaces
interface SystemMenu extends SystemMenuDefaults,PeripheralControls{

  void screenRelatedMenu(int option);
}

interface Controls extends SystemMenu{
  int LIGHT_LVL = 100;
  boolean POWER_STATE = true;
  
  void adjustLight(int level);
  void power();
}

//The implementing class must implement
//the abstract methods of parent interface
//and its sub interfaces
class MyTV implements Controls{
  
  @Override
  public void adjustLight(int level){}
  @Override
  public void power(){}
  @Override
  public void screenRelatedMenu(int option){}
  @Override
  public void moveUpAlternative(){}
  @Override
  public void moveDownAlternative(){}
  @Override
  public void adjustResolution(){}
  @Override
  public void scanMode(String scanType){}
  
}
In the above example, we see that an interface can extend multiple interfaces. If a class implements a sub interface with parent interfaces then the class must define the abstract methods of the sub interface and its parent interfaces.

Inheritance Between Class And Interface

If we want a class to inherit an interface we use the implements keyword. Java supports multiple inheritance in interface. Thus, a class can inherit multiple interfaces using the implements keyword.
public class SampleClass{

  public static void main(String[]args){
  
    MyTV myTV = new MyTV();
    myTV.power();
    myTV.adjustLight(10);
  }
}

interface ControlsDefaults{
  int LIGHT_LVL = 100;
  boolean POWER_STATE = true;
}
  
interface Controls{
  
  void adjustLight(int level);
  void power();
}

//class implementing multiple interfaces using
//comma-separated list
class MyTV implements ControlsDefaults,Controls{
  private int lightLvl;
  private boolean isOff;
  
  MyTV(){
    lightLvl = LIGHT_LVL;
    isOff = POWER_STATE;
  }
  
  @Override
  public void adjustLight(int level){
  
    if(isOff){
      System.out.println("Can't adjust brightness because "+
                         "TV is off...");
      return;
    }
  
    System.out.println("Current brightness: "
                       + lightLvl + "%");
    System.out.println("Adjusting brightness by: "
                       + level + "%");
    lightLvl -= level;
    if(lightLvl < 0)
       lightLvl = 0;
    
    System.out.println("Current brightness: "
                       + lightLvl + "%");
  }
  
  @Override
  public void power(){
    if(isOff){
      isOff = false;
      System.out.println("power is on...");
    }
    else{
      isOff = true;
      System.out.println("power is off...");
    }
      
  }
}
Note: A class can inherilt an interface but an interface can't inherit a class.

To resolve shadowing of variables between interfaces, we can add their interfaces names everytime we access them from the implementing class.
public class SampleClass{

  public static void main(String[]args){
    ClassA classA = new ClassA();
  }
  
}

interface InterfaceA{
  String NAME = "InterfaceA";
}

interface InterfaceB{
  String NAME = "InterfaceB";
}

class ClassA implements InterfaceA,InterfaceB{
  
  ClassA(){
    System.out.println(InterfaceA.NAME);
    System.out.println(InterfaceB.NAME);
  }
}
Ambiguous Inheritance

1.) If a super interface and its sub interface have the same method then, the implementing class only needs to override the identical methods once. This also applies to implementing class with multiple super interfaces with identical methods.
public class SampleClass{

  public static void main(String[]args){
    ClassA classA = new ClassA();
  }
}

interface InterfaceA{

  void message();
}

interface InterfaceB extends InterfaceA{

  void message();
}

class ClassA implements InterfaceB{

  @Override
  public void message(){
    System.out.println("ClassA");
  }
  
  ClassA(){
    message();
  }
}
2.) If the implementing class has super class, super interfaces and their super interfaces and they have identical methods then, the implementing class won't be required to override the methods in the interfaces instead, java will accept the method implementation of the super class, if there's an impelementation in the super class. If all identical methods are abstract then, the implementing class only needs to override those methods once.
public class SampleClass{

  public static void main(String[]args){
    ClassB classB = new ClassB();
  }
}

interface InterfaceA{

  void message();
}

interface InterfaceB extends InterfaceA{

  void message();
}

abstract class ClassA{

  public void message(){
    System.out.println("ClassA");
  }
}

class ClassB extends ClassA implements InterfaceB{
  
  ClassB(){
    message();
  }
}
If we override message() in ClassB then, ClassB only needs to override those message() methods once.
public class SampleClass{

  public static void main(String[]args){
    ClassB classB = new ClassB();
  }
}

interface InterfaceA{

  void message();
}

interface InterfaceB extends InterfaceA{

  void message();
}

abstract class ClassA{

  public void message(){
    System.out.println("ClassA");
  }
}

class ClassB extends ClassA implements InterfaceB{
  
  @Override
  public void message(){
    System.out.println("ClassB");
  }
  
  ClassB(){
    super.message();
    message();
  }
}
3.) If the implementing class has super class, super interfaces and their super interfaces and they have similar methods with same names, same number of parameters but different return type then, A compile-time error will occur in the implementing class because implementing class can't override those methods because overriding those methods in one class is very similar to method overloading.
public class SampleClass{

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

interface InterfaceA{

  void message();
}

abstract class ClassA{
  //comment this method if you're gonna use
  //the fix
  abstract String message();
  
  //1.) Try this method to fix the error
  //abstract String message(String message);
}

class ClassB extends ClassA implements InterfaceA{

  @Override
  public void message(){}
  
  //comment this method definition if you're gonna use
  //the fix
  @Override
  String message(){return "";}
  
  /*2.)
  @Override
  String message(String message){ return message; }
  */
}
The example above will throw a compile-time error. To fix the error, we can add a parameter to one of the message() methods to comply with the method overloading rules.

Tag or Marker Interface

As the name implies, tag or marker interface tags of marks a class. Java has pre-defined marker interfaces like Serializable, EventListener,etc. These interfaces have special meaning to the JVM. For example, if we tag a class as serializable then the instances of that class can be serialize in a file. Take a look at this example:
import java.io.Serializable;

public class SampleClass{

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

//that instances of this class can be serialize
class ClassA implements Serializable{
  String name;
  int num;
}
We can create our own marker interface if we wanna categorize our classes.
public class SampleClass{

  public static void main(String[]args){
  
    Rectangle rect = new Rectangle();
    
    //check if a shape is non-intersecting
    if(rect instanceof NonIntersecting)
      System.out.println("Rectangle has no intersecting "
                         +"line segments");
  }
}

//tag or marker interface
interface NonIntersecting{}

//tag this class as non-intersecting shape
class Rectangle implements NonIntersecting{
}

//tag this class as non-intersecting shape
class Triangle implements NonIntersecting{
}

//Pentagram has intersecting line segments
class Pentagram{
}

Functional Interface

This topic is pretty advance and an understanding of lambda expression is required to understand the use of this interface. Regardless, I'm gonna explain the basic concept of this interface very briefly. A functional interface is an interface with only one abstract method. However, it can have multiple default and static methods. default method is an added feature in JDK8.

This example shows the structure of a functional interface.
//@FunctionalInterface is an annotation
@FunctionalInterface
interface MyFunctionalInterface{

  void commit();
  
  //this method is optional in
  //functional interface
  default void greetings(){
    System.out.println("Hello! This is "+
                       "my functional interface");
  }
}
Java has pre-defined functional interfaces that we can use. Check out the java.util.function package. An understanding of generics is required to understand the syntax of the functional interfaces in that package.

Calling Method Using Interface Reference

We know that interface can't be instantiated. However, just like abstract class, typecasting can still happen between a sub class and a super interface.
public class SampleClass{

  public static void main(String[]args){
  
    Messenger messenger = new Messenger();
    
    //create the interface reference and upcast
    //NotificationSender instance
    Notifications notif = new NotificationSender();
    
    //these methods only need messageNotification()
    //and alertNotification methods. So, using 
    //Notification reference will suffice here and
    //avoid the misuse of displayNotificationCount().
    messenger.sendMessage("Hi There!",notif);
    messenger.sendAlert("You Battery is low!",notif);
    
    //downcast the NotificationSender instance that is
    //referenced in notif variable in order to access
    //the displayNotificationCount() method.
    NotificationSender ns = (NotificationSender)notif;
    ns.displayNotificationCount();
    
  }
}

interface Notifications{

  void messageNotification();
  void alertNotification();
}

class NotificationSender implements Notifications{
  private int msgNotifCount;
  private int alertNotifCount;

  @Override
  public void messageNotification(){
    System.out.println("Message Sent!");
    msgNotifCount++;
  }
  
  @Override
  public void alertNotification(){
    System.out.println("Alert! This matter is "
                       +"somewhat important!");
    alertNotifCount++;
  }
  
  public void displayNotificationCount(){
    
    System.out.println("message notifation count: "
                       +msgNotifCount);
    System.out.println("alert notifation count: "
                       +alertNotifCount);
  }
}

class Messenger{

  void sendMessage(String message,Notifications notif){
    System.out.println(message);
    
    //call messageNotification() using the
    //reference of Notifications interface
    notif.messageNotification();
  }
  
  void sendAlert(String alert,Notifications notif){
    System.out.println(alert);
    
    //call alertNotification() using the
    //reference of Notifications interface
    notif.alertNotification();
  }
}
Static Class In Interface

An interface can't have an inner class due to the fact that it doesn't have contructor. Although, interface can have static nested class as its member. Classes that are defined in interface are implicitly static.
public class SampleClass{

  public static void main(String[]args){
  
    MyTV myTV = new MyTV();
    myTV.adjustLight();
    myTV.adjustVolume();
    
    if(myTV.toggleAltControls())
      myTV.useAltControls(Controls.VOLUME);
    
  }
}

interface Controls{
  String LIGHT = "light";
  String VOLUME = "volume";
  
  
  //class member of interface
  //is static by default
  //static keyword can be omitted
  class PeripheralControls{
    
    void adjustVolumeAlternative(){
      System.out.println("Alternative Volume "+
                         "Controller");
    }
    
    void adjustLightAlternative(){
      System.out.println("Alternative Light "+
                         "Controller");
    }
    
  }
  
  void adjustLight();
  void adjustVolume();
}

class MyTV implements Controls{
  private PeripheralControls perpCon;
  private boolean isActivated;
  
  MyTV(){
    isActivated = false;
    perpCon = new PeripheralControls();
  }
  
  @Override
  public void adjustLight(){
    System.out.println("Main Light "+
                       "Controller");
  }
  
  @Override
  public void adjustVolume(){
    System.out.println("Main Volume "+
                       "Controller");
  }
  
  boolean toggleAltControls(){
    isActivated = !isActivated;
    return isActivated;
  }
  
  void useAltControls(String control){
  
    if(isActivated){
    
      switch(control){
      
        case Controls.LIGHT:
        perpCon.adjustLightAlternative();
        break;
        
        case Controls.VOLUME:
        perpCon.adjustVolumeAlternative();
        break;
        
        default:
        System.out.println("Invalid Input.");
        break;
        
      }
    }
    else System.out.println("Can't use "
                    +"alternative controls "
                    +"because it's not activated");
  }
  
}

Added features In Interface since Java 8

Since Java 8, there are added features that improve java interface. Those improvements really pushed interface boundary making it more flexible and usable. These are the added features:

Default Method

Default method also called defender method or virtual extension method was introduced in java8. Prior to java8, interface can't have defined methods.

However, having no defined methods in interface pose a problem. For example, if an interface has been implemented multiple times in a project and then we want to add another method; We have no choice but to implement that additional method to all implementing classes of that interface.

First of all, that's gonna be tedious and a frustrating work. One of the main purposes of default methods is to provide a simple way of adding new methods without updating the implementing classes. Let's take a look at this example.
public class SampleClass{

  public static void main(String[]args){
  
  Message1 msg1 = new Message1();
  if(msg1.message(null) == false)
    msg1.defaultMessage();
  
  Message2 msg2 = new Message2();
  if(msg2.message(null) == false)
    msg2.defaultMessage();
  
  }
}

interface DefaultMessage{
  
  //default method is not required to be overriden
  //we can override this if it's needed
  default void defaultMessage(){
    System.out.println("Default message");
  }
  
  boolean message(String message);
}

class Message1 implements DefaultMessage{
  
  //Overriding the default method
  @Override
  public void defaultMessage(){
    System.out.println("Default message in Message1");
  }
  
  @Override
  public boolean message(String message){
  
    if(message == null)
      return false;
  
    System.out.println("Message1 message: "
                       +message);
    return true;
  }
}

class Message2 implements DefaultMessage{

  @Override
  public boolean message(String message){
    if(message == null)
      return false;
  
    System.out.println("Message2 message: "
                       +message);
    return true;
  }
}
In the above example, we see that we're the implementing classes are not required to override the default method. Thus, implementing classes are not required to update everytime we add default methods in our interface. Also, default method is public by default.

If we want to access identical default methods between interfaces, we need to override the identical methods first then we can use the super keyword to call for the methods.
public class SampleClass{

  public static void main(String[]args){
  
    ClassA classA = new ClassA();
  }
}

interface InterfaceA{

  default void message(){
    System.out.println("InterfaceA");
  }
}

interface InterfaceB{

  default void message(){
    System.out.println("InterfaceB");
  }
}

class ClassA implements InterfaceA,InterfaceB{
  
  //Override message() first
  @Override
  public void message(){
    //call default methods using the super
    //keyword
    InterfaceA.super.message();
    InterfaceB.super.message();
  }
  
  ClassA(){
    message();
  }
}
If you don't override message() first, you will encounter this error:
"ClassA inherits unrelated defaults..."

Default method can be redeclared as abstract method in another interface.
public class SampleClass{

  public static void main(String[]args){
  
    ClassA classA = new ClassA();
  }
}

interface InterfaceA{

  //default method
  default void message(){
    System.out.println("InterfaceA");
  }
}

interface InterfaceB extends InterfaceA{
  
  //redeclare default method as abstract method
  void message();
}

class ClassA implements InterfaceB{
  
  //redifine message() in implementing class
  @Override
  public void message(){
    System.out.println("ClassA");
  }
  
  ClassA(){
    message();
  }
}
Default method has this "static-non-static" behaviour, if you will. Default method can only access static class/interface members. However, default method can't be called like static method. Take a look at this example:
public class SampleClass{

  public static void main(String[]args){
    
    //error: can't call getName() default method directly
    //System.out.println(ClassA.Interface1.getName());
    
    new ClassB();
    
    //static method can be called directly
    ClassA.Interface1.setName("main");
    
    new ClassB();
  }
}

abstract class ClassA{
  //this variable can be accessed by
  //default method in nested interface
  //because it's static
  private static String name = "ClassA";
  
  //nested interface
  interface Interface1{
  
    default String getName(){
      return name;
    }
    
    static void setName(String name){
      ClassA.name = name;
    }
  }
  
}

//implement Interface1 in ClassA
class ClassB implements ClassA.Interface1{
  
  ClassB(){
    //default method can be called in
    //implementing class
    System.out.println(getName());
  }
}
Private and Static Method

Interface can now have private and static methods. A non-private static method is implicitly public.
public class SampleClass{

  public static void main(String[]args){
    Defaults.defaultMessage();
  }
}

interface Defaults{
  
  //private static method
  private static void defaultFont(){
    System.out.println("Default Font Acquired!");
  }
  
  //implicitly public
  static void defaultMessage(){
    System.out.println("Acquiring Default Font...");
    defaultFont();
    System.out.println("This is a Default Message!");
  }
  
}

Nested Interface

Like classes, interface can also be nested. An interface can be nested in a class or another interface. One of the uses of nested interface is to group interfaces that are related to each other.
Interface In Another Interface

An interface can have interface as its members. A nested interface in another interface is implicilty public.
public class SampleClass{

  public static void main(String[]args){
    String toolToUse = Toolkit.HAMMER;
    
    switch(toolToUse){
    
      case Toolkit.HAMMER:
      Toolkit.ConstructionTools.useHammer();
      break;
      
      case Toolkit.SCREWDRIVER:
      Toolkit.HardwareTools.useScrewDriver();
      break;
    }
    
  }
}

interface Toolkit{
  String HAMMER = "hammer";
  String NAILS = "nails";
  String SCREWDRIVER = "screwdriver";
  String SCREWS = "screws";
  
  //nested interface
  interface ConstructionTools{
  
    static void useHammer(){
      getNails();
      System.out.println("Using " + HAMMER + "...");
      System.out.println("Job's Done!");
    }
    
    private static void getNails(){
      System.out.println("Getting nails...");
      System.out.println(NAILS+" acquired!");
    }
  }
  
  //nested interface
  interface HardwareTools{
    static void useScrewDriver(){
      getScrews();
      System.out.println("Using " + SCREWDRIVER + "...");
      System.out.println("Job's Done!");
    }
    
    private static void getScrews(){
      System.out.println("Getting screws...");
      System.out.println(SCREWS+" acquired!");
    }
  }
}
Here's another example:
public class SampleClass{

  public static void main(String[]args){
    MyConstTools mct = new MyConstTools();
    mct.useHammer();
    mct.useDrill();
    
    MyCustomTools cTools = new MyCustomTools();
    cTools.useTool();
    
  }
}

interface Tools{
  
  interface ConstructionTools{
    
    void useHammer();
    void useDrill();
  }
  
  void useTool();
}

//implement nested interface
class MyConstTools implements Tools.ConstructionTools{

  @Override
  public void useHammer(){
    System.out.println("Using my hammer...");
  }
  
  @Override
  public void useDrill(){
    System.out.println("Using my drill...");
  }
  
}

//implement top-level interface
class MyCustomTools implements Tools{

  @Override
  public void useTool(){
    System.out.println("Using my cutom-made tool");
  }
}
Interface In a Class

An interface can be nested in a class. Unlike interface in another interface, interface in a class can have public, default or protected access modifier.
public class SampleClass{

  public static void main(String[]args){
  
    MyToolBox toolBox = new MyToolBox(ToolBox.
                                      WoodenBox.BOX_NAME,
                                      7);
                        
    if(ToolBox.WoodenBox.checkBox(toolBox))
      System.out.println("This box is a: " +
                         ToolBox.WoodenBox.BOX_NAME);
    else if(ToolBox.MetalBox.checkBox(toolBox))
      System.out.println("This box is a: " +
                         ToolBox.MetalBox.BOX_NAME);
                         
  }
}

abstract class ToolBox{
  private static String name;
  
  ToolBox(String name){
  
    this.name = name;
  }
  
  //nested interface
  interface WoodenBox{
    String BOX_NAME = "Wooden Box";
    
    static boolean checkBox(ToolBox box){
      //interface can only access static
      //members of a class
      if(box.getName() == name)
        return true;
      else return false;
      
    }
  }
  
  //nested interface
  interface MetalBox{
    String BOX_NAME = "Metal Box";
    
    static boolean checkBox(ToolBox box){
      //interface can only access static
      //members of a class
      if(box.name == name)
        return true;
      else
        return false;
    }
  }
  
  String getName(){ return name; }
  
}

class MyToolBox extends ToolBox{
  private int weight;
  
  MyToolBox(String name,int weight){
    super(name);
    this.weight = weight;
  }
}
In the above example, we see that interface can access the name static variable in ToolBox. Remember, nested interface in a class can access static members but not instance members because nested interface behave similarly to nested static class.

Sunday, June 13, 2021

Java Tutorial: The final Keyword

Chapters

The final Keyword

The final keyword can be used in a variable, method and class. The final keyword affects variable, method and class differently.

Using final Keyword In Variables

When we use final keyword in a variable, the value of the variable can't be changed. We call these variables as constants. If the value of a variable is an object reference then the state of the object of the reference can be changed but the reference that is assigned with the variable can't be changed. This property is called non-transitivity.

arrays and collections have this property because arrays and collections are objects. Constant variables require less resources than regular variables. Thus, constants may improve the performance of our program.

Let's create an example to demonstrate final variables.
public class SampleClass{
  //blank final instance variable
  //this variable needs to
  //be instantiated in an
  //initializer block or
  //a constructor
  final String NAME;
  
  //final instance variable
  static final int ONES = 5;
  
  //final instance variable
  //with object reference
  final StringBuilder STR_BUILD = 
                  new StringBuilder("abcd");
  
  //blank final static variable
  //this variable needs to be
  //instantiated in a static
  //block
  //
  //Sometimes, it's convenient to make your
  //final variable static to prevent
  //it from having duplicates
  //everytime we create a class
  //object where the final variable
  //resides
  static final double DECIMAL;
  
  //final static variable
  final static int TENS = 37;
  
  SampleClass(){
    //initialize blank final
    //in a constructor or
    //initializer block
    NAME = "SampleClass";
    
    //error: once blank final is 
    //initialized, we can't
    //change its value anymore
    //NAME = "ClassSample";
  }
  
  static{
    //initialize static blank final
    //in a static block
    DECIMAL = 10.5;
    
    //error: once blank final is 
    //initialized, we can't
    //change its value anymore
    //DECIMAL = 11;
  }
  
  public static void main(String[]args){
    //final local variable
    final int NUM = 1;
    
    //error. can't change num value because
    //it's final
    //NUM = 5;
    
    SampleClass sc = new SampleClass();
    System.out.println(sc.NAME);
    System.out.println(sc.ONES);
    System.out.println(sc.TENS);
    System.out.println(sc.DECIMAL);
    System.out.println();
    
    System.out.println(sc.STR_BUILD.toString());
    System.out.println("Add String...");
    
    //change object state
    sc.STR_BUILD.append("efgh");
    
    //error: reference assigned to builder variable
    //can't be changed
    //sc.STR_BUILD = new StringBuilder("abcdefgh");
    
    System.out.println(sc.STR_BUILD.toString());
  }
}
There are lots of interesting things going on in the example. We see that once a final variable has been initialized, its value can't be changed. If the variable is a reference type variable, the properties of the object referenced by the reference can be changed but the reference that the variable holds can't be changed.

Now, let's talk about blank final variable. This variable can be declared without a value. However, it's required to be initialized in an initializer block or constructor if the variable is non-static, if it's static then it's required to be initialized in a static block.

Using final Keyword In Classes

When final keyword is used in classes, those classes can't be extended or in other words, they can't have child classes.
Note: final keyword doesn't work with abstract classes.
public class SampleClass{

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

final class ClassA{
  static String name = "ClassA";

}

//error: Class can't extend ClassA
class ClassB extends ClassA{
  String name = "ClassB";
}
Using final Keyword In Methods

When final keyword is used in methods, those methods can't be overriden.
public class SampleClass{

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

class ClassA{
  static String name = "ClassA";
  
  //final method
  public final void displayName(){
    System.out.println(name);
  }
  
  //This syntax is legal but final keyword
  //here is redundant since static methods
  //can't be overriden already
  /*
  public final static void displayName(){
    System.out.println(name);
  }
  */
  
}

class ClassB extends ClassA{
  static String name = "ClassB";
  
  //error: can't override final
  //method
  /*
  @Override
  public final void displayName(){
    System.out.println(name);
  }
  */
  
  //error: can't override static method
  /*
  @Override
  final static public void displayName(){
    System.out.println(name);
  }
  */
  
  public void displayParentName(){
    super.displayName();
  }
}
In the above example, we see that displayName() in ClassA can't be overriden. We also see that adding final keyword in a static method is redundant since static methods can't be overriden already.

Another interesting thing is this syntax:
public final static void displayName()
In this syntax we have three modifiers: public access modifier, static and final. Some modifiers can be arranged in any order. These three modifiers can be placed in any order
Example
static public final void displayName(){}

Using final Keyword In Method/Constructor Parameter

When final keyword is used in Method/Constructor Parameter, the value of the parameter can't be changed in the method/constructor block. Otherwise, a compilation error will be thrown.
public class SampleClass{
  
  static void method(final String str){
    String myString = str;
    
    //Uncomment this code below
    //and you will encounter a compilation
    //error
    //str = "This is an error";
  }
  
  public static void main(String[] args){
  
  }
}

Saturday, June 12, 2021

Java Tutorial: The static Keyword

Chapters

The static Keyword

Classes, variables, methods and blocks with static keyword belong to the class itself. It means, static members don't need an instance of a class in order to be accessed.

Static members are always initialized first before class instance initialization because, when a class is loaded into the JVM, static members are also initialized. Classes need to be loaded first into the JVM before our program can instantiate them.
Note: static keyword is not allowed in top-level classes.
public class SampleClass{
  //static variable
  static String name = "SampleClass";
  //non-static variable
  int num = 1;
  
  //static method
  static int add(int n1,int n2){
    return n1 + n2;
  }
  
  //non-static method
  int multiply(int n1,int n2){
    return n1 * n2;
  }
  
  //non-static method
  void displayName(){
    System.out.println("Display name in displayName(): ");
    //static members can be accessed in non-static
    //context
    System.out.println(name);
  }
  
  public static void main(String[]args){
  
    //error: non-static members can't directly
    //be accessed in static context
    //System.out.println(num);
    //System.out.println(multiply(2,2));
    
    //static members can be directly accessed
    //in static context
    System.out.println(name);
    System.out.println(add(2,2));
    
    //non-static members can be indirectly
    //accessed in static context by instantiation
    SampleClass sc = new SampleClass();
    System.out.println(sc.num);
    System.out.println(sc.multiply(2,2));
    sc.displayName();
    System.out.println();
    
    //class instance can access static members
    //and static members are shared across
    //the class instances.
    System.out.println("Accessing static members through"+
                       " class instances.");
    System.out.println(sc.name);
    SampleClass sc2 = new SampleClass();
    System.out.println(sc2.name);
    System.out.println();
    
    ClassA classA = new ClassA();
  }
}

class ClassA{
  
  ClassA(){
    System.out.println("ClassA constructor");
    
    //when accessing a static member of a class
    //to another class, write the class name first
    //then dot(.) then the variable name
    System.out.println("Call SampleClass.name in ClassA:" +
                       SampleClass.name);
                       
    //All instances of SampleClas share the same
    //static members.
    //Take a look at this example
    SampleClass sc1 = new SampleClass();
    SampleClass sc2 = new SampleClass();
    sc1.name = "Modified";
    System.out.println("Call SampleClass.name in sc2:" +
                       sc2.name);
    
  }
}
Note: We can think of "static context" as context that is related to static elements like static methods, fields, etc.
Alright! There are lots of interesting things happening in the example above. We can see above that a static member can be directly access in a non-static class member. You might ask: "why?". I already explained the answer in the introduction of this chapter, though, I'm gonna explain it again here.

Static members are initialized during class loading into the JVM. Classes need to be loaded first into the JVM before our program can create instances of them. If we insist on putting non-static member in a static context then we will encounter nasty exceptions like NullPointerException,NoClassDefFoundError,etc. That's why java prohibits non-static members in a static context.

However, we can indirectly access non-static members in a static context by instantiating the class first. If successful, Java knows that the class is loaded and its instance is successfully created. Thus, Java knows its non-static members exist.

When we wanna call a static member of a class to another class then, we need to write the class name first then dot(.) then the variable name like this code in the example above: SampleClass.name

As long as static members are not private, they will be shared with every instance of the class and with the class subclasses. That's why a class instance can call static class members.

Static Class Members In Inheritance

Static variables, methods and classes are inherited by sub class during inheritance. However, static methods can't be overriden.
public class SampleClass{
  
  public static void main(String[]args){
   
     ClassB b = new ClassB();
     b.displayName();
     b.displayParentName();
  }
}

class ClassA{
    protected static String name;
	
    static void displayName(){
      System.out.println(name);
    }
}

class ClassB extends ClassA{
	static String name;
	
	//error: @Override annotation
	//can't be placed because static
	//methods can't be overriden
	//@Override
	static void displayName(){
		//error: can't put super()
		//in static context because
		//call to super is non-static
		//super.displayName();
		System.out.println(name);
	}
	
	void displayParentName(){
		//can call parent class
		//displayName()
		super.displayName();
	}
	
	ClassB(){
		//can call parent class
		//name variable
		super.name = "ClassA";
		name = "ClassB";
	}
}
As you can see from the example above, we can't use @Override annotation in the displayName() of ClassB because displayName() in ClassB doesn't override displayName() in ClassA. Though, we can still call displayName() of ClassA from ClassB because it's just hidden.

Java Tutorial: Access Modifiers

Chapters

Java Access Modifiers

As the title implies, access modifiers restrict classes and class members accessibility in packages or enclosing blocks. There are four access modifiers in java. Let's discuss them one by one.

public Access Modifier

public access modifier is the most unrestrictive modifier in all access modifiers in java. classes or class members that have this modifier are accessible to all packages in a project and related enclosing blocks.
public class SampleClass{
  public String name = "SampleClass";
  
  public void displayName(){
    //name is accessible here
    System.out.println(name);
  }
  
  public static void main(String[]args){
   //can't directly put non-static variable in a
   //static context even they're in the same
   //class block
   //System.out.println(name);
   
   SampleClass sc = new SampleClass();
   //variables and other public members
   //can be accessed once there's an 
   //instance of a class
   System.out.println(sc.name);
   sc.displayName();
   
  }
}
Package accessibility. We need to put source files in folders.
//This source file must be in p1 folder
package p1;

public class Compute{

  public int add(int n1, int n2){
    return n1 + n2;
  }
}

//This source file must be in p2 folder
package p2;

//use import keyword to import classes
//to another package
import p1.Compute;

public class SampleClass{

  public static void main(String[]args){
    //compute class is accessible in p2
    Compute compute = new Compute();
    System.out.println("Add 3 and 7");
    
    //add() is also accessible in p2
    System.out.println("Answer: " + compute.add(3,7));
  }
}
default Access Modifier

This modifier is keyword-less modifier. If we want a class or a class member to have default modifier, just leave the modifier part blank. classes or class members that have this modifier are only accesible in the package where they reside.
public class SampleClass{
  String name = "SampleClass";
  
  void displayName(){
    //name is accessible here
    System.out.println(name);
  }
  
  public static void main(String[]args){
   //can't directly put non-static variable in a
   //static context even they're in the same
   //class block
   //System.out.println(name);
   
   SampleClass sc = new SampleClass();
   //variables and other default members
   //can be accessed once there's an 
   //instance of a class
   System.out.println(sc.name);
   sc.displayName();
   
  }
}
Package accessibility. We need to put source files in folders.
//This source file must be in p1 folder
package p1;

public class Compute{
  int aggrResult;
  
  public int add(int n1, int n2){
    aggrResult += (n1 + n2);
    return n1 + n2;
  }
}

class Calculate{

  public int add(int n1, int n2){
    return n1 + n2;
  }
}

//This source file must be in p2 folder
package p2;

//use import keyword to import classes
//to another package
import p1.Compute;
import p1.Calculate;

public class SampleClass{

  public static void main(String[]args){
    //compute class is accessible in p2
    Compute compute = new Compute();
    System.out.println("Add 3 and 7");
    
    //add() is also accessible in p2
    System.out.println("Answer: " + compute.add(3,7));
    System.out.println("Add 4 and 6");
    System.out.println("Answer: " + compute.add(4,6));
    
    //error: aggrResult is not accessible in another
    //package because it has default access modifier
    //System.out.println("Aggregate Result: " + 
    //                   compute.aggrResult);
                       
    //error: Calculate class is not accessible in another
    //package because it has default access modifier
    //Calculate calculate = new Calculte();
  }
}
protected Access Modifier

This access modifier makes classes and class members only accessible in a package where they reside or in a sub class
Note: protected access modifier is not allowed in top-level classes.
public class SampleClass{
  
  public static void main(String[]args){
   ClassA a = new ClassA();
   //name variable with protected modifier
   //can be accessed in the package where
   //it resides
   System.out.println(a.name);
  }
}

class ClassA{
  protected String name = "ClassA";
  
  public String getName(){
    return name;
  }
}

class ClassB extends ClassA{

  public ClassB(){
    //name is accessible here because
    //ClassB is sub class of ClassA
    //and ClassB is in the same package
    //as ClassA
    name = "ClassB";
  }
}
Package accessibility. We need to put source files in folders.
//This source file must be in p1 folder
package p1;

public class ClassA{
  protected String name = "ClassA";
  
  public String getName(){
    return name;
  }
}

//This source file must be in p1 folder
package p1;

public class ClassB extends ClassA{

  public ClassB(){
    //name is accessible here because
    //ClassB is sub class of ClassA
    //and ClassB is in the same package
    //as ClassA
    name = "ClassB";
  }
}

//This source file must be in p2 folder
package p2;

import p1.ClassA;
import p1.ClassB;

public class SampleClass{
  
  public static void main(String[]args){
   ClassA a = new ClassA();
   //error: name variable can't be accessed in
   //another package because it has
   //protected access modifier
   //System.out.println(a.name);
   
   ClassC c = new ClassC();
   System.out.println(c.getName());
  }
}

class ClassC extends ClassA{
  
  ClassC(){
  //name variable can be accessed here
  //because ClassC is sub class of ClassA
   name = "ClassC";
  }
}
private Access Modifier

private access modifier is the most restrictive modifier in all access modifiers in java. Classes and class members that have this modifier are only accessible in their enclosing class.
Note: private access modifier is not allowed in top-level classes.
public class SampleClass{
  private String name;
  private static int num;
  
  SampleClass(String name, int num){
    //name variable can be accessed here
    //because this constructor block is
    //part of the instance of SampleClass
    this.name = name;
    
    //static variable is allowed in 
    //non-static context
    SampleClass.num = num;
  }
  
  public static void main(String[]args){
    SampleClass sc = new SampleClass("SampleClass",1);
    
    //name and num variable can be accessed here
    //because main() is in SampleClass enclosing block.
    System.out.println(sc.name);
    System.out.println(SampleClass.num);
  }
}

class ClassA{
  private int num;
  
  ClassA(){
    //error: num variable in SampleClass
    //can't be accessed here because this
    //is not SampleClass class.
    //num = SampleClass.num;
  }
}

class ClassB extends ClassA{

  ClassB(){
    //can't access num of ClassA here
    //because this is not part of
    //ClassA
    //num = 2;
  }
}
Tips On Using Access Modifiers

When building an application, we want to balance its security and maintainability. If we want our application to be more maintainable then, we need to relax some of its restrictions so that, it has more flexibility, thus, it can be easily maintained. However, relaxing restrictions may reduce application's security.

If we want to make our applcation to be more secure then, we need to increase the restrictions of our application. However, It will make our application less flexible, thus, it may become less maintanable.

Friday, June 11, 2021

Java Tutorial: Typecasting(Objects)

Chapters

Typecasting(Objects)

You need to have an understanding of inheritance to understand this topic. In this topic, we're going to discuss casting an object type to another type which is called typecasting.

I already covered typecasting of primitive types in my previous tutorials. When we instantiate a class, an object is gonna be created. Objects have types and their types are based on the types of classes in which they're created.

Typecasting can be done if two classes have parent-to-child relationship. A sub class is a sub type and a super class is a super type. Typecasting has two types: upcasting and downcasting. Variables(fields) types of instance being converted remain the same during typecasting.

Upcasting

Upcasting is the process of casting a sub type to a super type. Target type is implicitly done by the compiler.
public class SampleClass{

  public static void main(String[]args){
    BallPoint bp = new BallPoint(1, 100, "Pointy");
    System.out.println("bp content");
    System.out.println("Name: " + bp.name);
    System.out.println("Ink Level: " + bp.inkLvl);
    System.out.println("Pen No: " + bp.getPenNo());
    System.out.println();
  
    //This statement is valid but redundant.
    //Pen pen = (Pen)bp;
  
    //No need to explicitly write the target type
    //the compiler will do it for us
    Pen pen = bp;
  
    System.out.println("pen content");
    System.out.println("Pen No: " + pen.getPenNo());
    System.out.println("Ink Level: " + pen.inkLvl);
    //error sub class members are not visible to
    //super class
    //System.out.println("Name: " + pen.name);
  }
  
}

abstract class Pen{
  private int penNo;
  int inkLvl;
  
  Pen(int penNo,int inkLvl){
    this.penNo = penNo;
    this.inkLvl = inkLvl;
  }
  
  public int getPenNo(){ return penNo; }
}

class BallPoint extends Pen{
  String name;
  
  BallPoint(int penNo,int inkLvl,String name){
    super(penNo,inkLvl);
    this.name = name;
  }
}
In the example above, we can see that we can assign a BallPoint object type to a Pen type variable. BallPoint is sub class of Pen and Pen is super class of BallPoint. Thus, upcasting is successful.

We can also see in the example above that pen variable can only access Pen class members. That is expected because when we upcast a sub type to a super type, a sub type will become a super type, thus, the sub type will have the same behavior as super type.

When a sub type is casted to a super type, sub class members still exist, they're just not accessible. They can be accessible again once the sub type that becomes super type is casted back to sub type.

When we cast a sub class that overrode a method to a parent class then, overriding method in sub class will override the the overriden method in parent class once the casting is successful.
public class SampleClass{

 public static void main(String[]args){

    ClassA a = new ClassB();
    a.greetings();
 }
}

class ClassA{

  void greetings(){
    System.out.println("Hello! This is ClassA!");
  }
}

class ClassB extends ClassA{

  void greetings(){
    System.out.println("Hello! This is ClassB!");
  }
}

Result
Hello! This is ClassB!

Downcasting

Downcasting is the process of casting a super type to a sub type. Target type must be explicitly defined.
public class SampleClass{

  public static void main(String[]args){
    BallPoint bp = new BallPoint(1, 100, "Pointy");
    System.out.println("bp content");
    System.out.println("Name: " + bp.name);
    System.out.println("Ink Level: " + bp.inkLvl);
    System.out.println("Pen No: " + bp.getPenNo());
    System.out.println();

    Pen pen = bp;
    System.out.println("pen content");
    System.out.println("Pen No: " + pen.getPenNo());
    System.out.println("Ink Level: " + pen.inkLvl);
    System.out.println();
    
    //Downcasting
    //It's a good practice to use instanceof
    //everytime we downcast a type
    if(pen instanceof BallPoint){
      BallPoint bp2 = (BallPoint)pen;
      System.out.println("bp2 content");
      System.out.println("Name: " + bp2.name);
      System.out.println("Ink Level: " + bp2.inkLvl);
      System.out.println("Pen No: " + bp2.getPenNo());
      System.out.println();
    }
    
  }
  
}

abstract class Pen{
  private int penNo;
  int inkLvl;
  
  Pen(int penNo,int inkLvl){
    this.penNo = penNo;
    this.inkLvl = inkLvl;
  }
  
  public int getPenNo(){ return penNo; }
}

class BallPoint extends Pen{
  String name;
  
  BallPoint(int penNo,int inkLvl,String name){
    super(penNo,inkLvl);
    this.name = name;
  }
}
In the example above, we can see that the object that is referenced to pen variable which is a former sub type retains its accessibility to all of its members once it returns back to its original type. Also, use instanceof keyword to avoid ClassCastException.

ClassCastException is thrown at runtime if the type that we're casting is not compatible with the target type. instanceof keyword checks if the reference type on its left is compatible with the type on its right.

You might wonder: "Why downcasting needs the target type to be explicitly defined whereas upcasting doesn't?" The reason, in my opinion, is that downcasting is more problematic than upcasting.

In primitive types, downcasting may cause data loss. For example, we wanna downcast long to int, long is 64 bits and int is 32 bits, in order to cast long to int, long needs to lose half of its bits.

In object typecasting, downcasting is more prone to ClassCastException than upcasting. That's why it's preferrable to check if one type is compatible with another type by using instanceof before downcasting a type. Take a look at this example.
public class SampleClass{

  public static void main(String[]args){
    
    BallPoint bp = new BallPoint(1, 100, "Pointy");
    System.out.println("bp content");
    System.out.println("Name: " + bp.name);
    System.out.println("Ink Level: " + bp.inkLvl);
    System.out.println("Pen No: " + bp.getPenNo());
    System.out.println("Ball Point Type: " + bp.ballPointType);
    System.out.println();
    
    Pen pen = bp;
    System.out.println("pen content");
    System.out.println("Pen No: " + pen.getPenNo());
    System.out.println("Ink Level: " + pen.inkLvl);
    System.out.println();
    
    //ClassCastException
    RollerBall bp2 = (RollerBall)pen;
    System.out.println("bp2 content");
    System.out.println("Name: " + bp2.name);
    System.out.println("Ink Level: " + bp2.inkLvl);
    System.out.println("Pen No: " + bp2.getPenNo());
    System.out.println("Roller Ball Type: " + bp2.rollerBallType);
    System.out.println();
  }
  
}

abstract class Pen{
  private int penNo;
  int inkLvl;
  
  Pen(int penNo,int inkLvl){
    this.penNo = penNo;
    this.inkLvl = inkLvl;
  }
  
  public int getPenNo(){ return penNo; }
}

class BallPoint extends Pen{
  String name;
  String ballPointType = "default";
  
  BallPoint(int penNo,int inkLvl,String name){
    super(penNo,inkLvl);
    this.name = name;
  }
}

class RollerBall extends Pen{

  String name;
  String rollerBallType = "default";
  
  RollerBall(int penNo,int inkLvl,String name){
    super(penNo,inkLvl);
    this.name = name;
  }
}
In the example above, A ClassCastException happened when the program attempted to cast Pen object type to RollerBall object type. When you think about it, it is legal because Pen is the super class of RollerBall. Thus, Pen can be downcasted to RollerBall.

However, the object type that is referenced to "bp" variable is only compatible with BallPoint and Pen classes because when we instantiate the BallPoint class, it inherits its parent class which is Pen class in this case, thus inheriting its parent type.

Since java 14, we can use this type of syntax for downcasting.
public class SampleClass{

  public static void main(String[]args){
    Pen pen = new BallPoint(1, 100, "Pointy");
    
    //Shorthand syntax for downcasting
    //bp2 is defined in the if parentheses
    //no need to use the traditional
    //downcasting syntax
    if(pen instanceof BallPoint bp2){
      System.out.println("bp2 content");
      System.out.println("Name: " + bp2.name);
      System.out.println("Ink Level: " + bp2.inkLvl);
      System.out.println("Pen No: " + bp2.getPenNo());
      System.out.println();
    }
    
  }
  
}

abstract class Pen{
  private int penNo;
  int inkLvl;
  
  Pen(int penNo,int inkLvl){
    this.penNo = penNo;
    this.inkLvl = inkLvl;
  }
  
  public int getPenNo(){ return penNo; }
}

class BallPoint extends Pen{
  String name;
  
  BallPoint(int penNo,int inkLvl,String name){
    super(penNo,inkLvl);
    this.name = name;
  }
}
Typecasting Using Class<T> Class

Note: You need to understand generics to understand the syntax of Class<T> class.
Another way to cast objects is using the Class<T> Class. Don't be confused with the java class and "Class<T>" class. Class<T> class is a class in java that provides tools to gather information about classes.

This type of typecasting is pretty advance and it's preferrably used in java reflection. This <T> that we're seeing is part of the syntax of generic types which is also a pretty advance topic.

We're not gonna fully discuss Class<T> class here. We're just gonna focus on its two methods: cast() and isInstance().
public class SampleClass{

  public static void main(String[]args){
    BallPoint bp = new BallPoint(1, 100, "Pointy");
    System.out.println("bp content");
    System.out.println("Name: " + bp.name);
    System.out.println("Ink Level: " + bp.inkLvl);
    System.out.println("Pen No: " + bp.getPenNo());
    System.out.println();

    Pen pen = bp;
    System.out.println("pen content");
    System.out.println("Pen No: " + pen.getPenNo());
    System.out.println("Ink Level: " + pen.inkLvl);
    System.out.println();
    
    //Downcasting using Class<T>
    if(Pen.class.isInstance(pen)){
      BallPoint bp2 = BallPoint.class.cast(pen);
      System.out.println("bp2 content");
      System.out.println("Name: " + bp2.name);
      System.out.println("Ink Level: " + bp2.inkLvl);
      System.out.println("Pen No: " + bp2.getPenNo());
      System.out.println();
    }
  }
}

abstract class Pen{
  private int penNo;
  int inkLvl;
  
  Pen(int penNo,int inkLvl){
    this.penNo = penNo;
    this.inkLvl = inkLvl;
  }
  
  public int getPenNo(){ return penNo; }
}

class BallPoint extends Pen{
  String name;
  
  BallPoint(int penNo,int inkLvl,String name){
    super(penNo,inkLvl);
    this.name = name;
  }
}
In this example, we use the class keyword to refer to a specific class. For example, Pen.class refers to the Pen class. Once we refer to a class, we can use Class<T> methods like the cast() and isInstance(). isInstance() is equivalent to instanceof keyword and cast() is equivalent to traditional typecasting.

Thursday, June 10, 2021

Java OOPs: Inheritance

Chapters

Java Inheritance

Inheritance is part of java OOPs(Object Oriented Programming System) or OOP for short. It is the process in java in which one class can inherit inheritable another class. In java, we can achieve inheritance by using the extends or implements keyword.

The extends Keyword

When we want a class to inherit another class then we will use the extends keyword.
Example

public class SampleClass{

  public static void main(String[]args){
    
    Cat cat = new Cat();
    System.out.println("Cat is a " + cat.getType());
    System.out.println("Cat name: " + cat.getName());
    //private class members can't be inherited
    //error
    //System.out.println(cat.type);
    
    Animal animal = new Animal();
    System.out.println("Animal type: " + animal.getType());
    //subclass members are not visible to 
    //super(parent or base) class
    //error
    //System.out.println("Animal name: " + animal.getName());
  }
}

class Animal{
  private String type = "Mammal";
  
  public String getType(){
    return type;
  }

}

class Cat extends Animal{
  private String name = "Kitty";
  
  public String getName(){
    return name;
  }
}
In the example above, we see that Cat class inherits the getType() method of Animal Class but Cat class can't inherit(access) the "type" variable of Animal because it's private. We can also see that super class can't access sub class members.

The class whose members are inherited by another class is the super(base or parent) class. The class that inherits another class members is the sub(child, derived or extended) class. A class(except for enum class) can only explicitly extend one class. Java doesn't support multiple inheritance of classes.

If we don't want a parent class to be instantiated then we can make the parent class as abstract class.
Example

public class SampleClass{

  public static void main(String[]args){
    
    Cat cat = new Cat();
    System.out.println("Cat is a " + cat.getType());
    System.out.println("Cat name: " + cat.getName());
    
    //Abstract class can't be instantiated
    //error
    //Animal animal = new Animal();

  }
}

abstract class Animal{
  private String type = "Mammal";
  
  public String getType(){
    return type;
  }

}

class Cat extends Animal{
  private String name = "Kitty";
  
  public String getName(){
    return name;
  }
}
Interface can also use extends keyword but it only works on another interface.
interface SourceChecker{

  void verifySource();
}

interface SourceFilter extends SourceChecker{
  
  void filterSource();
}
In generics, extends keyword can be used to create a bounded type parameters and upper bounded wildcard.

The implements Keyword

We use the implements keyword to make a class to be a sub class of an interface.
public class SampleClass{

  public static void main(String[]args){
  
    new Animal().makeSound();
  }
}

interface AnimalSound{

  void makeSound();
}

class Animal implements AnimalSound{

  @Override
  public void makeSound(){
    System.out.println("Default Sound...");
  }
}
In the example above, Animal parent class(interface) is AnimalSound and we overrode AnimalSound's makeSound() method.

Unlike the extends keyword, we can use the implements keyword to implement multiple interfaces to a class. To implement multiple interfaces to a class, write the implements keyword then after that, write interface names and separate them by comma.
public class SampleClass{

  public static void main(String[]args){
    Cat cat = new Cat();
    cat.makeSound();
    cat.internalSkeleton();
  }
}

interface AnimalSound{

  void makeSound();
}

interface SkeletalSystem{
  
  void internalSkeleton();
  void exoSkeleton();
}

//This class has multiple parent classes(interfaces)
abstract class Animal implements AnimalSound,SkeletalSystem{

  @Override
  public void makeSound(){}
  @Override
  public void internalSkeleton(){}
  @Override
  public void exoSkeleton(){}
  
}

class Cat extends Animal{

  @Override
  public void makeSound(){
  
    System.out.println("Meow!");
  }
  
  @Override
  public void internalSkeleton(){
    System.out.println("Cat has internal skeleton!");
  }
}
extends and implements can be used at the same in a class
public class SampleClass{
 
 public static void main(String[]args){
 }
}

interface Interface{
}

class ClassA{
}

class ClassB extends ClassA implements Interface{
}
Remember, parent class is not instantiated during inheritance. Only the instance of subclass with superclass members is created. Though, sub class type can be casted to its parent class type. We will learn about casting objects in typecasting(Objects) topic.

In generics, the super keyword is used to create a lower bounded wildcard.

Object Class Implicit Inheritance

The Object class is the parent of all classes. Every class has Object as a superclass. Thus, Object class is implicitly inherited by user-defined classes. Take a look at this example:
public class SampleClass{

  public String ObjectToString(){
    return super.toString();
  }
  
  @Override
  public String toString(){
    return "SampleClass ToString()";
  }
  
  public static void main(String[]args){
    SampleClass sc = new SampleClass();
    System.out.println("Obj toString(): " +
                       sc.ObjectToString());
    System.out.println("SampleClass toString(): " +
                       sc.toString());
  }
}
As you can see in the example above, we can override toString() which is one of Object class members and we can call the toString() of Object class.

Implicit Call to super() During Inheritance

If we don't call super() explicitly in a constructor then super() is implicitly called in a constructor of a subclass when we do inheritance. Implicit call of super() calls the default constructor of a parent class whether it is defined or not.
public class SampleClass{

  public static void main(String[]args){
    ClassB cb = new ClassB("String");
  }
}

class ClassA{

  ClassA(){
    System.out.println("ClassA Default Constructor");
  }
  
  ClassA(String a){
    System.out.println(a);
  }
}

class ClassB extends ClassA{

  ClassB(){
    System.out.println("ClassB Default Constructor");
  }
  
  ClassB(String a){
    System.out.println(a);
  }
}

Result
ClassA Default Constructor
String
Try calling the default constructor of ClassB and the default constructor of ClassA will still be implicitly called. Also, try adding private keyword before the default constructor name of ClassA and you will encounter a compile-time error.

Types of Inheritance
There are various inheritance types that Java supports.

Single Inheritance

Simpliest form of inheritance. This inheritance is comprised of one parent class and one sub class.
public class SampleClass{

  public static void main(String[]args){
    ClassB b = new ClassB();
  }
}

abstract class ClassA{

  ClassA(){
    System.out.println("Class A");
  }
}
  
class ClassB extends ClassA{

  ClassB(){
    System.out.println("Class B");
  }
}
Single Inheritance Diagram
Single Inheritance

Multilevel Inheritance

This inheritance is comprised of a parent or root class, sub/parent class and sub class.
public class SampleClass{

  public static void main(String[]args){
    ClassC c = new ClassC();
  }
}

//parent or root class
abstract class ClassA{
  String name = "ClassA";
  int num1 = 1;
  
  ClassA(){
    System.out.println(name + " Constructor");
    System.out.println("number : " + num1);
    System.out.println();
  }
}

//sub/parent class
abstract class ClassB extends ClassA{
  String name = "ClassB";
  String parent = super.name;
  int num2 = 2;
  
  ClassB(){
    System.out.println(name + " Constructor");
    System.out.println("number : " + num2);
    System.out.println("ClassB Parent: " + parent);
    System.out.println("number : " + num1);
    System.out.println();
  }
}

//sub class
class ClassC extends ClassB{
  String name = "ClassC";
  String parent = super.name;
  int num3 = 3;
  
  ClassC(){
    System.out.println(name + " Constructor");
    System.out.println("number : " + num3);
    System.out.println("ClassC Parent: " + parent);
    System.out.println("number : " + num2);
    
    //Won't work. sub class can't directly access Parent's parent
    //class hidden members
    //System.out.println(super.name + " Parent: " + super.super.name);
    
    System.out.println(super.name + " Parent: " + super.parent);
    System.out.println("number : " + num1);
    System.out.println();
  }
}

Result
ClassA Constructor
number: 1

ClassB Constructor
number: 2
ClassB Parent: ClassA
number: 1

ClassC Constructor
number: 3
ClassC Parent: ClassB
number: 2
ClassB Parent: ClassA
number: 1
In the example above, we can see that ClassC inherits inheritable members of ClassB and ClassC. We can also see that ClassC can't directly access ClassA hidden members. In this example, ClassB is used as a bridge in order to pass the value of name variable of ClassA to ClassC.
Shadowing or member hiding is discussed in the this keyword topic.

Multilevel Inheritance Diagram
Multilevel Inheritance

Hierachical Inheritance

This inheritance is comprised of a parent class and multiple child classes.
public class SampleClass{

  public static void main(String[]args){
  
    ClassB b = new ClassB();
    ClassC c = new ClassC();
  }
}

class ClassA{
  String name = "ClassA";
  
  ClassA(){
    System.out.println(name + " Constructor");
    System.out.println();
  }
}

class ClassB extends ClassA{
  String name = "ClassB";
  
  ClassB(){
    System.out.println(name + " Constructor");
    System.out.println(name + " Parent: " + super.name);
    System.out.println();
  }
}

class ClassC extends ClassA{
  String name = "ClassC";
  
  ClassC(){
    System.out.println(name + "Constructor");
    System.out.println(name + " Parent: " + super.name);
    System.out.println();
  }
}
Hierarchical Inheritance Diagram
Multilevel Inheritance

Multiple Inheritance(Interface Only)

Java doesn't support multiple parent classes. However, a sub class can have multiple interfaces as parent class.
public class SampleClass{
  
  public static void main(String[]args){
  
    ClassC c = new ClassC();
    c.message1();
    c.message2();
  }
}

interface InterfaceA{
  default void message1(){
    System.out.println("InterfaceA");
  }
}
  
interface InterfaceB{
  default void message2(){
    System.out.println("InterfaceB");
  }
}
  
class ClassC implements InterfaceA,InterfaceB{
  
  ClassC(){
    System.out.println("ClassC Constructor");
  }
}
Default methods in interface can be used since Java8.

Multiple Inheritance Diagram
Multiple Inheritance

Hybrid Inheritance

This inheritance comprises two or more types of inheritance.
public class SampleClass{

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

interface InterfaceA{
}

interface InterfaceB{
}

//multiple inheritance
class ClassC implements InterfaceA,InterfaceB{
}

//single inheritance
class ClassD extends ClassC{
}

//hierarchical inheritance
class ClassE extends ClassD{
}

//hierarchical inheritance
class ClassF extends ClassD{
}

Hybrid Inheritance Diagram
Hybrid Inheritance