Week 8 – Introduction to Inheritance and Enumerated type
Week 8 Description
This week, we see that you do not always have to start from scratch when creating a
new user-defined class. Often, we use an existing class as a starting point, and modify
it to create a new class. This process is called Inheritance, and it's the another one of
the big deals in Object Oriented programming. We’ll discuss enumerated types.
Inheritance
Inheritance allows an object of one class to acquire the properties and methods of
another class.
1
Week 8 – Introduction to Inheritance and Enumerated type
Inheritance is central to object-oriented (OO) programming in Java and other OO
languages. The key concept is creating a new class from an existing one. The new
class is called a subclass and the original one a superclass.
Here's another example:
2
Week 8 – Introduction to Inheritance and Enumerated type
The Object Class
Every class in Java is, either directly or indirectly, a subclass of a Java library class
called Object. Therefore, every class inherits the methods of Object. The subclass can
either keep these methods unchanged, or override them. Some methods of the Object
class:
3
Week 8 – Introduction to Inheritance and Enumerated type
Enumerated Types
[Link]
In few cases, a variable should only hold a restricted set of values. For example, you
may want to represent clothes in four sizes: small, medium, large, and extra large. It
could be an error-prone setup to encode these sizes as integers 1, 2, 3, 4 or characters
S, M, L, XL because there is a possibility for a variable to hold a wrong value such as 0
or m.
In this situation, we can define our own enumerated type. An enumerated type has a
finite number of named values or constants. To represent cloth sizes, we can write:
enum Size {SMALL, MEDIUM, LARGE, EXTRA_LARGE};
To declare a variable of enumerated type, we can write:
Size clothSize = [Link];
A variable of type Size can hold only one of the values listed in the type declaration, or
the special value null that indicates that the variable is not set to any value at all.
Enumeration Classes
We can add constructors, methods, and fields to an enumerated type. Keep in mind that
the constructors are only invoked when the enumerated constants are constructed.
public enum Size {
SMALL("S"),MEDIUM("M"), LARGE("L"),EXTRA_LARGE("XL");
private String abbreviation;
//constructor of an enumeration is automatically private
Size(String abbr){
[Link] = abbr;
public String getAbbreviation(){
return abbreviation;
4
Week 8 – Introduction to Inheritance and Enumerated type
The constructor of an enumeration is always private. We can omit the private modifier.
However, it is a syntax error to declare an enum constructor as public.
All enumerated types are subclasses of the class Enum. Among all the inherited
methods, the most useful one is toString. Here, toString() returns the name of the
enumerated constant. For instance, [Link]() returns the string “SMALL”.