Slayt 11
Slayt 11
Encapsulation
1
Declaring a Subclass
A subclass extends properties and methods from the
superclass. You can also:
Add new properties
Add new methods
Override the methods of the superclass
2
Superclasses and Subclasses
GeometricObject1
Circle4
Rectangle1
TestCircleRectangle
Run
3
Are superclass’s Constructor
Inherited?
No. They are not inherited.
They are invoked explicitly or implicitly.
Explicitly using the super keyword.
A constructor is used to construct an instance of a class.
Unlike properties and methods, a superclass's
constructors are not inherited in the subclass. They can
only be invoked from the subclasses' constructors, using
the keyword super. If the keyword super is not explicitly
used, the superclass's no-arg constructor is
automatically invoked.
4
Using the Keyword super
The keyword super refers to the superclass
of the class in which super appears. This
keyword can be used in two ways:
To call a superclass constructor
To call a superclass method
5
CAUTION
class B { class B {
public void p(double i) { public void p(double i) {
System.out.println(i * 2); System.out.println(i * 2);
} }
} }
7
The toString() method in Object
The toString() method returns a string representation of the
object. The default implementation returns a string consisting
of a class name of which the object is an instance, the at sign
(@), and a number representing this object.
8
The instanceof Operator
Use the instanceof operator to test whether an object is an instance of a class:
9
Encapsulation
encapsulation: Hiding implementation details from
clients.
– Encapsulation forces abstraction.
separates external view (behavior) from internal
view (state)
protects the integrity of an object's data
Private fields
A field that cannot be accessed from outside the class
private type name;
– Examples:
private int id;
private String name;
16
ArrayList Example
TestArrayList Run
17
The protected Modifier
The protected modifier can be applied on data and
methods in a class. A protected data or a protected
method in a public class can be accessed by any class in
the same package or its subclasses.
Cannot be accessed if the subclasses are in a different
package.
private, default, protected, public
18
Accessibility Summary
public
protected -
default - -
private - - -
19
Visibility Modifiers
package p1;
public class C1 { public class C2 {
public int x; C1 o = new C1();
protected int y; can access o.x;
int z; can access o.y;
private int u; can access o.z;
cannot access o.u;
protected void m() {
} can invoke o.m();
} }
package p2;
20
NOTE
the final modifier can also be used on local
variables in a method. A final local
variable is a constant inside a method.
21
The final Modifier
The final class cannot be extended:
final class Math {
...
}
22