Você está na página 1de 28

Using Encapsulation and Constructors

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.


Objectives

After completing this lesson, you should be able to:


• Use access modifiers
• Describe the purpose of encapsulation
• Implement encapsulation in a class
• Create a constructor

11 - 2 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.


Topics

• Encapsulation
• Constructors

11 - 3 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.


Overview

• Encapsulation means hiding object fields by making all


fields private:
– Use getter and setter methods.
– In setter methods, use code to ensure that values are valid.
• Encapsulation mandates programming to the interface:
– Data type of the field is irrelevant to the caller method.
– Class can be changed as long as interface remains same.
• Encapsulation encourages good object-oriented (OO)
design.

11 - 4 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.


public Modifier

public class Elevator {


public boolean doorOpen=false;
public int currentFloor = 1;
public final int TOP_FLOOR = 10;
public final int MIN_FLOOR = 1;

... < code omitted > ...

public void goUp() {


if (currentFloor == TOP_FLOOR) {
System.out.println("Cannot go up further!");
}
if (currentFloor < TOP_FLOOR) {
currentFloor++;
System.out.println("Floor: " + currentFloor);
}
}
}

11 - 5 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.


Dangers of Accessing a public Field

Elevator theElevator = new Elevator();

theElevator.currentFloor = 15; Could cause a problem!

11 - 6 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.


private Modifier

public class Elevator {


private boolean doorOpen=false;
private int currentFloor = 1; None of these fields
private final int TOP_FLOOR = 10; can now be
private final int MIN_FLOOR = 1; accessed from
another class using
dot notation.
... < code omitted > ...

public void goUp() {


if (currentFloor == TOP_FLOOR) {
System.out.println("Cannot go up further!");
}
if (currentFloor < TOP_FLOOR) {
currentFloor++;
System.out.println("Floor: " + currentFloor);
}
}
}

11 - 7 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.


Trying to Access a private Field

Elevator theElevator = new Elevator();

theElevator.currentFloor = 15; not permitted

NetBeans will
show an error.
You can get an
explanation if
you place your
cursor here.

11 - 8 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.


private Modifier on Methods

public class Elevator { Should this method


... < code omitted > ... be private?

private void setFloor() {


int desiredFloor = 5;
while ( currentFloor != desiredFloor ){
if (currentFloor < desiredFloor) {
goUp();
} else {
goDown();
}
}
}

public void requestFloor(int desiredFloor) {


... < contains code to add requested floor to a queue > ...
}

11 - 9 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.


Interface and Implementation

Elevator
Control Panel

4 Public Access

3 Public Access

2 Public Access

1 Public Access

Elevator 1 Going Up Elevator 2 Going Down

11 - 10 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.


Get and Set Methods

public class Shirt {


private int shirtID = 0; // Default ID for the shirt
private String description = "-description required-"; // default
// The color codes are R=Red, B=Blue, G=Green, U=Unset
private char colorCode = 'U';
private double price = 0.0; // Default price for all items

public char getColorCode() {


return colorCode;
}
public void setColorCode(char newCode) {
colorCode = newCode;
}
// Additional get and set methods for shirtID, description,
// and price would follow

} // end of class

11 - 11 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.


Using Setter and Getter Methods

public class ShirtTest {


public static void main (String[] args) {
Shirt theShirt = new Shirt();
char colorCode;

// Set a valid colorCode


theShirt.setColorCode('R');
colorCode = theShirt.getColorCode();
// The ShirtTest class can set and get a valid colorCode
System.out.println("Color Code: " + colorCode);

// Set an invalid color code


theShirt.setColorCode('Z'); not a valid color code
colorCode = theShirt.getColorCode();
// The ShirtTest class can set and get an invalid colorCode
System.out.println("Color Code: " + colorCode);
}

11 - 12 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.


Setter Method with Checking

public void setColorCode(char newCode) {


switch (newCode) {
case 'R':
case 'G':
case 'B':
colorCode = newCode;
break;
default:
System.out.println("Invalid colorCode. Use R, G, or B");
}
}

11 - 13 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.


Using Setter and Getter Methods

public class ShirtTest {


public static void main (String[] args) {
Shirt theShirt = new Shirt();
System.out.println("Color Code: " + theShirt.getColorCode());

// Try to set an invalid color code


Shirt1.setColorCode('Z'); not a valid color code
System.out.println("Color Code: " + theShirt.getColorCode());
}

Output:
Color Code: U Before call to setColorCode() – shows default value
Invalid colorCode. Use R, G, or B call to setColorCode prints error message
Color Code: U colorCode not modified by invalid argument passed to setColorCode()

11 - 14 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.


Encapsulation: Summary

Encapsulation protects data:


• By making all fields private
– Use getter and setter methods.
– In setter methods, use code to check whether values are
valid.
• By mandating programming to the interface
– Data type of the field is irrelevant to the caller method.
– Class can be changed as long as interface remains same.
• By encouraging good OO design

11 - 15 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.


Topics

• Encapsulation
• Constructors

11 - 16 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.


Initializing a Shirt Object

public class ShirtTest {


public static void main (String[] args) {
Shirt theShirt = new Shirt();

// Set values for the Shirt


theShirt.setColorCode('R');
theShirt.setDescription("Outdoors shirt");
theShirt.price(39.99);

11 - 17 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.


Constructors

• Constructors are method-like structures in a class:


– They have the same name as the class.
– They are usually used to initialize fields in an object.
– They can receive arguments.
– They can be overloaded.
• All classes have at least one constructor:
– If there are no explicit constructors, the Java compiler
supplies a default no-argument constructor.
– If there are one or more explicit constructors, no default
constructor will be supplied.

11 - 18 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.


Creating Constructors
Syntax:
[modifiers] class ClassName {

[modifiers] ClassName([arguments]) {
code_block
}
}

11 - 19 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.


Creating Constructors

public class Shirt {


public int shirtID = 0; // Default ID for the shirt
public String description = "-description required-"; // default
// The color codes are R=Red, B=Blue, G=Green, U=Unset
private char colorCode = 'U';
public double price = 0.0; // Default price all items

// This constructor takes one argument


public Shirt(char colorCode ) {
setColorCode(colorCode);
}

11 - 20 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.


Initializing a Shirt Object by Using a Constructor

public class ShirtTest {


public static void main (String[] args) {
Shirt theShirt = new Shirt('G');

theShirt.display();
}

11 - 21 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.


Multiple Constructors

public class Shirt {


... < declarations for field omitted > ... If required,
must be added
explicitly
// No-argument constructor
public Shirt() {
// You could add some default processing here
}
// This constructor takes one argument
public Shirt(char colorCode ) {
setColorCode(colorCode);
}
public Shirt(char colorCode, double price) {

this(colorCode);
setPrice(price); Chaining the
constructors
}

11 - 22 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.


Quiz

What is the default constructor for the following class?


public class Penny {
String name = "lane";
}
a. public Penny(String name)
b. public Penny()
c. class()
d. String()

11 - 23 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.


Summary

In this lesson, you should have learned how to:


• Use access modifiers
• Describe the purpose of encapsulation
• Implement encapsulation in a class
• Create a constructor

11 - 24 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.


Practice 11-1 Overview:
Implementing Encapsulation in a Class
In this practice, you create a class containing private attributes
and try to access them in another class. During this practice,
you:
• Implement encapsulation in a class
• Access encapsulated attributes of a class

11 - 25 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.


Challenge Practice 11-2 Overview:
Adding Validation to the DateThree Class
In this practice, you add a setDate()method to the
DateThree class that performs validation on the date part
values that are passed into the method.

Note: This practice (11-2) is an optional Challenge practice.

11 - 26 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.


Practice 11-3 Overview:
Creating Constructors to Initialize Objects
In this practice, you create a class and use constructors to
initialize objects.

11 - 27 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.


Practice 11-3 Overview:
Creating Constructors to Initialize Objects
In this practice, you create a class and use constructors to
initialize objects.

11 - 28 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Você também pode gostar