当前位置:高等教育资讯网  >  中国高校课件下载中心  >  大学文库  >  浏览文档

上海交通大学:《操作系统 Operating System》课程教学资料(Java)Java Primer

资源类别:文库,文档格式:PDF,文档页数:20,文件大小:113.83KB,团购合买
In this appendix, we present a primer for people who are unfamiliar with the Java language. This introduction is intended to allow you to develop the Java skills necessary to understand the programs in this text. It is not a complete Java reference; for a more thorough coverage of Java, consult the Bibliographical Notes. We do not assume that you are familiar with object-oriented principles, such as classes, objects, and encapsulation, although some knowledge of these topics would be helpful. If you are already familiar with C or C++, the transition to Java will be smooth, because much Java syntax is based on C/C++.
点击下载完整版文档(PDF)

Appendix ava Primer In this appendix,we present a primer for people who are unfamiliar with the Java language.This introduction is intended to allow you to develop the Java skills necessary to understand the programs in this text.It is not a complete Java reference;for a more thorough coverage of Java,consult the Bibliographical Notes.We do not assume that you are familiar with object-oriented principles, such as classes,objects,and encapsulation,although some knowledge of these topics would be helpful.If you are already familiar with C or C++,the transition to Java will be smooth,because much Java syntax is based on C/C++. E.1 Basics In this section,we cover basics such as the structure of a basic program,control statements,methods,classes,objects,and arrays. E.1.1 A Simple Program A Java program consists of one or more classes.One class must contain the main()method.(A method is equivalent to a function in C/C++.)Program execution begins in this main method.Figure E.1 illustrates a simple program that outputs a message to the terminal.The main()method must be defined as public static void main(String args[]),where String args[]are /* The first simple program */ public class First f public static void main(String args[]){ /output a message to the screen System.out.println("Java Primer Now Brewing!"); Figure E.1 A first Java program. 1

E Appendix Java Primer In this appendix, we present a primer for people who are unfamiliar with the Java language. This introduction is intended to allow you to develop the Java skills necessary to understand the programs in this text. It is not a complete Java reference; for a more thorough coverage of Java, consult the Bibliographical Notes. We do not assume that you are familiar with object-oriented principles, such as classes, objects, and encapsulation, although some knowledge of these topics would be helpful. If you are already familiar with C or C++, the transition to Java will be smooth, because much Java syntax is based on C/C++. E.1 Basics In this section, we cover basics such as the structure of a basic program, control statements, methods, classes, objects, and arrays. E.1.1 A Simple Program A Java program consists of one or more classes. One class must contain the main() method. (A method is equivalent to a function in C/C++.) Program execution begins in this main method. Figure E.1 illustrates a simple program that outputs a message to the terminal. The main() method must be defined as public static void main(String args[]), where String args[] are /* The first simple program */ public class First { public static void main(String args[]) { // output a message to the screen System.out.println("Java Primer Now Brewing!"); } } Figure E.1 A first Java program. 1

Appendix E Java Primer optional parameters that may be passed on the command line.Output to the screen is done via the call to the method System.out.println().Note that Java supports the C++style of comments,including /This string is a comment for single-line comments and /And this string too is a comment for multiline comments. The name of the file containing the main()method must match the class name in which it appears.In this instance,the main()method is in the class First.Therefore,the name of this file must be First.java.To compile this program using the Java Development Kit (JDK)command line compiler,enter javac First.java on the command line.This will result in the generation of the file First.class.To run this program,type the following on the command line java First Note that java commands and file names are case sensitive. E.1.2 Methods A program usually consists of other methods in addition to main().Figure E.2 illustrates the use of a separate method to output the message Java Primer Now Brewing!In this instance,the String is passed to the static method printIt(), where it is printed.Note that both the main()and printIt()methods return void.Later examples throughout this chapter will use methods that return values.We will also explain the meaning of the keywords public and static in Section E.1.6. public class Second public static void printIt(String message){ System.out.printIn(message); } public static void main(String args[]){ printIt ("Java Primer Now Brewing!"); } Figure E.2 The use of methods

2 Appendix E Java Primer optional parameters that may be passed on the command line. Output to the screen is done via the call to the method System.out.println(). Note that Java supports the C++ style of comments, including // This string is a comment for single-line comments and /* And this string too is a comment */ for multiline comments. The name of the file containing the main() method must match the class name in which it appears. In this instance, the main() method is in the class First. Therefore, the name of this file must be First.java. To compile this program using the Java Development Kit (JDK) command line compiler, enter javac First.java on the command line. This will result in the generation of the file First.class. To run this program, type the following on the command line java First Note that java commands and file names are case sensitive. E.1.2 Methods A program usually consists of other methods in addition to main(). Figure E.2 illustrates the use of a separate method to output the message Java Primer Now Brewing! In this instance, the String is passed to the static method printIt(), where it is printed. Note that both the main() and printIt() methods return void. Later examples throughout this chapter will use methods that return values. We will also explain the meaning of the keywords public and static in Section E.1.6. public class Second { public static void printIt(String message) { System.out.println(message); } public static void main(String args[]) { printIt("Java Primer Now Brewing!"); } } Figure E.2 The use of methods

E.1 Basics 3 E.1.3 Operators Java uses the +-*operators for addition,subtraction,multiplication,and division,and the operator for the remainder.Java also provides the C++ autoincrement and autodecrement operators +and--.The statement ++T;is equivalent to TT 1.In addition,Java provides shortcuts for all the binary arithmetic operators.For example,the +operator allows the statement T =T 5;to be written as T +=5. The relational operators are ==for equality and !for inequality.For example,the statement 4 ==4 is true,whereas 4 !4 is false.Other relational operators include =>Java uses&as the and operator and II as the or operator. Unlike C++,Java does not allow operator overloading.However,you can use the operator to append strings.For example,the statement System.out.println("Can you hear "+"me?"); appends me?to Can you hear. E.1.4 Statements In this section,we cover the basic statements for controlling the flow of a program. E.1.4.1 The for statement The format of the for loop is as follows: for (initialization;test;increment){ /body of for loop } For example,the following for loop prints out the numbers from 1 to 25. int i; for(i=1;i<=25;i++){ System.out.println("i="+i); Note that,when the body of the for loop consists of only one line,the braces of the loop can be eliminated.Also,the index of the for loop can be declared within the for statement,rather than prior to the statement.Therefore,the previous loop could have been written as follows: for (int i=1;i <=25;i++) System.out.println("i="+i); When the index is declared in the for loop,the scope of the index is only within the for statement.The index of a for loop must be an integer(int).Java data types are discussed in Section E.1.5

E.1 Basics 3 E.1.3 Operators Java uses the +-*/ operators for addition, subtraction, multiplication, and division, and the & operator for the remainder. Java also provides the C++ autoincrement and autodecrement operators ++ and --. The statement ++T; is equivalent to T = T + 1. In addition, Java provides shortcuts for all the binary arithmetic operators. For example, the += operator allows the statement T=T + 5; to be written as T += 5. The relational operators are == for equality and != for inequality. For example, the statement 4 == 4 is true, whereas 4 != 4 is false. Other relational operators include = >. Java uses && as the and operator and || as the or operator. Unlike C++, Java does not allow operator overloading. However, you can use the + operator to append strings. For example, the statement System.out.println("Can you hear " + "me?"); appends me? to Can you hear. E.1.4 Statements In this section, we cover the basic statements for controlling the flow of a program. E.1.4.1 The for statement The format of the for loop is as follows: for (initialization; test; increment) { // body of for loop } For example, the following for loop prints out the numbers from 1 to 25. int i; for (i = 1; i <= 25; i++) { System.out.println("i = " + i); } Note that, when the body of the for loop consists of only one line, the braces of the loop can be eliminated. Also, the index of the for loop can be declared within the for statement, rather than prior to the statement. Therefore, the previous loop could have been written as follows: for (int i = 1; i <= 25; i++) System.out.println("i = " + i); When the index is declared in the for loop, the scope of the index is only within the for statement. The index of a for loop must be an integer (int). Java data types are discussed in Section E.1.5

Appendix E Java Primer E.1.4.2 The while statement The format of the while loop is as follows: while(boolean condition is true){ /body of loop The format of the do-while loop is as follows: do /body of loop while (boolean condition is true); As is the case for the for loop,if the body of either the while or the do-while loops is only one statement,the braces can be eliminated. E.1.4.3 The if statement The format of the if statement is as follows: if (boolean condition is true){ /statement(s) else if (boolean condition is true){ /other statement(s) else /even other statement(s) If there is only a single statement to be performed if the Boolean expression is true,then the braces can be eliminated. E.1.5 Data Types Java provides two different varieties of data types:primitive and reference(or nonprimitive).Primitive data types include boolean,char,byte,short, int,long,float,and double.Reference data types include objects and arrays. E.1.6 Classes and Objects Objects are at the heart of Java programming.An object consists of data and methods that access(and possibly manipulate)the data.An object also has a state,which consists of the values for the object's data at a particular time. Objects are modeled with classes.Figure E.3 is a class for a Point.The data for this class are the x and y coordinates for the point.An object-which is an instance of this class-can be created with the new statement.For example,the statement Point ptA new Point(0,15);

4 Appendix E Java Primer E.1.4.2 The while statement The format of the while loop is as follows: while (boolean condition is true) { // body of loop } The format of the do-while loop is as follows: do { // body of loop } while (boolean condition is true); As is the case for the for loop, if the body of either the while or the do-while loops is only one statement, the braces can be eliminated. E.1.4.3 The if statement The format of the if statement is as follows: if (boolean condition is true) { // statement(s) } else if (boolean condition is true) { // other statement(s) } else { // even other statement(s) } If there is only a single statement to be performed if the Boolean expression is true, then the braces can be eliminated. E.1.5 Data Types Java provides two different varieties of data types: primitive and reference (or nonprimitive). Primitive data types include boolean, char, byte, short, int, long, float, and double. Reference data types include objects and arrays. E.1.6 Classes and Objects Objects are at the heart of Java programming. An object consists of data and methods that access (and possibly manipulate) the data. An object also has a state, which consists of the values for the object’s data at a particular time. Objects are modeled with classes. Figure E.3 is a class for a Point. The data for this class are the x and y coordinates for the point. An object—which is an instance of this class—can be created with the new statement. For example, the statement Point ptA = new Point(0,15);

E.1 Basics creates an object with the name ptA of type Point.Furthermore,the state of this object is initialized to x=0 and y=15.We initilize objects using a constructor. A constructor looks like an ordinary method except that it has no return value and it must have the same name as the name of the class.The constructor is called when the object is created with the new statement.In the statement Point ptA new Point(0,15);,the values 0 and 15 are passed as parameters to the constructor,where they are assigned to the data xCoord and yCoord. With the Point class written the way it is,we could not create a point using the statement Point ptA new Point () because there is no constructor that has an empty parameter list.If we wanted to allow the creation of such an object,we have to create a matching constructor. For example,we could add the constructor shown in Figure E.4 to the class Point.Doing so allow us to create an object using the statement Point ptA new Point();.In this case,the x and y coordinates for the point are initialized to 0. Having two constructors in the Point class leads to an interesting issue.In some ways,a constructor behaves like an ordinary method.Two constructors for this class essentially means two methods with the same name.This feature of object-oriented languages is known as method overloading.A class may class Point /constructor to initialize the object public Point(int i,int j){ xCoord =i; yCoord j; /exchange the values of xCoord and yCoord public void swap(){ int temp; temp xCoord; xCoord yCoord; yCoord temp; public void printIt()f System.out.println("X coordinate ="xCoord); System.out.println("Y coordinate ="yCoord); } /class data private int xCoord;//X coordinate private int yCoord;//y coordinate Figure E.3 A point

E.1 Basics 5 creates an object with the name ptA of type Point. Furthermore, the state of this object is initialized to x = 0 and y = 15. We initilize objects using a constructor. A constructor looks like an ordinary method except that it has no return value and it must have the same name as the name of the class. The constructor is called when the object is created with the new statement. In the statement Point ptA = new Point(0,15);, the values 0 and 15 are passed as parameters to the constructor, where they are assigned to the data xCoord and yCoord. With the Point class written the way it is, we could not create a point using the statement Point ptA = new Point(); because there is no constructor that has an empty parameter list. If we wanted to allow the creation of such an object, we have to create a matching constructor. For example, we could add the constructor shown in Figure E.4 to the class Point. Doing so allow us to create an object using the statement Point ptA = new Point();. In this case, the x and y coordinates for the point are initialized to 0. Having two constructors in the Point class leads to an interesting issue. In some ways, a constructor behaves like an ordinary method. Two constructors for this class essentially means two methods with the same name. This feature of object-oriented languages is known as method overloading. A class may class Point { // constructor to initialize the object public Point(int i, int j) { xCoord = i; yCoord = j; } // exchange the values of xCoord and yCoord public void swap() { int temp; temp = xCoord; xCoord = yCoord; yCoord = temp; } public void printIt() { System.out.println("X coordinate = " + xCoord); System.out.println("Y coordinate = " + yCoord); } // class data private int xCoord; // X coordinate private int yCoord; // Y coordinate } Figure E.3 A point

6 Appendix E Java Primer public Point(){ xCoord 0; yCoord =0; } Figure E.4 Default constructor for the Point class. contain one or more methods with the same name,as long as the data types in the parameter list are different. The Point class has two other methods:swap (and printIt ()Note that these methods are not declared as static;unlike the printIt()method in Figure E.2.These methods can be invoked with the statements ptA.swap(); ptA.printIt(); The difference between static and instance(nonstatic)methods is that static methods do not require being associated with an object,and we can call them by merely invoking the name of the method.Instance methods can be invoked only by being associated with an instance of an object.That is,they can be called with only the notation object-name.method.Also,an object containing the instance methods must be instantiated with new before its instance methods can be called.In this example,we must first create ptA to call the instance methods swap()and printIt(). Also notice that we declare the methods and data belonging to the class Point using either the public or private modifiers.A public declaration allows the method or data to be accessed from outside the class.Private declaration allows the data or methods to be accessed from only within the class. Typically,we design classes by declaring class data as private.Thus,the data for the class are accessible through only those methods that are defined within the class.Declaring data as private prevents the data from being manipulated from outside the class.In Figure E.3,only the swap()and printIt()methods can access the class data.These methods are defined as public,meaning that they can be called by code outside the class.Therefore,the designer of a class can determine how the class data are accessed and manipulated by restricting access to private class data through public methods.(In Section E.3,we look at the protected modifier.) Note that there are instances where data may be declared as public and methods as private.Data constants may be declared as public if access from outside the class is desired.We declare constants using the keywords static final.For example,a class consisting of mathematical functions may publicly declare the constant pi as public static final double PI =3.14159; Also,if a method is to be used only within the class,it is appropriate to define that method as private. Objects are treated by reference in Java.When the program creates an instance of an object,that instance is assigned a reference to the object.Figure

6 Appendix E Java Primer public Point() { xCoord = 0; yCoord = 0; } Figure E.4 Default constructor for the Point class. contain one or more methods with the same name, as long as the data types in the parameter list are different. The Point class has two other methods: swap() and printIt(). Note that these methods are not declared as static; unlike the printIt() method in Figure E.2. These methods can be invoked with the statements ptA.swap(); ptA.printIt(); The difference between static and instance (nonstatic) methods is that static methods do not require being associated with an object, and we can call them by merely invoking the name of the method. Instance methods can be invoked only by being associated with an instance of an object. That is, they can be called with only the notation object-name.method. Also, an object containing the instance methods must be instantiated with new before its instance methods can be called. In this example, we must first create ptA to call the instance methods swap() and printIt(). Also notice that we declare the methods and data belonging to the class Point using either the public or private modifiers. A public declaration allows the method or data to be accessed from outside the class. Private declaration allows the data or methods to be accessed from only within the class. Typically, we design classes by declaring class data as private. Thus, the data for the class are accessible through only those methods that are defined within the class. Declaring data as private prevents the data from being manipulated from outside the class. In Figure E.3, only the swap() and printIt() methods can access the class data. These methods are defined as public, meaning that they can be called by code outside the class. Therefore, the designer of a class can determine how the class data are accessed and manipulated by restricting access to private class data through public methods. (In Section E.3, we look at the protected modifier.) Note that there are instances where data may be declared as public and methods as private. Data constants may be declared as public if access from outside the class is desired. We declare constants using the keywords static final. For example, a class consisting of mathematical functions may publicly declare the constant pi as public static final double PI = 3.14159; Also, if a method is to be used only within the class, it is appropriate to define that method as private. Objects are treated by reference in Java. When the program creates an instance of an object, that instance is assigned a reference to the object. Figure

E.1 Basics 7 public class Third public static void main(String args[]){ /create 2 points and initialize them Point ptA new Point(5,10); Point ptB new Point (-15,-25); /output their values ptA.printIt(); ptB.printIt () /now exchange values for first point ptA.swap(); ptA.printIt(); /ptc is a reference to ptB Point ptC ptB; /exchange the values for ptC ptC.swap(); /output the values ptB.printIt(); ptC.printIt () } Figure E.5 Objects as references. E.5 shows two objects of class Point:ptA and ptB.These objects are unique; each has its own state.However,the statement Point ptc ptB; assigns ptC a reference to object ptB.In essence,both ptB and ptC now refer to the same object,as shown in Figure E.6.The statement ptc.swap(); alters the value of this object,calling the swap()method,which exchanges the values of xCoord and yCoord.Calling the printIt()method for ptB and ptc illustrates the change in the state for the object,showing that now the x coordinate is-25 and the y coordinate is-15. Whenever objects are passed as parameters to methods,they are passed by reference.Thus,the local parameter is a reference to the argument being passed.If the method alters the state of the local parameter,it also changes the state of the argument that it was passed.In Figure E.7,the object ptD is passed to the method change(),where the swap()method is called.When they return from change(),the values of the x and y parameters for ptD are exchanged. The Java keyword this provides an object a reference to itself.The this reference is useful when an object needs to pass a reference of itself to another object

E.1 Basics 7 public class Third { public static void main(String args[]) { // create 2 points and initialize them Point ptA = new Point(5,10); Point ptB = new Point(-15,-25); // output their values ptA.printIt(); ptB.printIt(); // now exchange values for first point ptA.swap(); ptA.printIt(); // ptC is a reference to ptB Point ptC = ptB; // exchange the values for ptC ptC.swap(); // output the values ptB.printIt(); ptC.printIt(); } } Figure E.5 Objects as references. E.5 shows two objects of class Point: ptA and ptB. These objects are unique; each has its own state. However, the statement Point ptC = ptB; assigns ptC a reference to object ptB. In essence, both ptB and ptC now refer to the same object, as shown in Figure E.6. The statement ptC.swap(); alters the value of this object, calling the swap() method, which exchanges the values of xCoord and yCoord. Calling the printIt() method for ptB and ptC illustrates the change in the state for the object, showing that now the x coordinate is −25 and the y coordinate is −15. Whenever objects are passed as parameters to methods, they are passed by reference. Thus, the local parameter is a reference to the argument being passed. If the method alters the state of the local parameter, it also changes the state of the argument that it was passed. In Figure E.7, the object ptD is passed to the method change(), where the swap() method is called. When they return from change(), the values of the x and y parameters for ptD are exchanged. The Java keyword this provides an object a reference to itself. The this reference is useful when an object needs to pass a reference of itself to another object

Appendix E Java Primer xCoord=5 xCoord=-15 yCoord=10 yCoord=-25 ptA ptB ptC pt C is a reference to pt B. Figure E.6 ptC is a reference to ptB. E.1.7 Arrays Arrays are reference data types in Java;thus,they are created just like any other type of object.The syntax for creating an array of 10 bytes is byte[]numbers new byte[10]; Arrays can also be created and initialized in the same step.The following code fragment initializes an array to the first five prime numbers. int [primeNums {3,5,7,11,13}; Note that neither is the size of the array specified nor is the new statement used when an array is initialized. When we create an array of objects,we must first allocate the array with the new statement and we must allocate each object using new.The statement Point [pts new Point [5]; creates an array to hold five references to Point objects.The statements for (int i =0;i<5;i++){ pts[i]new Point(i,i); pts[i].printIt(); } create the five objects,assigning a reference to each object to the appropriate array element. public static void change(Point tmp){ tmp.swap(); Point ptD new Point(0,1); change(ptD); ptD.printIt(); Figure E.7 Object parameters are passed by reference

8 Appendix E Java Primer xCoord=5 yCoord=10 pt A xCoord=–15 yCoord=–25 pt B pt C pt C is a reference to pt B. Figure E.6 ptC is a reference to ptB. E.1.7 Arrays Arrays are reference data types in Java; thus, they are created just like any other type of object. The syntax for creating an array of 10 bytes is byte[] numbers = new byte[10]; Arrays can also be created and initialized in the same step. The following code fragment initializes an array to the first five prime numbers. int[] primeNums = {3,5,7,11,13}; Note that neither is the size of the array specified nor is the new statement used when an array is initialized. When we create an array of objects, we must first allocate the array with the new statement and we must allocate each object using new. The statement Point[] pts = new Point[5]; creates an array to hold five references to Point objects. The statements for (int i = 0; i < 5; i++) { pts[i] = new Point(i,i); pts[i].printIt(); } create the five objects, assigning a reference to each object to the appropriate array element. public static void change(Point tmp) { tmp.swap(); } Point ptD = new Point(0,1); change(ptD); ptD.printIt(); Figure E.7 Object parameters are passed by reference

E.2 Inheritance 9 Java performs default array initialization.Primitive numeric data types are initialized to zero,and arrays of objects are initialized to null. E.1.8 Packages Many of the core classes for Java are gathered into packages.We do not teach you how to create packages,but we do show how to use the different packages that consistute the core Java application programming interface(API). A package is simply a set of related classes.The naming convention for the core Java packages is java...The standard package for the core API is java.lang.Many of the more commonly used classes belong to this package,including String and Thread.Therefore,the fully qualified names for these classes are java.lang.String and java.lang.Thread.Classes that belong to java.lang are so common that we can refer to them by their class name,omitting the preceding package name.However,there are many other classes that belong to packages other than java.lang,and they do not follow this rule.In these instances,the fully qualified package name must be used. For example,the Vector class belongs to the package java.util(we look at vectors in Section E.2).To use a Vector,therefore,we must use the following syntax java.util.Vector items new java.util.Vector(); This requirement obviously can lead to cumbersome syntax.The less verbose solution is for the program to declare that it is using a class in a certain package by issuing the following statement at the top(before any class definitions.) import java.util.Vector; Now,we could declare the Vector using the easier style: Vector items new Vector(); However,the most common style people use when they are using packages is import java.util.*; This approach allows the program to use any class in the package java.uti1. The JavaSoft web site (http://www.javasoft.com)includes a complete listing of all packages in the core API. E.2 Inheritance Java is considered a pure object-oriented language.A feature of such languages is that they are able to extend the functionality of an existing class.In object- oriented terms,this extension is inheritance.In general,it works as follows. Assume that there exists a class that has almost all the functionality that is

E.2 Inheritance 9 Java performs default array initialization. Primitive numeric data types are initialized to zero, and arrays of objects are initialized to null. E.1.8 Packages Many of the core classes for Java are gathered into packages. We do not teach you how to create packages, but we do show how to use the different packages that consistute the core Java application programming interface (API). A package is simply a set of related classes. The naming convention for the core Java packages is java... The standard package for the core API is java.lang. Many of the more commonly used classes belong to this package, including String and Thread. Therefore, the fully qualified names for these classes are java.lang.String and java.lang.Thread. Classes that belong to java.lang are so common that we can refer to them by their class name, omitting the preceding package name. However, there are many other classes that belong to packages other than java.lang, and they do not follow this rule. In these instances, the fully qualified package name must be used. For example, the Vector class belongs to the package java.util (we look at vectors in Section E.2). To use a Vector, therefore, we must use the following syntax java.util.Vector items = new java.util.Vector(); This requirement obviously can lead to cumbersome syntax. The less verbose solution is for the program to declare that it is using a class in a certain package by issuing the following statement at the top (before any class definitions.) import java.util.Vector; Now, we could declare the Vector using the easier style: Vector items = new Vector(); However, the most common style people use when they are using packages is import java.util.*; This approach allows the program to use any class in the package java.util. The JavaSoft web site (http://www.javasoft.com) includes a complete listing of all packages in the core API. E.2 Inheritance Java is considered a pure object-oriented language. A feature of such languages is that they are able to extend the functionality of an existing class. In object￾oriented terms, this extension is inheritance. In general, it works as follows. Assume that there exists a class that has almost all the functionality that is

10 Appendix E Java Primer public class Person public Person(String n,int a,String s){ name =n; age a; ssn si } public void printperson(){ System.out.println("Name:"name); System.out.println("Age:"age); System.out.println("Social Security:"ssn); } private string name; private int age; private String ssn; Figure E.8 A person. needed for a particular application.Rather than developing from scratch a new class that contains all the necessary functionality,we can use inheritance to add to the existing class whatever is needed.For example,assume that an application must keep track of student records.A student is distinguished by her name,age,social-security number,major,and grade-point average(GPA). If another class already exists that represents people using name,age,and social-security number,we can create a student class by extending it,adding a major and GPA.The class being inherited from is the base class;the extended class is the derived class. The code for the Person class is shown in Figure E.8.The class Student is shown in Figure E.9.What is new in this class definition is the keyword extends.The Java syntax for a derived class to inherit from a base class is derived-class extends base-class Also note that the constructor in the Student class has a call to super(n,a,s). When an object of class Student is created,the constructor for the base class is not normally called.By invoking the super()method,the derived class can call the constructor in the base class. Java makes extensive use of inheritance throughout the core API.For example,many of the classes in the packages java.awt (used for creating graphical programs)and java.io (provides I/O facilities)are part of an inheritance hierarchy.In addition,one of the ways of creating a thread (described in Chapter 4)is to define a class that extends the Thread class. By default,all Java classes are derived from a common class called Object. We can exploit this feature by using the Vector class from the package

10 Appendix E Java Primer public class Person { public Person(String n, int a, String s) { name = n; age = a; ssn = s; } public void printPerson() { System.out.println("Name: " + name); System.out.println("Age: " + age); System.out.println("Social Security: " + ssn); } private String name; private int age; private String ssn; } Figure E.8 A person. needed for a particular application. Rather than developing from scratch a new class that contains all the necessary functionality, we can use inheritance to add to the existing class whatever is needed. For example, assume that an application must keep track of student records. A student is distinguished by her name, age, social-security number, major, and grade-point average (GPA). If another class already exists that represents people using name, age, and social-security number, we can create a student class by extending it, adding a major and GPA. The class being inherited from is the base class; the extended class is the derived class. The code for the Person class is shown in Figure E.8. The class Student is shown in Figure E.9. What is new in this class definition is the keyword extends. The Java syntax for a derived class to inherit from a base class is derived-class extends base-class Also note that the constructor in the Student class has a call to super(n, a, s). When an object of class Student is created, the constructor for the base class is not normally called. By invoking the super() method, the derived class can call the constructor in the base class. Java makes extensive use of inheritance throughout the core API. For example, many of the classes in the packages java.awt (used for creating graphical programs) and java.io (provides I/O facilities) are part of an inheritance hierarchy. In addition, one of the ways of creating a thread (described in Chapter 4) is to define a class that extends the Thread class. By default, all Java classes are derived from a common class called Object. We can exploit this feature by using the Vector class from the package

点击下载完整版文档(PDF)VIP每日下载上限内不扣除下载券和下载次数;
按次数下载不扣除下载券;
24小时内重复下载只扣除一次;
顺序:VIP每日次数-->可用次数-->下载券;
共20页,试读已结束,阅读完整版请下载
相关文档

关于我们|帮助中心|下载说明|相关软件|意见反馈|联系我们

Copyright © 2008-现在 cucdc.com 高等教育资讯网 版权所有