《ch3_Classes and Objects_类和对象ppt课件.pptx》由会员分享,可在线阅读,更多相关《ch3_Classes and Objects_类和对象ppt课件.pptx(75页珍藏版)》请在taowenge.com淘文阁网|工程机械CAD图纸|机械工程制图|CAD装配图下载|SolidWorks_CaTia_CAD_UG_PROE_设计图分享下载上搜索。
1、ch3_Classes and Objects_类和对象Chapter 3 Classes and Objects类与对象3. 1 Concepts of OOP Java supports object-oriented programming (面向对象程序设计) This chapter studies the anatomy of a class, and how to declare fields, methods, and constructors. 3.1.1 Everything is an object 万物万物皆对象皆对象 Object-oriented program s
2、ee all things objects. An object can be a computer, a person, or an intangible thing, like a bank account. An object is anything that is a single material item. A program is a bunch of objects telling each other what to do by sending messages. The world is composed of objects. An object has state, b
3、ehavior and identity. This means that an object can have internal data (which gives it state), methods (to produce behavior), and each object can be uniquely distinguished from each other, each object occupies a unique memory space in the main memory. 面向对象的思想将一切事物都看成对象。对象可以是计算机、人或者银行账号这样无形的事物。对象可以是任
4、何实体。程序包含若干对象,对象之间通过接口相互传递消息。大千世界由对象组成。 对象有状态状态(内部数据)、行为行为(方法,产生行为),当然还有名字名字。对象彼此区别,每个对象都在内存里有唯一的存储空间。Abstraction(抽象) Abstraction is an important property of all object oriented programming language. The same types of entity have the same properties. So we can extract those same features from real-en
5、tities. This approach is called abstraction. The concept of abstraction is todescribe a set of similar concrete entities, e.g. as a whole, a car isa single object, in detail, the car consists of several subsystems: steering, brakes, sound system, heating and so on. In turn, each of these subsystems
6、is made up of more specialized units. 抽象抽象是面向对象程序设计语言的一个重要特性。同类对象有相似的特性,将相似的特性(状态)和行为(方法)抽取出来,将相似的特性(状态)和行为(方法)抽取出来,叫做叫做抽象抽象。抽象就是对同类实体特征的描述抽象就是对同类实体特征的描述。例如,一辆轿车是一个对象,轿车包含多个子系统:变速、刹车、音响、空调等,而每个子系统又由更为具体的单元组成。3.1.2 Defining classes 定义类 In chapters one and two, weve already seen some classes and used
7、new operator to create objects. Virtually all object-oriented programming languages use the “class” keyword. class ClassName /fields /constructors /methods This is a class definition. The class body contains declarations for the fields that provide the state of the class, and methods to implement th
8、e behavior of the class. Fields represent member variables in a class. Constructors are methods too, for initializing new objects created from the class. Once a class is established, you can make as many objects of that class as you like. 3.2 Useful classes常用类 Java class library contains many classe
9、s. Here introduce several of them for use. 1. Data type corresponded classes 与基本数据类型一一对应的类 Each primitive data type corresponds to a class, e.g. byte Byte int Integer char Character public class TypeMaxValue public static void main(String a) byte maxByte=Byte.MAX_VALUE; short maxShort=Short.MAX_VALU
10、E; int maxInt=Integer.MAX_VALUE; System.out.println(The maximum byte value: +maxByte); System.out.println(The maximum short value: +maxShort); Date class is available in java.util package, this class encapsulates the current date and time. The Date class supports two constructors. Date( ) This const
11、ructor initializes the object with the current date and time.Date(long millisec) This constructor accepts an argument that equals the number of milliseconds that have elapsed since midnight, January 1, 1970. Java的java.util包里有个Date类,该类封装了当前日期和时间。Date类有2个构造方法:Date(),用当前时间和日期初始化对象用当前时间和日期初始化对象,Date(lon
12、g millisec),含一个参数,其值代表从1970年1月1日起流逝的毫秒数。2. Date classimport ; /or import java.util.*; public class ClassDate public static void main(String a) Date date = new Date(); System.out.println(date.toString(); /System.out.println(date); Output:Tue Jul 10 15:14:37 CST 2018 (CST 美国中央时区) The current time and
13、date are converted to a String type string by toString() method. When the actual parameter of the println or print method is an object, the toString() can be omitted, that is System.out.println(date.toString();can be: System.out.println(date); Test test=new Test(); System.out.println(test.toString()
14、; can be: System.out.println(test); Except for the Date object, in common,println or print method prints address of the object if its actual parameter is an object. The address consists of class name+hash address of the object. toString()方法将当前日期和时间转换成String类型的字符串。当println 或print方法的实参是对象时,可以省略.toStri
15、ng(),即 System.out.println(date.toString(); can be: System.out.println(date); 除了Date对象,通常,如果println或print方法的实参是对象,他们输出对象的地址。对象的地址由“类名对象的哈希地址”组成。 Display current time and date using toString().import java.util.Date;public class ClassDate public static void main(String a) System.out.println(new Date();
16、 Output:Tue Jul 10 15:14:37 CST 20183. String classUseful methods:1) public char charAt(int arg0)2) public String split(String arg0)3) public char toCharArray()class TryString public static void main(String args) String str=new String(hello!); char ch=str.charAt(0); /h System.out.println(ch); char s
17、c=str.toCharArray(); for(char s:sc) System.out.print(s); /hello! System.out.println(); String string=str.split(l); for(String s:string) System.out.print(s+ ); /he o! System.out.println(); System.out.println(string.length); /3 hhello!he o! 3String concatenate Operator “+” concatenates strings or stri
18、ngs and any objects or primitive variables or any types of constants. The adding results are String objects.class STR public static void main(String args) String str=hello!; str=str+ +12+ +67.2; str=str+ +true; Ty ty=new Ty(); str=str+ +ty; /str=str+ty.toString System.out.println(str); class Tyhello
19、! 12 67.2 true Ty1fa1bb64. Keyboard input: Scanner classScanner 可以接收 int,double, boolean, String, byte 等键盘输入。 import ; /import java.util.*;public class Test public static void main(String args) Scanner input=new Scanner(System.in); System.out.println(请输入星期几请输入星期几); int today=input.nextInt(); switch(
20、today) case 1: case 3: (专业课专业课); break; case 2: case 4: (公共课公共课); break; (不上课不上课); (必须是必须是1-7); Scanner class provides several methods to accept keyboard inputs of all primitive types except for char type. The char input can be realized by method next(), which accept a string from the keyboard. impo
21、rt java.util.Scanner;public class ScannerTest public static void main(String args) Scanner input=new Scanner(System.in); System.out.println(请输入星期几); char today=input.next().charAt(0); /next() for String switch(today) case 1: case 3: case 5: System.out.println(去工作); break; case 2: case 4: case 6: Sys
22、tem.out.println(去上课); break; case7: System.out.println(休息); Scanner的next()方法从键盘接收一个字符串。 Here is an example to accept arbitrary number of integers from the keyboard and output them in reverse order. 从键盘接受任意个整数,按反序输出。 import java.util.Scanner;public class ScanNumber public static void main(String args
23、) int total; Scanner input=new Scanner(System.in);(Enter the total number youll input:); total=input.nextInt(); int ary=new inttotal;(please input +total+ integers:); for(int i=0;i=0;i-)System.out.print(aryi+,); Example of accept any number of numbers从键盘接收任意个数3.3 Method Overloading 方法重载 Polymorphism
24、 is another property of OOP, which is accomplished by method overloading. Methods within the same class having the same name but differing in arguments are termed overloaded methods. Overloading means more than one method have the same name, when the method calling, which one is called is identified
25、 during the compile time, not run time according to their different arguments. This is the static polymorphism. 多态多态,是OOP程序设计的另一个特点,通过方法重载实现。一个类里的多个方法可以取相同的名字一个类里的多个方法可以取相同的名字,但方法的参数不同,叫做方法重载方法重载。 重载意味着多个方法具有同一个名字。调用方法时,根据方法参数的不同确定调用哪一个。在编译时编译时,而不是在运行时,就确定了哪个方法被调用,是静态多态静态多态。 The overloaded methods s
26、hare one name, but differ in arguments means the argument lists could differ via: Number of parameters Data type of parameters Sequence of parameters 重载的方法用同一个名字同一个名字,但它们的参数不同。参数不同指、的是:参数个数参数类型参数次序Differ in arguments void add(int a, int b)void add(int a, float b)void sub(int a, float b)void sub(int
27、a, int b, float c)void mult(int a, float b)int mult(int a, float b) 不能仅通过方法的返回类型不同实现重载!不能仅通过方法的返回类型不同实现重载!Overloaded methodsNot overloading. Compile error.class OverLoading /static polymorphism void plan() System.out.println(no arguments); void plan(int x) System.out.println(The value of x is +x);pu
28、blic class OverLoad public static void main(String args) OverLoading ov= new OverLoading(); ov.plan(); ov.plan(5); E.g. OverLoading.javaWhich method is called is decided at the compile time.3.4 Constructors 构造方法 Constructors play important roles in objects initialization. A constructor is a method.
29、Without constructors, an object cant be initialized properly. A constructor shares the same name as its class. It does not return a value, not even void. It may or may not have arguments. with method overloading, several constructors may be defined in a class. If a class has constructors, Java autom
30、atically calls one of the constructors when an object is created. 构造方法用于对象的初始化。构造方法首先是方法,没有它,就无法恰当地初始化对象。构造方法名与类名相同构造方法名与类名相同,没有返回值,没有返回值,即使即使void也不能用也不能用。它既可以是有参方法,也可以是无参方法。方法重载,允许在一个类里定义多个构造方法允许在一个类里定义多个构造方法。 如果类里有构造方法,创建一个对象时系统会自动调用其中创建一个对象时系统会自动调用其中的一个构造方法。的一个构造方法。 For example: public class Stud
31、ent Student() Student(String Param) For example:class Account private int act_no; private double balance; private String name; public void display() (Account:+act_no);(Name:+name); System.out.println(“Balance:+balance); public void deposit(double amount) public void withdraw(double amount) public st
32、atic void main( String args ) Account person1=new Account(); person1.display(); Account person2=new Account(); person2.display(); Object person1 and person2 both hold defaults. Different objects hold same values. Using constructors, a newly created object can hold individual values. Java automatical
33、ly calls a constructor when an object is created. 对象person1 和 person2的数据都具有缺省值,不同的对象却有相同的值。使用构造方法,新建对象新建对象的的fields可以可以有自己特定的初始值有自己特定的初始值。如果类里有构造方法,创建对象时,Java会自动调用其中的一个会自动调用其中的一个。;public class Account private int act_no; private double balance; private String name; public void display() System.out.pr
34、intln(Account:+act_no); System.out.println(Name:+name); System.out.println(Balance:+balance); Account(int acc, String nm, double b) act_no=acc; name=nm; balance=b; public static void main(String args) int act; String name; double b; Scanner in=new Scanner(System.in); System.out.print(Account:); act=
35、in.nextInt(); System.out.print(Name:); name=in.next(); System.out.print(Balance:); b=in.nextDouble(); Account person=new Account(act, name, b); person.display(); Output:Account:12Name:宋和平Balance:120.5Example of each new instance with its own initial valuesExample:class Tree int height; public Tree()
36、 / constructor method System.out.println(Planting a seed); height = 0; public Tree(int i) /overloading constructor System.out.println(Creating new Tree + i + feet tall); height = i; For example: class Rock public Rock(int k) System.out.println(Create rock +k); public class Constructor public static
37、void main(String args) for(int i=0;i5; i+) new Rock(i); For example:class DataOnly int i; float f; boolean b; public DataOnly( int x, float y, boolean z ) i=x; f=y; b=z; public static void main(String args) DataOnly d=new DataOnly(1, 2, true); (i= +d.i); System.out.println(f= +d.f); (b= +d.b); 3.5 D
38、efault Constructor A constructor that takes no arguments is called the default constructor. But like any methods, the constructors can also take arguments. 无无参构造方法叫缺省构造方法参构造方法叫缺省构造方法。与其它方法一样,构造方法也可以有参数。 For example:class Rock int k=100; public Rock() (Creating Rock k=+k);public class Constructor pub
39、lic static void main(String args) for(int i=0;i st2- 各有各的空间。 a (0)b (12)a (0)b (12)i (47)class StaticTest static void method() static int i = 47; static void funct() StaticTest st1 = new StaticTest(); StaticTest st2 = new StaticTest(); st1.i=12; /or st2.i=38; or StaticTest.i+; or i+; method(); /st1.
40、method(); or StaticTest.method(); / There are 3 ways to refer to a static variable. class Inctable /与StaticTest不同的类不同的类 void ment() StaticTest.i+; StaticTest.method(); method(); /? increment(); static void increment() There are three ways to refer to a static members of a class: 1. A reference that
41、refers to an object.2. Directly by name of the static fields or methods.This is not true, if static fields and methods in a class are called in other classes.3. The class name, where the static fields or methods are. 有3种访问静态成员的方式:1. 对象对象2. 静态成员的名字 当当静态成员在另一个类中被访问时,这条不成立静态成员在另一个类中被访问时,这条不成立,只限于,只限于在定
42、义在定义静态成员的类内静态成员的类内访问。访问。3. 静态成员所在类的类名Ways to refer to a static member of a class访问静态成员的方式 class X private static int s ; public static void main(String k) Y a=new Y(); Y b=new Y(); Y c=new Y(); Y d=new Y(); System.out.println(s value is :+s); System.out.println(x value is :+a.x); class Y static int
43、x=12; /非非privateExample:b.xc.xd.xY.xpublic class Test3 private String s; private Test3 t; private Byte b; private static int stc; String gets() return s; Test3 gett() return t; Byte getb() return b; public static void main(String yy) Test3 v=new Test3(); System.out.println(Default of String :+v.gets
44、(); /v.s System.out.println(Default of Test3 :+v.gett(); /v.t System.out.println(Default of Byte :+v.getb(); /v.b System.out.println(Default of Byte :+stc); Except for void, must return something!v.stcTest3.stcCant be bclass DataOnly private int i; private float f; private boolean b; public static v
45、oid main(String args) DataOnly d=new DataOnly(); System.out.println(i= +d.i); System.out.println(f= +d.f); System.out.println(b= +d.b); Exampleclass DataOnly public static void main(String s) int x; float y; boolean z; System.out.println(x= +x); /? System.out.println(y= +y); /? System.out.println(z=
46、 +z); /? Instance variableslocal variablesVariables in a method are local, without default values.class DataOnly private int i; private float f; private boolean b; public static void main(String args) DataOnly d=new DataOnly(); System.out.println(i= +d.i); System.out.println(f= +d.f); System.out.pri
47、ntln(b= +d.b); Exampleclass DataOnly private int i; private float f; private boolean b; void fun(); static void kk() public static void main(String s) (i= +i); /? System.out.println(f= +f); /? System.out.println(b= +b); /? DataOnly d=new DataOnly(); d.outp(); /outp();? d.kk(); /kk();? void outp() /n
48、on static (i= +i); /? System.out.println(f= +f); /? System.out.println(b= +b); /? fun(); kk(); /? Instance variables非非静态方法:静态方法:直接访问所有成员直接访问所有成员(静态、非静态、fields、方法)静态静态方法方法: 直接访问静态成员直接访问静态成员,通过实例访问通过实例访问非静态成员非静态成员class DataOnly private int i; private float f; private boolean b; public static void main
49、(String args) DataOnly d=new DataOnly(); System.out.println(i= +d.i); System.out.println(f= +d.f); System.out.println(b= +d.b); Exampleclass DataOnly private int i; private float f; private boolean b; void fun(); static void kk() public static void main(String s) System.out.println(“i= “+i); /X(“f=
50、+f); /X(“b= +b); /X DataOnly d=new DataOnly(); d.outp(); /outp();X通过对象才行 d.kk(); /kk(); void outp() System.out.println(“i= +i); / (“f= +f); / (“b= +b); / fun(); kk(); / Instance variables非非静态方法:静态方法:直接访问所有成员直接访问所有成员(静态、非静态、fields、方法)静态静态方法方法: 直接访问静态成员直接访问静态成员,通过实例访问通过实例访问非静态成员非静态成员public class Test3