Java面向?qū)ο缶幊?.1.ppt_第1頁(yè)
Java面向?qū)ο缶幊?.1.ppt_第2頁(yè)
Java面向?qū)ο缶幊?.1.ppt_第3頁(yè)
Java面向?qū)ο缶幊?.1.ppt_第4頁(yè)
Java面向?qū)ο缶幊?.1.ppt_第5頁(yè)
已閱讀5頁(yè),還剩71頁(yè)未讀 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說(shuō)明:本文檔由用戶(hù)提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡(jiǎn)介

1、1,2.1.1 Defining Classes,Static Variables and Methods,2,public void methodA() . Student a1 = new Student(“a1”,18); Student a2 = new Student(“a2”,19); Student a3 = new Student(“a3”,17); . , = “a1” a1.age = 18, = “a2” a2.age = 19, = “a3” a3.age = 17,instance variable,3,instance va

2、riable Whenever an instance of that class is created, memory is allocated for the instance variable; consequently, each instance of the class will have its own copy of the instance variable.,4,public void methodA() . Student a1 = new Student(“a1”,18); Student a2 = new Student(“a2”,19); Student a3 =

3、new Student(“a3”,17); . ,a1.grade = “08” = “a1” a1.age = 18,a1.grade = “08” = “a2” a1.age = 19,a3.grade = “08” = “a3” a3.age = 17,5,class variable,public void methodA() . Student a1 = new Student(“a1”,18); Student a2 = new Student(“a2”,19); Student a3 = new Student(“a3”,17);

4、. , = “a1” a1.age = 18, = “a2” a1.age = 19, = “a3” a3.age = 17,Student.grade = “08”,6,Static Variables and Methods Only one copy of a class variable will ever exist. That copy is shared by all instances of the class. A class variable is declared using the static keyword so it is

5、 frequently called a static variable. private static String grade; A class method is a method that can access only class variables. In contrast, an instance method can access both instance and class variables. A class method is also declared using the static keyword. public static int method() ,7,8,

6、Create Object,Declare: Point p;/只是聲明引用,不在內(nèi)存中為對(duì)象分配地址空間,而是分配一個(gè)引用空間; Instantiation: 運(yùn)算符new為對(duì)象分配內(nèi)存空間,它調(diào)用對(duì)象的構(gòu)造方法,返回引用;一個(gè)類(lèi)的不同對(duì)象分別占據(jù)不同的內(nèi)存空間。 Create: 執(zhí)行構(gòu)造方法,進(jìn)行初始化;根據(jù)參數(shù)不同調(diào)用相應(yīng)的構(gòu)造方法。,9,Creating objects of a class,Point p,new Point(20,23);,=,0 x0000,0 xFF00,10,Creating objects of a class,Q,pointTwo,Before Assig

7、nment,After Assignment,Point pointOne = new Point(); Point pointTwo = new Point() ; pointOne = pointTwo;,11,Automatic garbage collection,The object does not have a reference and cannot be used in future. The object becomes a candidate for automatic garbage collection. Java automatically collects gar

8、bage periodically and releases the memory used to be used in the future.,P,12,public class Point /* Number of instances created */ private static int numberOfInstances = 0; private int x; private int y;,13,public static void main(String args) Point pointOne = new Point(10, 100); System.out.println(x

9、: + pointOne.getX(); System.out.println(y: + pointOne.getY(); pointOne.setX(20); pointOne.setY(200); System.out.println(new x: + pointOne.getX(); System.out.println(new y: + pointOne.getY(); System.out.println(Instances before PointTwo is created: + Point.getNumberOfInstances(); Point pointTwo = new

10、 Point(20, 200); System.out.println(Instances after PointTwo is created: + Point.getNumberOfInstances(); ,Point,- numberOfInstances :String - x:int - y:int,+Point(int initialX, int initialY) + getNumberOfInstances():int + getX():int + getY():int + setX(newX:int) + setX(newX:int),14,public Point(int

11、initialX, int initialY) x = initialX; y = initialY; numberOfInstances+; public static int getNumberOfInstances() return numberOfInstances; ,15,public int getX() return x; public int getY() return y; public void setX(int newX) x = newX; public void setY(int newY) y = newY; ,16,public static void main

12、(String args) Point pointOne = new Point(10, 100); System.out.println(x: + pointOne.getX(); System.out.println(y: + pointOne.getY(); pointOne.setX(20); pointOne.setY(200); System.out.println(new x: + pointOne.getX(); System.out.println(new y: + pointOne.getY(); System.out.println(Instances before Po

13、intTwo is created: + Point.getNumberOfInstances(); Point pointTwo = new Point(20, 200); System.out.println(Instances after PointTwo is created: + Point.getNumberOfInstances(); ,x=10 y=100,x=20 y=200,x=20 y=200,x=20 y=200,public Point(int initialX, int initialY) x = initialX; y = initialY; numberOfIn

14、stances+; ,17,To invoke an instance method, the method name must be preceded by an object reference: pointOne.setX(20); By convention, to invoke method, the method name should be preceded by the class name: Point.getNumberOfInstances() This makes sense because class variables are not part of any obj

15、ect so the methods that operate on them are not associated with any particular object. Class variables, if public, are also accessed using the class name. If numberOfInstances were declared as public, we would write: Point.numberOfInstances Since class variables and class methods are not associated

16、with any particular object, they can be used even when no objects of the class exist! For example, we can call getNumberOfInstances before any Point objects are created.,18,Accessor and Mutator Methods An accessor, or read accessor, is used to retrieve the value of an instance variable. By conventio

17、n, the name of an accessor is getVariableName where VariableName is the name of the instance variable. A mutator, or write accessor, is used to change, or mutate, the value of an instance variable. By convention, the name of a mutator is setVariableName. In this material, we use the prefix initial t

18、o name the parameters of constructors and the prefix new to name the parameters of mutators. This convention avoids the logical error that occurs when a programmer uses the same name for a parameter and for an instance variable, and forgets to use the keyword this.,19,2.1.2 Inheritance,Implementing

19、Specialization/Generalization Relationships A specialization/generalization relationship is implemented in Java using inheritance. Inheritance is a mechanism that creates a new class by extending or specializing an existing class.,20,The new class (the subclass or child class) inherits the variables

20、 and methods of the existing class (the superclass or parent class).,21,22,To declare a subclass, use the keyword extends followed by the name of the superclass: public class DerivedClass extends BaseClass ,23,public class Person private String name; private String address; public Person (String ini

21、tialName, String initialAddress) name = initialName; address = initialAddress; public String getName() return ; public String getAddress() return this.address; ,24,public class Employee extends Person private double salary; public Employee (String initialName, String initialAddress, double

22、initialSalary) super(initialName, initialAddress); salary = initialSalary; public double getSalary() return this.salary; public void setSalary(double newSalary) salary = newSalary; ,25,1.Uses the keyword super to call the constructor in Person. 2. The instance variables name and address are declared

23、 in Person, so the Person constructor will initialize them. 3.In Java, the super call in constructors must always be the first statement.,public Employee (String initialName, String initialAddress, double initialSalary) super(initialName, initialAddress); salary = initialSalary; ,26,An instance of c

24、lass Employee contains a copy of the variables name and address, but the Employee methods cannot access these variables. These variables are declared private in class Person, so they can only be accessed by Person methods.,27,An Employee object must use the methods getName and getAddress, both inher

25、ited from Person, to access the values of name and address.,public class Employee extends Person public void methodA() String s2 = e.getName(); ,28,Casting Objects An employee is-a person, so every Employee object is also a Person object.,29,For this reason, an Employee reference variable can be ass

26、igned to a Person reference variable. Person person = new Employee(Joe Smith, 100 Main Ave, 3000.0);,person,Person object,30,The reference person, which points to an Employee object, cannot be used to invoke the Employee methods! double salary = person.getSalary(); / illegal,person,31,the compiler w

27、ill complain because it cant find a method called getSalary in the class Personat this point in the code, the compiler only knows the person is a Person.,person,32,change the reference person into an Employee reference with a cast.,person,Employee employee = (Employee) person; double salary = employ

28、ee.getSalary(); / or,double salary = (Employee) person). getSalary();,invoke the getSalary method,33,We can cast the reference person to an Employee reference because person really points to an Employee object. If it did not and we ran the code, the cast would be illegal and the Java virtual machine

29、 (JVM) would throw a ClassCastException.,34,Person person = new Person (Joe Smith, 100 Main Ave);,person,=,double salary = (Employee) person).getSalary();/ illegal,This code will compile, but when it is executed, the JVM will throw a ClassCastException because, in this example, the reference person

30、does not point to an Employee object.,35,The instanceof Operator two operands: an object reference , a class name object instanceof ClassX true: if the specified object is an instance of the specified class if object is an instance of a ClassX subclass if object is an instance of any class that has

31、ClassX as an ancestor false:If the left-hand operand is null,36,Note: the instanceof operator cannot be used to determine the type of a primitive expression. int i=5; i instanceof int; ;/ illegal,37,The instanceof operator is often used to avoid an illegal cast: Person person = new Person (Joe Smith

32、, 100 Main Ave); if (person instanceof Employee) salary = (Employee)person).getSalary(); The cast is not made because the reference person does not point to an Employee object.,person,Name=“Joe” Address=“aa”,=,38,2.1.3 Method equals and Method toString Method equals In Java, all classes descend, dir

33、ectly or indirectly, from class Object, so all classes inherit the methods defined in class Object.,Object,39,The method equals compares two objects and returns true if and only if they are equal. The version of this method defined in class Object returns true if the objects being compared are the s

34、ame object. This default implementation is exactly the same as obj1 = obj2.,40,takes one input parameter, an Object reference. In Java, this means that a reference to an object of any type can be passed to equals. Consequently, equals can be used to compare two instances of any class.,equals(Object

35、x) person1. equals(person1),41,Object,Point,- numberOfInstances :String - x:int - y:int,+Point(int initialX, int initialY) + getNumberOfInstances():int + getX():int + getY():int + setX(newX:int) + setX(newX:int),42,Point pointOne = new Point(10, 100); Point pointTwo = new Point(10, 100); Point point

36、Three = pointOne;,43,if (pointOne.equals(pointTwo) System.out.println(pointOne and pointTwo are equal); else System.out.println(pointOne and pointTwo are different); ,44,if (pointOne.equals(pointThree) System.out.println(pointOne and pointThree are equal); else System.out.println(pointOne and pointT

37、hree are different); ,45,Method equals defined in Object, is not appropriate for most classes, so many of them override it. The version of equals in most classes returns true when the objects being compared have the same state, that is, contain the same data.,46,public boolean equals(Object object)

38、if (object instanceof Point) Point point = (Point) object; return point.getX() = getX() ,Note that this implementation applies to comparisons between Point objects and objects of its subclasses.,47,Point pointOne = new Point(10, 100); Point pointTwo = new Point(10, 100); Point pointThree = new Point

39、(50, 500);,48,if (pointOne.equals(pointTwo) System.out.println(pointOne and pointTwo are equal); else System.out.println(pointOne and pointTwo are different); ,49,if (pointOne.equals(pointThree) System.out.println(pointOne and pointThree are equal); else System.out.println(pointOne and pointThree ar

40、e different); ,50,Method toString Class Object defines a method called toString that returns the string representation of the invoking object. The version of this method defined in class Object returns a String with the following format: ClassNamenumber It is recommended that all subclasses override

41、 method toString.,51,public String toString() return ( + getX() + , + getY() + ); ,52,The following code uses the method toString defined in class Point. When method println is passed an object reference, it finds the string equivalent of the specified object by invoking the version of toString asso

42、ciated with that object.,Point pointOne = new Point(10, 100); Point pointTwo = new Point(-20, 200); Point pointThree = new Point(50, -500); System.out.println(pointOne); System.out.println(pointTwo); System.out.println(pointThree); System.out.println();,53,54,2.1.4 Unit Testing,an important aspect o

43、f software design.,verifies if a class, or a group of classes, behave as expected.,Test code can be added to the class being tested in the method main, or a new class dedicated to testing can be created.,55,BankAccount,- double balance :String,+ BankAccount() : + getBalance() : double + deposit(doub

44、le amount) : boolean +withdraw(double amount) : boolean,TestBankAccount,56,public boolean deposit(double amount) if (amount 0) balance += amount; return true; else return false; ,BankAccount,- double balance :String,+ BankAccount() : + getBalance() : double + deposit(double amount) : boolean +withdr

45、aw(double amount) : boolean,57,import java.io.*; public class TestBankAccount private static PrintWriter stdOut = new PrintWriter(System.out, true); private static PrintWriter stdErr = new PrintWriter(System.err, true); public static void main(String args) boolean result; BankAccount accountTwo = ne

46、w BankAccount(); result = accountTwo.deposit(100); assertTrue(2: testing method deposit, result); stdOut.println(done); ,TestBankAccount,BankAccount,58,public static void assertTrue( String message, boolean condition) if (! condition) stdErr.print(* Test failure ); stdErr.println(message); ,59,2.1.5 Implementing the Library System,60,Library System Classes,61,CatalogItem .java Book .java Recording .java Borrower .java,62,public class CatalogItem private String

溫馨提示

  • 1. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶(hù)所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒(méi)有圖紙預(yù)覽就沒(méi)有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶(hù)上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶(hù)上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶(hù)因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。

評(píng)論

0/150

提交評(píng)論