Polymorphism, Object Type casting, Abstraction, interfaces

Lesson 303.10 - Object-Oriented Programming, Polymorphism, Object Type Casting, Abstraction, and Interfaces

Section 1

Polymorphism

One of the pillars of Object-Oriented Programming.

Learning Objectives:

  • Define the Polymorphism concept.

  • Describe Object Type Casting in Java.

  • Describe the "instanceof" Operator.

  • Demonstrate how to use Polymorphism concept in Java.

Table of Contents

  • Topic 1: Object Type Casting in Java.

  • Topic 2: Overview of Polymorphism.

  • Topic 3: Introduction to Polymorphism.

  • Topic 4: The "instanceof" Operator.

Topic 1: Object Type Casting in Java

  • Parent extends Child c = new parent()

  • Child Parent p = new Child() upcasting

  • Upcasting - Parent p = new Child(); Child c = (Child) p;

  • Trying to downcast - Downcasting

There are two types of Object Type Casting:

  1. Upcasting

  2. DownCasting.

Casting from a subclass to a superclass is called Upcasting. Typically, the upcasting is implicitly performed by the compiler. Upcasting is closely related to inheritance. Casting from a superclass to a subclass is called Downcasting. If it is performed directly, the compiler gives an error message as ClassCastException is thrown at runtime, as shown below.

To learn more about Object Casting, visit the Wiki document.

Child child2 = (Child) parent;

Topic 2: Overview of Polymorphism

  • Polymorphism, which means “many forms,” is an essential object-oriented programming (OOP) concept. In other words, it is a variable, method or object’s ability to take on many forms. This occurs when we have many classes that are related to each other by inheritance.

  • Inheritance lets us inherit variable and methods from another class. Polymorphism uses those methods to perform different tasks, allowing us to perform a single action in different ways.

Topic 3: Introduction to Polymorphism

Polymorphism allows us to use inherited properties to perform different tasks. We can achieve Polymorphism in Java using:

  • Method Overriding (Non Abstraction, Abstraction and interfaces).

  • Method Overloading.

  • Operator Overriding.

Consider the following illustration. Suppose that our program uses many kinds of animals. We should design a superclass called Animal, which defines the public (common) behaviors of all of the Animals. For example, we would like all of the Animals to have a method called animalsound() and animaleat(), which returns the specific output, or prints a specific output.

Animal

  • animalsound()

  • animaleat()

Superclass defines the common behaviors of all subclasses.

Cat

  • animalsound()

  • animaleat()

Pig

  • animalsound()

  • animaleat()

Dog

  • animalsound()

  • animaleat()

Subclasses provide the actual implementations.

Example: Polymorphism

Create 4 classes as shown below and write a code into those classes. Now we can create Pig and Dog objects and call the animalSound() method on both of them:

public class myMain {
  public static void main(String[] args) {
Animal myAnimal = new Animal(); // Create a Animal object // it’s fine because a Pig is a animal by inheritance
Animal myPig = new Pig(); // Create a Pig object // it’s fine because a Dog is a animal by inheritance
    Animal myDog = new Dog();  // Create a Dog object
    myAnimal.animalSound();
    myPig.animalSound();
    myDog.animalSound();
} }
 public class Animal {
  public void animalSound() {
System.out.println("The animal makes a sound"); }}
 public class Pig extends Animal {
  public void animalSound() {
    System.out.println("The pig says: wee wee");
  }}
 public class Dog extends Animal {
  public void animalSound() {
    System.out.println("The dog says: bow wow");
  }}

Topic 4: The "instanceof" Operator

  • Java provides a binary operator called instanceof. This operator evaluates to true or false, depending on whether the variable refers to an object of type Class.

  • Also, instanceof returns true if the variable is a child of Class. It can also be a grandchild or great-grandchild, and beyond of the class.

The syntax is as follows: anObject instanceof aClass Example:

myAnimal instanceof Animal;  //true
myAnimal instanceof Pig;  //false
myPig instanceof Pig;  //True
myPig instanceof Animal;  //True

Example: Polymorphism and instanceof

Let’s use the previous example, but make changes in our myMain() class. Now we can create Pig and Dog objects and call the animalSound() method on both of them:

public class Animal {
  public void animalSound() {
System.out.println("The animal makes a sound"); }}
 public class myMain {
  public static void main(String[] args) {
    Animal myAnimal = new Animal();  // Create a Animal object
  // it’s fine because a Pig is a animal by inheritance
    Animal myPig = new Pig();  // Create a Pig object
    Animal myDog = new Dog();  // Create a Dog object
    myAnimal.animalSound();
    myPig.animalSound();
    myDog.animalSound();
System.out.println(myAnimal instanceof Animal);
System.out.println(myAnimal instanceof Pig);  //false
System.out.println(myPig instanceof Pig);  //True
System.out.println(myPig instanceof Animal);  //True
System.out.println(myAnimal instanceof Dog);  //false
System.out.println(myDog instanceof Animal);  //True
System.out.println(myDog instanceof Dog);  //True
} }

Section 1 Hands-On Lab

Complete the GLAB - 303.10.1 - Inheritance and Object Type Casting. You can find the lab on Canvas under the assignment section. If you have any technical questions while performing the lab activity, ask your instructors for assistance.

Section 2

Abstraction

One of the pillars of Object-Oriented Programming.

Learning Objectives:

  • Explain the Abstraction Concept.

  • Demonstrate how to use Abstract Classes and the Abstract Method.

  • Identify when to use an Abstraction.

  • Describe how to use Abstraction.

Table of Contents

  • Topic 5: Overview of Abstraction.

  • Topic 6a: Abstraction - Abstract Methods.

  • Topic 6b: Abstraction - Abstract Classes.

  • Topic 6c: Why Use an Abstract Class?

Topic 5: Overview of Abstraction

  • Abstraction in programming is about hiding unwanted details while showing the most essential information, and separating the implementation from the declaration.

  • Abstraction in general means hiding complexities and presenting only with essential properties and behavior.

Abstraction can be achieved through:

  • Abstract methods.

  • Abstract classes and interfaces.

  • The abstract keyword is a non-access modifier used for classes and methods.

Topic 6: Abstraction - Abstract Methods

Abstract Variables do not exist. The closest thing to an abstract variable is a variable with no declared value. Regular variables can exist in abstract classes.

  • We declare a method as abstract by adding the ‘abstract’ keyword in front of the method declaration. An abstract method has NO implementation or body. It just has a method signature:

    • Syntax: abstract Accessmodifier return-datatype MethodName(parameter-list);

    • Example: abstract public double getArea();

  • The body of abstract method is provided by the subclass (inherited from).

  • The declaration of an abstract method must end with a semicolon (;).

An abstract method CAN NOT be declared final, as the final method cannot be overridden. An abstract method, on the other hand, must be overridden in a descendant before it can be used. An abstract method CAN NOT be private (which generates a compilation error). This is because the private method is not visible to the subclass, and thus, cannot be overridden.

Topic 6b: Abstraction - Abstract Classes

  • Abstract Classes:

    • Can have both abstract and regular methods.

    • Cannot be instantiated, which means that an abstract class does not allow you to create objects of its type.

    • Are declared by using abstract keyword.

    • Can be extended by another class that will provide implementation for abstract methods.

  • Classes extending an Abstract Class:

    • Must provide logic for every abstract method.

    • Must be substituted wherever the Abstract Class is needed.

Example: Abstract Class and Methods

public abstract class AbstractStudent {
   static final protected String COLLAGENAME = "Per scholas";
   protected String username;
   // abstract method
   public abstract  void displayinformation();
   public abstract String[] getFullName(String[] fullname);
   // regular methods
   public String getUsername() {
       return username;
   }
   public void setUsername(String username) {
       this.username = username;
   }
   public String getPassword() {
       return password;
   }
   public void setPassword(String password) {
       this.password = password;
   }
   public int getRollnumber() {
       return rollnumber;
   }
   public void setRollnumber(int rollnumber) {
       this.rollnumber = rollnumber;
   }
   protected String password;
   protected int rollnumber;
}
public class StudentService extends AbstractStudent {
   // Assume this gpa is coming from Database
   private double gpa = 4.2;
   @Override
   public void displayinformation() {
     System.out.println("Welcome to " + this.COLLAGENAME);
     System.out.println("Your username is " + this.username + " and password is " + this.password);
     System.out.println(" Your roll number is "+ this.rollnumber + " and You got  " + this.gpa);
   }
   @Override
   public String[] getFullName(String[] name) {
       String[] fullname = name;
       return fullname;
   }
}

Topic 6c: Why Use an Abstract Class?

An Abstract Class:

  • Allows you to make sure that the coder using this class can only see the essential methods.

    • Prevents confusion from other programmers.

    • Keeps your code clean, readable, and intuitive.

  • Reduces the code you have to write.

    • Rather than creating different methods to implement each individual type of display, use a single method that references the abstract class.

    • Each child class might require the same method with the same logic. Instead of writing that method over and over, write it once in the abstract class.

  • Provides a basic structure for each of your implementing classes.

Section 2 Hands-On Lab

Complete the GLAB - 303.10.3 - Abstraction. You can find the lab on Canvas under the Assignment section. If you have any technical questions while performing the lab activity, ask the instructors for assistance.

Practice Assignment

Complete this assignment, PA 303.10.1 - Practice Assignment - Polymorphism and inheritance. You can find this assignment on Canvas, under the Assignment section. Use your office hours to complete this assignment. If you have technical questions while performing the practice assignment, ask your instructors for assistance.

Summary

Using Polymorphism, it is possible to write a method that correctly processes lots of different types of functionalities with the same name. Polymorphism also allows gaining consistency in our code. Polymorphism allows a superclass to define methods that are common to all of its derived classes while allowing subclasses to specify the additional implementation of some or all of those methods. Polymorphism can achieve by Abstract classes and interfaces. Abstraction in programming is about hiding unwanted details while showing the most essential information, and separating the implementation from the declaration. Abstraction can be achieved through Abstract methods, Abstract classes, and interfaces.

Section 2

Abstraction One of the pillars of Object-Oriented Programming

Learning Objectives:

By the end of lesson, learners will be able to:

  • Explain the Abstraction Concept.

  • Demonstrate how to use Abstract Classes and the Abstract Method.

  • Identify when to use an Abstraction.

  • Describe how to use Abstraction.

Table of contents

  • Topic 5: Overview of Abstraction.

  • Topic 6a: Abstraction - Abstract Methods.

  • Topic 6b: Abstraction - Abstract Classes.

  • Topic 6c: Why Use an Abstract Class?

Topic 5: Overview of Abstraction

  • Abstraction:

    • Abstraction in programming is about hiding unwanted details while showing the most essential information, and separating the implementation from the declaration.

    • Abstraction in general means hiding complexities and presenting only with essential properties and behavior.

  • Abstraction can be achieved through:

    • Abstract methods.

    • Abstract classes and interfaces.

    • An abstract keyword is a non-access modifier used for classes and methods.

Topic 6: Abstraction - Abstract Methods

  • Abstract Variables do not exist. The closest thing to an abstract variable is a variable with no declared value. Regular variables can exist in abstract classes.

  • Abstract Methods:

    • We declare a method as abstract by adding the ‘abstract’ keyword in front of the method declaration. An abstract method has NO implementation or body. It just has a method signature:

      • Syntax: abstract Accessmodifier return-datatype MethodName(parameter-list);

      • Example: abstract public double getArea();

    • The body of abstract method is provided by the subclass (inherited from).

    • The declaration of an abstract method must end with a semicolon (;).

  • An abstract method CAN NOT be declared final, as the final method cannot be overridden. An abstract method, on the other hand, must be overridden in a descendant before it can be used.

  • An abstract method CAN NOT be private (which generates a compilation error). This is because the private method is not visible to the subclass, and thus, cannot be overridden.

Topic 6a: Abstraction - Abstract Methods (continued)

  • Classes extending an Abstract Class:

    • Must provide logic for every abstract method.

    • Must be substituted wherever the Abstract Class is needed.

Topic 6b: Abstraction - Abstract Classes

  • Abstract Classes:

    • Can have both abstract and regular methods.

    • Cannot be instantiated, which means that an abstract class does not allow you to create objects of its type.

    • Are declared by using abstract keyword.

    • Can be extended by another class that will provide implementation for abstract methods.

Example: Abstract Class and Methods

public abstract class AbstractStudent {
   static final protected String COLLAGENAME = "Per scholas";
   protected String username;
   // abstract method
   public abstract  void displayinformation();
   public abstract String[] getFullName(String[] fullname);
   // regular methods
   public String getUsername() {
       return username;
   }
   public void setUsername(String username) {
       this.username = username;
   }
   public String getPassword() {
       return password;
   }
   public void setPassword(String password) {
       this.password = password;
   }
   public int getRollnumber() {
       return rollnumber;
   }
   public void setRollnumber(int rollnumber) {
       this.rollnumber = rollnumber;
   }
   protected String password;
   protected int rollnumber;
}

public class StudentService extends AbstractStudent {
   // Assume this gpa is coming from Database
   private double gpa = 4.2;
   @Override
   public void displayinformation() {
     System.out.println("Welcome to " + this.COLLAGENAME);
     System.out.println("Your username is " + this.username + " and password is " + this.password);
     System.out.println(" Your roll number is "+ this.rollnumber + " and You got  " + this.gpa);
   }
   @Override
   public String[] getFullName(String[] name) {
       // TODO Auto-generated method stub
       String[] fullname = name;
       return fullname;
   }
}

public class MyRunner {
   public static void main (String [] args) {
       AbstractStudent student = new StudentService();
       student.setUsername("Mike123");
       student.setPassword("password1234567");
       student.setRollnumber(0024);
       student.displayinformation();
       String[] name = {"Mike", "Gabriel"};
       System.out.println(Arrays.toString(student.getFullName(name)));
   }
}

Output:

Welcome to Per scholas.
Your username is Mike123, and your password is password1234567
Your roll number is 20 and you got 4.2.
[Mike, Gabriel]

Topic 6c: Why Use an Abstract Class?

  • An Abstract Class:

    • Allows you to make sure that the coder using this class can only see the essential methods.

      • Prevents confusion from other programmers.

      • Keeps your code clean, readable, and intuitive.

    • Reduces the code you have to write.

      • Rather than creating different methods to implement each individual type of display, use a single method that references the abstract class.

      • Each child class might require the same method with the same logic. Instead of writing that method over and over, write it once in the abstract class.

    • Provides a basic structure for each of your implementing classes.

Hands-On Lab

Complete the GLAB - 303.10.3 - Abstraction. You can find the lab on Canvas under the Assignment section. If you have any technical questions while performing the lab activity, ask the instructors for assistance.

Section 3: Interfaces

The Interface is a design contract.

Learning Objectives:

By the end of this lesson, learners will be able to:

  • Describe and explain an interface.

  • Demonstrate how to implement the interface.

  • Explain when to use an interface and an abstract class while designing applications.

  • Describe the key differences between an interface and an abstract class.

Table of contents

  • Topic 7: Overview of Interfaces.

  • Topic 8: Abstraction vs. Encapsulation.

  • Topic 9: Abstract Class vs. Interface.

Topic 7: Overview of Interfaces

  • In order to define an interface, instead of using a keyword "class" for normal classes, you must use the keyword "interface."

  • An interface contains only abstract methods and final variables. Because of this, you do not need to specify an abstract keyword and a public modifier before methods. Interface methods are public and abstract. Additionally, you do not need to specify final, public, or static keywords before variables. They are automatically set to those states. Interface variables are by default, or implicitly public, static, and final.

  • Interfaces cannot be instantiated.

  • Interfaces cannot have constructors because we cannot instantiate them.

  • An interface cannot extend any class but a class can implement one or multiple interfaces.

    • When a class implements one or multiple interfaces, it must provide implementation for ALL abstract methods.

    • Example: public class Circle implements interfaceOne, InterfaceTwo.

Overview of Interfaces (continued)

  • An interface provides a form, protocol, standard, contract, specification, set of rules, and an interface, for all objects that implements it. Any object that implements an interface agrees to follow the requirements.

  • In Java, an abstract class and an interface are used to separate the public interface of a class from its implementation so as to allow the programmer to program at the interface instead of at the various implementation.

  • Interface Naming Convention:

    • Use an adjective (typically ends with "able") consisting of one or more words. Each word shall be initial capitalized (camel-case). For example, Serializable, Extenalizable, Movable, Clonable, Runnable, etc.

Example Interface

public class StudentService extends AbstractStudent implements College {
    private double gpa = 4.2;
    @Override
    public void displayinformation() {
        System.out.println("Welcome to " + this.COLLAGENAME);
        System.out.println("Your username is " + this.username + " and password is " + this.password);
        System.out.println(" Your roll number is "+ this.rollnumber + " and You got  " + this.gpa);
    }
    @Override
    public String[] getFullName(String[] name) {
        String[] fullname = name;
        return fullname;
    }
    @Override
    public void getCourseName(){
        System.out.println("Full Stack Java development");
    }
    public void getIAName() {
        System.out.println("Do not Assign");
    }
    public void getInstructor(){
        System.out.println("Your Instructor name is James");
    }
    public void getProgramDuration(){
        System.out.println("Program Duration is approximately 15 week");
    }
}
public interface College {
    // All variables are by default public, static and final
    String COLLAGENAME = "Perscholas";
    String Address = "23-66ST";
    void getCourseName();
    void getIAName();
    void getInstructor();
    void getProgramDuration();
}

Example Interfaces (continued)

public class MyRunner {
    public static void main (String [] args) {
        AbstractStudent student = new StudentService();
        student.setUsername("Mike123");
        student.setPassword("password1234567");
        student.setRollnumber(0024);
        student.displayinformation();
        String[] name = {"Mike", "Gabriel"};
        System.out.println(Arrays.toString(student.getFullName(name)));
        StudentService st = new StudentService();
        st.getCourseName();
        st.getInstructor();
        st.getIAName();
        st.getProgramDuration();
    }
}

Output

Welcome to Perscholas.
Your username is Mike123, and your password is password1234567.
Your roll number is 20 and You got 4.2.
[Mike, Gabriel]
Full Stack Java development.
Your Instructor name is James.
Do not Assign.
Program Duration is approximately 15 weeks.

Topic 8: Abstraction vs. Encapsulation

AbstractionEncapsulation

Solves the problem at the design level.

Solves the problem at the implementation level.

Allows showing important aspects while hiding implementation details.

Binds code and data together into a single unit, and hides it from the world.

Topic 9: Abstract Class vs. Interface

Basis for ComparisonAbstract ClassInterface

Methods

Can have abstract as well as other methods.

Can have only abstract methods.

Final Variables

May contain final and non-final variables.

Variables declared are final by default.

Accessibility of Data Members

Can be private, public, etc.

Public by default.

Implementation

Can provide the implementation of an interface.

Cannot provide the implementation of an abstract class.

When to use

- The logic for some methods will always be the same in child classes.

  • You can create logic that will be useful for all child classes.

  • You want to create variables that all child classes will use and set values for.

  • You want to create a structure only.

  • The only variables you need in all child classes will have constant values. | - When you want to define a contract specifying how different parts of your application should interact.

  • When you want to define a contract specifying what a class can do, not how it does it. |

Hands-On Lab

Complete GLAB - 303.10.4 - How to use Interface. You can find this lab on Canvas under the Assignment section.

Practice Assignment

You will find the below Practice Assignment on Canvas under the Assignment section.

  • PA 303.10.2 - Practice Assignment - Abstraction (Hackerank)

  • PA 303.10.3 - Practice Assignment - Polymorphism and Interface

Use your office hours to complete this assignment. If you have any technical questions while performing the practice assignment activity, ask your instructors for assistance.

Section 4

Learning Objectives:

  • Define Object Class, Enumerations, and Nested class.

  • Describe Enumerations and enum keywords.

Table of contents

  • Object as a Superclass.

  • Enumerations.

  • Nested and Inner Classes.

Topic 10: Object as a Superclass

  • All Java classes are subclasses of the Object class.

  • This feature is built into the language. You do not need to explicitly extend the Object class.

  • We can observe this with our Thingy class in the screenshot:

    • Thingy class does not explicitly extend any class, and declares no methods.

    • If we create a Thingy object in Eclipse, we can see that it has nine methods that we can use. These methods are inherited from the Object class.

Method of Object Class:

MethodDescription

boolean equals(Object other)

Returns true when other is equal to this. You will need to override this method often; it is used by (for example) the Collection classes to test for object equality.

int hashCode()

Returns a hash code for the object. You should override this any time that you override equals.

Class<?> getClass()

Returns an object, which represents the Class from which the object was defined. The Class object allows you to get meta-information about the class, such as what interfaces it implements, its constructors, and what methods it declares. This allows a specialized type of programming called reflection.

String toString()

Returns a String representation of the object. You should override this whenever it is useful.

Visit Wiki document for more information about Object as a Superclass.

Topic 11: Enumerations

  • In Java, an enum (short for enumeration) is a special type.

  • It contains a fixed set of constant values.

  • We use the enum keyword to declare enums. The enum keyword signals to the Java compiler that this type definition is an enum.

  • Enum can be declared either outside the class, inside the class, or inside the interface. However, enums cannot be declared inside of a method.

    • An enum class may include a constructor just like a regular class, but an enum constructor is private or private-packaged. This means that either they are accessible within a class or within a package.

Example - enum Keyword Inside A Class

In this example, we are going to initialize four enumerators: spade, heart, diamond, and club, which belong to an enumerated type called “cards.”

public class MyMain {
   enum cards {
        spade, club, heart, diamond;
   }
   public static void main(String[] args) {
       /* stored each of the enumerators in the reference variables a1,a2,a3,a4
       respectively.  note that the new keyword was not used here  */
        cards a1 = cards.spade;
        cards a2 = cards.club;
        cards a3 = cards.heart;
        cards a4 = cards.diamond;
        System.out.println("Enumerators are: "+ a1 + "," + a2 + "," + a3 + "," + a4);
        System.out.println("----- printing using enhanced loop -----");
        for (cards index:cards.values()) {
            System.out.println(index);
        }
   }
}

Output

Enumerators are: spade, club, heart, diamond
----- printing using enhanced loop--
spade
club
heart
diamond

Example - Enum Class

public enum MyDatabaseconnection {
    ORACLEDB("ORACLE DATABASE IS CONNECTION ..."),
    SQLDBB("SQL DATABASE IS CONNECTING..."),
    POSTGRESSQL("POSTGRES DATABASE IS CONNECTING");
    // Class variable
    private final String establishDatabaseConnection;
    // private enum constructor
    private MyDatabaseconnection(String establishDatabaseConnection) {
        this.establishDatabaseConnection = establishDatabaseConnection;
    }
    // getter
    public String getEstablishDatabaseConnection() {
        return establishDatabaseConnection;
    }
}
public class myMain {
    public static void main(String[] args) {
        MyDatabaseconnection db = MyDatabaseconnection.ORACLEDB;
        System.out.println(db);
        System.out.println(db.getEstablishDatabaseConnection());
    }
}

Output

ORACLEDB
ORACLE DATABASE IS CONNECTION ...

Topic 11: Nested and Inner Classes

  • Just like a Class can contain methods and variables, classes can also contain more classes. In Java, nested classes are of two types: nested and inner.

  • If the “class inside a class” is static, we call it a nested class.

    • This means you do not have to instantiate a nested class to use it.

  • If the “class inside a class” is not static, we call it an inner class(non-static class).

    • This means you must instantiate an inner class to use it.

  • The nested class and the inner class behave as any other class:

    • It can have variables and methods.

    • It can be called from elsewhere.

    • The only difference is that they both exist inside of another class.

Visit Wiki document for more information and an explanation about Nested and Inner classes.

Summary

  • All Java classes are subclasses of Object class.

  • Interfaces (if any) - comma-separated list of interfaces implemented by the class, if any, and preceded by the keyword implements. A class can implement more than one interface.

  • In Java, enum types are considered to be a special type of class. An enumeration is a data type that consists of a set of named values that represent integral constants, known as enumeration constants. An enumeration is also referred to as an enumerated type because you must list (enumerate) each of the values in creating a name for each of them.

  • It is possible to define a class within another class, such classes are known as nested classes. They enable you to logically group classes that are only used in one place.

Last updated