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:
Upcasting
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:
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:
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:
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
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
Output:
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
Example Interfaces (continued)
Output
Topic 8: Abstraction vs. Encapsulation
Abstraction | Encapsulation |
---|---|
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 Comparison | Abstract Class | Interface |
---|---|---|
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:
Method | Description |
---|---|
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.”
Output
Example - Enum Class
Output
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