Tải bản đầy đủ (.ppt) (32 trang)

Chapter 4 Enhancing class

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (733.17 KB, 32 trang )

Enhancing class
Enhancing class
Chapter 4
Chapter 4
1
Out lin e
• Method parameters
• The static modifier
• Nested class and Inner classes
• Interface
• Polymorphism
2
Method parameters
Method parameters

The Java programming language always uses call by
value

This means that the method gets a copy of all parameter
values

In particular, the method cannot modify the contents of any
parameter variables that are passed to it

parameter passing is like an assignment statement

There are two kinds of method parameters:

Primitive types (numbers, boolean values)

Object references


3
Method parameters
Method parameters
(cont.)
(cont.)

A method cannot modify a parameter of primitive type
(that is, numbers or Boolean values)

A method can change the state of an object parameter

The method gets a copy of the object reference, and both
the original and the copy refer to the same object (aliases)

A method cannot make an object parameter refer to a
new object

See examples next…
4
Example: Pass primitive parameter
Example: Pass primitive parameter
class MyClass{
public static void setNum( int n )
{
n = 5;
System.out.println(“Trong hàm setNum, num= ” + n);
}
public static void main(String[] agrs)
{
int num = 10;

System.out.println(“Truoc khi goi ham setNum, num= ” + num);
setNum(num); // n=num
System.out.println(“Sau khi goi ham setNum, num= ” + num);
}
}
n
=
1
0
5
Example: Pass object reference parameter
Example: Pass object reference parameter

Change state of the object
6
public class RectangularTest {
static void modifyRec( Rectangular r ) {
r.setWidth(50);
}
public static void main( String[] args ) {
Rectangular rect = new Rectangular(10, 5);
double area = rect.getArea();
System.out.println("rect after created has area is "+ area);
modifyRec( rect ); // r = rect
System.out.print("After calling modifyRect, new width = " +
rect.getWidth());
area = rect.getArea();
System.out.println(", new area is "+ area);
}
}

rect
r
(10, 5)(50, 5)
Example: Pass object reference parameter
Example: Pass object reference parameter

Chang the object that the reference points to
7
public class RectangularTest {
static void modifyRec( Rectangular r ) {
r = new Rectangular(50, 5);
}
public static void main( String[] args ) {
Rectangular rect = new Rectangular(10, 5);
double area = rect.getArea();
System.out.println("rect after created has area is "+ area);
modifyRec( rect ); // r = rect
System.out.print("After calling modifyRect, new width = " +
rect.getWidth());
area = rect.getArea();
System.out.println(", new area is "+ area);
}
}
rect
r
(10, 5)
(50, 5)
Example: Swap objects in the method
Example: Swap objects in the method


Chang the object that the reference points to
8
public class RectangularTest {
static void swap( Rectangular x, Rectangular y ) {
Rectangular temp = x;
x = y;
y = temp;
}
public static void main( String[] args ) {
Rectangular a = new Rectangular( 5, 5 );
Rectangular b = new Rectangular( 10, 10 );
System.out.println("Before: a has width, height =" + a.getWidth() + " " +
a.getHeight());
System.out.println("Before: b has width, height =" + b.getWidth() + " " +
b.getHeight());
swap( a, b );
System.out.println("After: a has width, height =" + a.getWidth() + " " +
a.getHeight());
System.out.println("After: b has width, height =" + b.getWidth() + " " +
b.getHeight());
}
}
The x and y parameters of the swap method are
initialized with copies of these references. The
method then proceeds to swap these copies
Out lin e
• Method parameters
• The static modifier
• Nested class and Inner classes
• Interface

• Polymorphism
9
The
The
static
static
modifier
modifier

In Chapter 2 we discussed static methods, for example,
the methods of the Math class are static:
double result = Math.sqrt(25);

Variables can be static as well

To declare static methods and static variables, using the
static keyword
public static double getID()
private static int k;

Static methods and static variables are invoked
through its class name

Static methods and static variables often work
together
10
static
static
fields
fields


Each object has its own copy of all instance fields, but if
you define a field as static, then there is only one
such field per class

Example: class Employee

Every employee object now has its own id and name field, but
there is only one nextId field

Static fields are shared among all instances of a class

Changing the value of a static variable in one object changes it for all
others

Static fields are called class fields
11
class Employee {
. . .
private int id;
private String name;
private static int nextId = 1;
}
12
static
static
methods
methods

Static methods are methods that do not operate on

objects

You cannot access instance fields from a static method

Static methods can access the static fields in their class

Example: class Employee

It is legal to use an object to call a static method (not
recommended)
public static int getNextId() {
return nextId; // returns static field
}
To call this method, you supply the name of the class:
int n = Employee.getNextId();
Ex 1: StaticDemo.java
Ex 1: StaticDemo.java
class Employee
{
private String name, address;
private int SSN, number;
private static int counter;
public Employee(String name, String address, int
SSN)
{
System.out.println(“Constructing an Employee”);
this.name = name;
this.address = address;
this.SSN = SSN;
this.number = ++counter;

}
public static int getCounter()
{
return counter;
}
public int getNumber()
{
return number;
}
}
public class StaticDemo
{
public static void main(String [] args)
{
Employee e1 = new Employee("John",
"Hollywood Blvd.", 123456789);
Employee e2 = new Employee("Wayn",
"WallStreet Blvd.", 987654321);
System.out.println("Using e1, counter= " +
Employee.getCounter());
System.out.println("Using e2, counter= " +
Employee.getCounter());
System.out.println("Using e1, number= " +
e1.getNumber());
System.out.println("Using e2, number= " +
e2.getNumber());
}
}
Employee
0

counter
12
e1
name=“John”
address=“Hollywood Blvd.”
SSN=123456789
number=1
e2
name=“Wayn”
address=“WallStreet Blvd.”
SSN=987654321
number=2
13
Ex 2: Rectangle.java
Ex 2: Rectangle.java
class Rectangle {
private double width, height;
public Rectangle() {
this(0,0);
}
public Rectangle(double x, double y) {
width = x;
height = y;
}
public double getArea() {
return width*height;
}
public double getPerimeter() {
return (width+height)*2;
}

//…get/set methods
public static void printHeader() {
System.out.println("Width \t "+
"Height + \t Perimeter \t Area ");
}

public void printInfo() {
System.out.println( getWidth() + "\t" +
getHeight() + "\t" + getArea()+ "\t" +
getPerimeter());
}
}
Ex 2: RectangleTest.java
Ex 2: RectangleTest.java
class RectangleTest {
public static void main(String[] agrs)
{
Rectangle n1 = new Rectangle();
Rectangle n2 = new Rectangle(8,10);
Rectangle.printHeader();
n1.printInfo();
n2.printInfo();
}
}
15
Out lin e
• Method parameters
• The static modifier
• Nested class and Inner classes
• Interface

• Polymorphism
16
Nested Class
Nested Class

In addition to containing data and methods, a class
can also contain other classes

Classes within another class is called a nested classes

A nested class produces a separate bytecode file
17
class Outside {

public class Inside_1 {

}
public static class Inside_2 {

}
}
Outside.class
Outside$Inside_1.class
Outside$Inside_2.class
Inner Class
Inner Class

Nested classes are divided into two categories:

Static nested class


Non-static nested class: is called an inner class

Inner class methods can access the data from the scope in
which they are defined, even if they are declared private

Inner classes can be hidden from other classes in the same
package

See more in Core Java 1, chapter 6
18
Example
Example
class Outer {
int outer_x = 100;
void test() {
Inner inner = new Inner();
inner.display_x();
}
class Inner { // có thể truy xuất trực tiếp đến biến của lớp Outer
int inner_y = 10;
void display_x() {
System.out.println(“display : outer_x = “ + outer_x);
}
}
void display_y() { // không thể truy xuất biến của lớp Inner
System.out.println(“display : inner_y = “ + inner_y); // Error
}
}
class InnerClassDemo {

public static void main(String args[]) {
Outer outer = new Outer();
outer.test();
}
}
19
Out lin e
• Method parameters
• The static modifier
• Nested class and Inner classes
• Interface
• Polymorphism
20
Interface
Interface

An Interface is a collection of constants and
abstract methods

An abstract method is a method header without a method
body (it is followed by a semicolon)

Syntax


An Interface is not a class, so it cannot be instantiated

By default, methods in an interface have public visibility
21
public interface InterfaceName {

SomeType method1(…); // No body
SomeType method2(…); // No body
}
Interface
Interface
(cont.)
(cont.)

Why we use interface? Let's look at a concrete example:

The sort method of the Arrays class promises to sort an
array of objects, but under one condition: The objects must
belong to classes that implement the Comparable interface

Comparable interface looks like:

This means that any class that implements the Comparable
interface is required to have a compareTo method

How to declare a class that implements an interface?
22
public interface Comparable {
int compareTo( Object other );
}
Implement Interface
Implement Interface

To declare that a class implements interfaces, use the
implements keyword


A class can implement multiple interfaces (separated by
commas)

The class must implement all methods in all interfaces listed in
the header

A class that implements an interface can implement other
methods as well
23
public class ClassName implements Interface1, Interface2
{
// all methods of all interfaces
}
Example
Example

Shape interface
public interface Shape {
double getArea();
}

Circle class
public class Circle implements Shape {
private double radius; …
public double getArea() {
return Math.PI * radius * radius;}
}

Rectangle class
public class Rectangle implements Shape {

private double width, length; …
public double getArea() {
return width * length;}
}
24
The
The
Comparable
Comparable
interface
interface

The Java standard class library contains many helpful
interfaces

The Comparable interface contains one abstract
method called compareTo, which is used to compare
two objects

The String class implements Comparable, giving us the
ability to put strings in lexicographic order

To use the sort method of the Arrays class to sort an array
of objects, the objects must belong to classes that
implement the Comparable interface
public interface Comparable
{
int compareTo(Object other);
}
The value returned from compareTo

should be negative if obj1 is less
that obj2, 0 if they are equal, and
positive if obj1 is greater than
obj2
25

Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay
×