0% found this document useful (0 votes)
15 views22 pages

Slayt 11

Uploaded by

AHMET ÖZEN
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views22 pages

Slayt 11

Uploaded by

AHMET ÖZEN
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 22

Chapter 11 Inheritance and

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

• You must use the keyword super to call


the superclass constructor. Invoking a
superclass constructor’s name in a
subclass causes a syntax error.
• Java requires that the statement that uses
the keyword super appear first in the
constructor.
6
Overriding vs. Overloading
public class Test { public class Test {
public static void main(String[] args) { public static void main(String[] args) {
A a = new A(); A a = new A();
a.p(10); a.p(10);
a.p(10.0); a.p(10.0);
} }
} }

class B { class B {
public void p(double i) { public void p(double i) {
System.out.println(i * 2); System.out.println(i * 2);
} }
} }

class A extends B { class A extends B {


// This method overrides the method in B // This method overloads the method in B
public void p(double i) { public void p(int i) {
System.out.println(i); System.out.println(i);
} }
} }

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.

Loan loan = new Loan();


System.out.println(loan.toString());

The code displays something like Loan@15037e5 . This


message is not very helpful or informative. Usually you should
override the toString method so that it returns a digestible string
representation of the object.

8
The instanceof Operator
Use the instanceof operator to test whether an object is an instance of a class:

Object myObject = new Circle();


// Some lines of code
/**
Perform casting if myObject is an instance of Circle
*/
if (myObject instanceof Circle) {
System.out.println("myObject is instance of Circle");
...
}

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;

 Client code won't compile if it accesses private


fields:
Accessing private state
Accessing private state
// A "read-only" access to the x field
public int getX() {
return x;
}
// Allows clients to change the x field
public void setX(int newX) {
x = newX;
}
– Client code will look more like this:
System.out.println(p1.getX());
p1.setX(14);
Example: Point class
// A Point object represents an (x, y) location.
public class Point {
private int x;
private int y;
public Point(int initialX, int initialY) {
x = initialX;
y = initialY;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public double distanceFromOrigin() {
return Math.sqrt(x * x + y * y);
}
public void setLocation(int newX, int newY) {
x = newX;
y = newY;
}
public void translate(int dx, int dy) {
setLocation(x + dx, y + dy);
}
}
Benefits of encapsulation
 Abstraction between object and clients
 Protects object from unwanted access
– Example: Can't fraudulently increase an Account's
balance.
 Can constrain objects' state (invariants)
– Example: Only allow Accounts with non-negative
balance.
– Example: Only allow Dates with a month from 1-12.
The ArrayList Class
You can create an array to store objects. But the array’s size is fixed
once the array is created. Java provides the ArrayList class that can
be used to store an unlimited number of objects.
java.util.ArrayList
+ArrayList() Creates an empty list.
+add(o: Object) : void Appends a new element o at the end of this list.
+add(index: int, o: Object) : void Adds a new element o at the specified index in this list.
+clear(): void Removes all the elements from this list.
+contains(o: Object): boolean Returns true if this list contains the element o.
+get(index: int) : Object Returns the element from this list at the specified index.
+indexOf(o: Object) : int Returns the index of the first matching element in this list.
+isEmpty(): boolean Returns true if this list contains no elements.
+lastIndexOf(o: Object) : int Returns the index of the last matching element in this list.
+remove(o: Object): boolean Removes the element o from this list.
+size(): int Returns the number of elements in this list.
+remove(index: int) : Object Removes the element at the specified index.
+set(index: int, o: Object) : Object Sets the element at the specified index.

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

Modifier Accessed Accessed Accessed Accessed


on members from the from the from a from a different
in a class same class same package subclass package

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;

public class C3 public class C4 public class C5 {


extends C1 { extends C1 { C1 o = new C1();
can access x; can access x; can access o.x;
can access y; can access y; cannot access o.y;
can access z; cannot access z; cannot access o.z;
cannot access u; cannot access u; cannot access o.u;
can invoke m(); can invoke m(); cannot invoke o.m();
} } }

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 {
...
}

 The final variable is a constant:


final static double PI = 3.14159;

 The final method cannot be


overridden by its subclasses.

22

You might also like