1. Trang chủ
  2. » Giáo án - Bài giảng

Chapter 4 Enhancing class

32 274 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Enhancing Class
Trường học University of Example
Chuyên ngành Computer Science
Thể loại Lecture Notes
Năm xuất bản 2023
Thành phố Hanoi
Định dạng
Số trang 32
Dung lượng 809,5 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

The static modifier  In Chapter 2 we discussed static methods, for example, the methods of the Math class are static: double result = Math.sqrt25;  Variables can be static as well  To

Trang 1

Enhancing class

Chapter 4

1

Trang 2

• Method parameters

• The static modifier

• Nested class and Inner classes

• Interface

• Polymorphism

Trang 3

• In particular, the method cannot modify the contents of any

parameter variables that are passed to it

parameter passing is like an assignment statement

• Primitive types (numbers, boolean values)

• Object references

3

Trang 4

Method parameters (cont.)

 A method cannot modify a parameter of primitive type

(that is, numbers or Boolean values)

• 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

Trang 5

Example: Pass primitive parameter

Trang 6

Example: Pass object reference parameter

Change state of the object

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 = " +

(10, 5)

Trang 7

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 = " +

(10, 5)

(50, 5)

Trang 8

Example: Swap objects in the method

 Chang the object that the reference points to

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() + " " +

Trang 9

• Method parameters

• The static modifier

• Nested class and Inner classes

• Interface

• Polymorphism

9

Trang 10

The static 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

Trang 11

static 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

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

private String name;

private static int nextId = 1;

}

Trang 12

static 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

 It is legal to use an object to call a static method (not

public static int getNextId() {

return nextId; // returns static field

}

To call this method, you supply the name of the class:

int n = Employee.getNextId();

Trang 13

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

Employee

0 counter 1

number=2

13

Trang 14

} }

Trang 15

Ex 2: RectangleTest.java

class RectangleTest {

public static void main( String [] agrs)

{

Rectangle n1 = new Rectangle();

Rectangle n2 = new Rectangle(8,10);

Trang 16

• Method parameters

• The static modifier

• Nested class and Inner classes

• Interface

• Polymorphism

Trang 17

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

public static class Inside_2 {

… }

}

Outside.class Outside$Inside_1.class Outside$Inside_2.class

Trang 18

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

Trang 19

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

Trang 20

• Method parameters

• The static modifier

• Nested class and Inner classes

• Interface

• Polymorphism

Trang 21

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)

 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

}

Trang 22

Interface (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

public interface Comparable {

int compareTo( Object other );

}

Trang 24

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;}

Trang 25

The Comparable interface

 The Java standard class library contains many helpful

interfaces

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

25

Trang 26

Example: EmployeeSortTest.java

import java.util.*;

public class EmployeeSortTest {

public static void main( String [] args) {

Employee[] staff = new Employee[3];

staff[0] = new Employee(" Harry Hacker ", 35000);

staff[1] = new Employee(" Carl Cracker ", 75000);

staff[2] = new Employee(" Tony Tester ", 38000);

Arrays.sort(staff); // sắp xếp theo lương

for ( Employee e : staff)

System out.println(" name = " + e.getName() + " , salary = " + e.getSalary()); }

Trang 27

Example Employee.java

class Employee

implements Comparable<Employee>

{

private String name;

private double salary;

public Employee( String n, double s)

}

{ salary = s;

if (salary < other.salary) return -1;

if (salary > other.salary) return 1;

return 0;

}

}

27

Trang 28

The Iterator interface

Trang 29

• Method parameters

• The static modifier

• Nested class and Inner classes

• Interface

• Polymorphism

29

Trang 30

Polymorphism via Interface

An interface name can be used as the type of an object

reference variable

• Example:

but: Shape x = new Shape(); //ERROR

 An interface reference variable can be used to refer to

any object of any class that implements that interface

• Example:

x = new Circle( .); // if Circle implement Comparable

x = new Rectangle( .); // if Rectangle implement

Comparable

of object that x is referring to

• That reference is polymorphism , which can be defined as

Trang 31

public interface Speaker {

public void speak();

public void announce ( String str); }

public class Philosopher implements Speaker

That line of code might execute different methods at different times if the object that obj points to changes

31

Trang 32

Self-review questions

 What is the difference between a static variable and an

instance variable?

 What is the difference between a class and an interface?

 How to declare a class that implements an interface?

Ngày đăng: 13/05/2014, 10:42

TỪ KHÓA LIÊN QUAN

w