OOP in Java - Part 2
OOP in Java - Part 2
static keyword
to define a class member that will be used independently of any object of that
class
When a member is declared static, it can be accessed before any objects of its
class are created, and without reference to any object.
can declare both methods and variables to be static
Instance variables declared as static are, essentially, global variables.
When objects of its class are declared, no copy of a static variable is made.
Instead, all instances of the class share the same static variable.
Methods declared as static have several restrictions:
They can only directly call other static methods of their class.
They can only directly access static variables of their class.
They cannot refer to this or super in any way.
if you wish to call a static method from outside its class, you can do so using
the following general form:
classname.method( )
2
static keyword
3
final keyword
A field can be declared as final to prevents its contents from being modified,
making it, essentially, a constant
You can do this in one of two ways:
First, you can give it a value when it is declared.
Second, you can assign it a value within a constructor.
The first approach is probably the most common.
Here is an example:
final int FILE_NEW = 1;
final int FILE_OPEN = 2;
In addition to fields, both method parameters and local variables can be
declared final.
Declaring a parameter final prevents it from being changed within the method.
Declaring a local variable final prevents it from being assigned a value more
than once
final can also be applied to methods, and is explained when inheritance is
discussed. 4
Introducing Access Control
6
7
Nested and Inner Classes
It is possible to define a class within another class; such classes are known as
nested classes
The scope of a nested class is bounded by the scope of its enclosing class
Thus, if class B is defined within class A, then B does not exist independently
of A
A nested class has access to the members, including private members, of the
class in which it is nested
However, the enclosing class does not have access to the members of the
nested class
A nested class that is declared directly within its enclosing class scope is a
member of its enclosing class
8
Nested and Inner Classes
9
inner classes within any block scope
String is probably the most commonly used class in Java’s class library
The obvious reason for this is that strings are a very important part of
programming
The first thing to understand about strings is that every string you create is
actually an object of type String
Even string constants are actually String objects
For example, in the statement
System.out.println("This is a String, too");
the string "This is a String, too" is a String object
The second thing to understand about strings is that objects of type String are
immutable; once a String object is created, its contents cannot be altered
While this may seem like a serious restriction, it is not, for two reasons:
If you need to change a string, you can always create a new one that contains the
modifications
Java defines peer classes of String, called StringBuffer and StringBuilder, which allow
strings to be altered, so all of the normal string manipulations are still available in Java
11
Exploring the String Class
12
Methods of String class
13
Command-Line Arguments
14
Varargs: Variable-Length Arguments
A method that takes a variable number of arguments is called a variable-arity
method, or simply a varargs method.
Beginning with JDK 5, Java has included this feature
15
Varargs: Variable-Length Arguments
17
18
Type Inference with Local Variables
Recently, an exciting new feature called local variable type inference was added to the
Java language.
Beginning with JDK 10, it is now possible to let the compiler infer the type of a local
variable based on the type of its initializer, thus avoiding the need to explicitly specify
the type
local variable type inference has become a common part of the contemporary
programming environment
type inference, the context-sensitive identifier var was added
var counter; // Wrong! Initializer required.
var avg = 10.0;
int var = 1; // In this case, var is simply a user-defined identifier.
var myArray = new int[10]; // This is valid.
var[] myArray = new int[10]; // Wrong
var myArray[] = new int[10]; // Wrong
var myArray = { 1, 2, 3 }; // Wrong
Only one variable can be declared at a time;
a variable cannot use null as an initializer; and the variable being declared
cannot be used by the initializer expression
19
Local Variable Type Inference with
Reference Types
Earlier examples have shown type inference with primitive types, but it can
also be used with reference types.
var myStr = "This is a string";
one of the benefits of local variable type inference is its ability to streamline
code, and it is with reference types where such streamlining is most apparent.
The reason for this is that many class types in Java have rather long names.
FileInputStream fin = new FileInputStream("test.txt");
With the use of var, it can now be written like this:
var fin = new FileInputStream("test.txt");
20
Local Variable Type Inference with
Reference Types
21
Inheritance
Inheritance is one of the cornerstones of object-oriented programming because
it allows the creation of hierarchical classifications.
Using inheritance, you can create a general class that defines traits common to
a set of related items.
This class can then be inherited by other, more specific classes, each adding
those things that are unique to it.
In the terminology of Java, a class that is inherited is called a superclass.
The class that does the inheriting is called a subclass.
Therefore, a subclass is a specialized version of a superclass.
It inherits all of the members defined by the superclass and adds its own,
unique elements.
To inherit a class, you simply incorporate the definition of one class into
another by using the extends keyword
The general form of a class declaration that inherits a superclass:
class subclass-name extends superclass-name {
// body of class
22
Inheritance
23
Inheritance
24
Member Access and Inheritance
25
Member Access and Inheritance
26
Member Access and Inheritance
Box revisited
ColorBox
27
A Superclass Variable Can
Reference a Subclass Object
28
super keyword
when a superclass keeps the details of its implementation to itself (that is, that
keeps its data members private).
In this case, there would be no way for a subclass to directly access or
initialize these variables on its own.
Whenever a subclass needs to refer to its immediate superclass, it can do so by
use of the keyword super
super has two general forms. The first calls the superclass’ constructor.
The second is used to access a member of the superclass that has been hidden
by a member of a subclass.
29
super to Call Superclass Constructors
30
31
32
33
34
A Second Use for super
The second form of super acts somewhat like this, except that it always refers
to the superclass of the subclass in which it is used.
super.member
This second form of super is most applicable to situations in which member
names of a subclass hide members by the same name in the superclass.
35
36
Creating a Multilevel Hierarchy
37
Creating a Multilevel Hierarchy
38
Creating a Multilevel Hierarchy
39
Creating a Multilevel Hierarchy
40
Constructor invocation in
Multilevel Hierarchy
In a class hierarchy,
constructors complete
their execution in order of
derivation, from
superclass to subclass.
As, since super( ) must be
the first statement
executed in a subclass’
constructor, this order is
the same whether or not
super( ) is used.
If super( ) is not used,
then the default or
parameter-less
constructor of each
superclass will be
executed
41
Method Overriding
In a class hierarchy, when a method in a subclass has the same name and
type signature as a method in its superclass, then the method in the subclass
is said to override the method in the superclass.
When an overridden method is called from within its subclass, it will always
refer to the version of that method defined by the subclass.
The version of the method defined by the superclass will be hidden.
42
Method Overriding
If you wish to access the superclass version of an overridden method, you can
do so by using super.
43
Overriding vs Overloading
Method overriding occurs
only when the names and
the type signatures of the
two methods are identical.
If they are not, then the two
methods are simply
overloaded.
44
Dynamic Method Dispatch
Method overriding forms the basis for one of Java’s most powerful concepts:
dynamic method dispatch.
Dynamic method dispatch is the mechanism by which a call to an overridden
method is resolved at run time, rather than compile time.
Dynamic method dispatch is important because this is how Java implements
run-time polymorphism.
Java uses the fact “a superclass reference variable can refer to a subclass
object” to resolve calls to overridden methods at run time.
When an overridden method is called through a superclass reference, Java
determines which version of that method to execute based upon the type of the
object being referred to at the time the call occurs (at run time).
it is the type of the object being referred to (not the type of the reference
variable) that determines which version of an overridden method will be
executed.
45
Dynamic Method Dispatch
46
Dynamic Method Dispatch – Ex2
47
Applying Method Overriding
48
Applying Method Overriding
49
Abstract Classes
sometimes you will want to create a superclass that only defines a generalized
form that will be shared by all of its subclasses, leaving it to each subclass to
fill in the details.
Such a class determines the nature of the methods that the subclasses must
implement.
One way this situation can occur is when a superclass is unable to create a
meaningful implementation for a method.
The definition of area( ) is simply a placeholder. It will not compute and
display the area of any type of object.
As you will see as you create your own class libraries, it is not uncommon for
a method to have no meaningful definition in the context of its superclass.
You can handle this situation two ways.
Consider the class Triangle. It has no meaning if area( ) is not defined. In this
case, you want some way to ensure that a subclass does, indeed, override all
necessary methods. Java’s solution to this problem is the abstract method.
50
Abstract Classes
51
Abstract Classes
52
Abstract Classes
53
54
final with Inheritance
55
final with Inheritance
56
final to Prevent Inheritance
57
Local Variable Type Inference and
Inheritance
local variable type inference which is supported by the reserved type name var
type of a variable is based on the declared type of its initializer
Recall that a superclass reference can refer to a derived class object, and this
feature is part of Java’s support for polymorphism
If the initializer is of the superclass type, that will be the inferred type of the
variable.
It does not matter if the actual object being referred to by the initializer is an
instance of a derived class
58
Local Variable Type Inference and
Inheritance
59
Local Variable Type Inference and
Inheritance
60
The Object Class
61
The Object Class
Object defines the following methods, which means that they are available in
every object.
62