java教程3 java面向对象编程.ppt_第1页
java教程3 java面向对象编程.ppt_第2页
java教程3 java面向对象编程.ppt_第3页
java教程3 java面向对象编程.ppt_第4页
java教程3 java面向对象编程.ppt_第5页
已阅读5页,还剩90页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

第3章,Java面向对象编程,SunnyLiuweiliu_china,本课教学内容,定义类创建对象成员数据和方法给方法传参数构造函数访问说明符,本课教学内容,修饰符重载包继承的概念在Java中实现继承,本课教学内容,接口方法覆盖多态性使用super,问题陈述,顾客介绍过程中的Customer类有如下的属性和行为:创建一个顾客类Customer。该类存储顾客的个人信息:顾客ID号、顾客名、电话、邮编。为顾客类编写一个方法,该方法能显示顾客的个人信息。,定义类,语法,class/bodyofclass,其中,class是创建类所使用的关键字,是类的名称,包含属性和方法,定义类,类的命名规则:不能为Java中的关键字。不能包含空格或点号“.”。可以以下划线“_”、字母或“$”符号开头。,classBox/成员数据/方法,创建对象,创建一个对象分两步进行:声明对象的引用变量或名称。创建对象的一个实例。语法,创建对象,例子Boxmybox;在使用对象之前必须给它们分配内存。由new操作符来完成。mybox=newBox();,mybox,成员数据,定义一个成员数据的语法为:例子,publicclassBoxprivatedoublelength;privatedoublewidth;privatedoubledepth;,方法,语法:(参数列表)/语句例子,publicdoublevolume()returnwidth*height*depth;,返回类型,方法名,参数列表,访问说明符,方法首部声明,方法体,使用成员数据和方法,使用成员数据成员数据能用在不同的类中,通过创建类的对象然后用点”.”引用对象的成员数据。调用方法调用方法,必须是方法名后跟括弧和分号。如果两方法在同一个类里面,可以直接使用该方法的名字进行调用。类的一个方法能调用相同类里的另一个方法。如果两方法不在同一个类中,一个方法通过创建类的对象然后用”.”操作符指向那方法,从而调用不同类里的方法。,示例:使用成员数据和方法,classBoxdoublewidth;doubleheight;doubledepth;doublevolume()returnwidth*height*depth;,publicclassBoxDemopublicstaticvoidmain(Stringargs)Boxmybox=newBox();doublevol;/给盒子的实例变量赋值mybox.width=10;mybox.height=20;mybox.depth=15;/返回盒子的体积vol=mybox.volume();System.out.println(Volumeis+vol);,实例分析,任务单,实例分析,步骤1:说明类,publicclassCustomer,实例分析,步骤2:定义类的变量,publicclassCustomerpublicStringCustomerId;publicStringCustomerName;publicStringCustomerPhone;publicStringCustomerPostcode;,实例分析,步骤3:说明类中的方法,publicclassCustomerpublicStringCustomerId;publicStringCustomerName;publicStringCustomerPhone;publicStringCustomerPostcode;publicvoiddisplayDetails()/写入显示顾客的信息的代码,实例分析,步骤4:初始化变量,publicclassCustomerpublicStringCustomerId;publicStringCustomerName;publicStringCustomerPhone;publicStringCustomerPostcode;publicCustomer()CustomerId=ALFKI;CustomerName=MariaAnders;CustomerPhone=(171)555-2222;CustomerPostcode=12209;publicvoiddisplayDetails()/写入显示顾客的信息的代码,实例分析,步骤5:编写代码显示测试值,publicclassCustomerpublicStringCustomerId;publicStringCustomerName;publicStringCustomerPhone;publicStringCustomerPostcode;publicCustomer()CustomerId=ALFKI;CustomerName=MariaAnders;CustomerPhone=(171)555-2222;CustomerPostcode=12209;,publicvoiddisplayDetails()System.out.println(“IdofanCustomeris+CustomerId);System.out.println(“NameofanCustomeris+CustomerName);System.out.println(“PhoneofanCustomeris+CustomerPhone);System.out.println(“PostcodeofanCustomeris+CustomerPostcode);,实例分析,步骤6:编写main()方法步骤7:调用方法步骤8:编译运行程序,publicclassCustomerpublicStringCustomerId;publicStringCustomerName;publicStringCustomerPhone;publicStringCustomerPostcode;publicCustomer()CustomerId=ALFKI;CustomerName=MariaAnders;CustomerPhone=(171)555-2222;CustomerPostcode=12209;,publicvoiddisplayDetails()System.out.println(“IdofanCustomeris+CustomerId);System.out.println(“NameofanCustomeris+CustomerName);System.out.println(“PhoneofanCustomeris+CustomerPhone);System.out.println(“PostcodeofanCustomeris+CustomerPostcode);publicstaticvoidmain(Stringargs)CustomercustomerObject=newCustomer();customerObject.displayDetails();,稍等一下,编写CustomerCollection类,该类保存并显示三个顾客的信息。以下是提供给你的Customer类的代码模板。,classCustomerpublicStringCustomerId;publicStringCustomerName;publicStringCustomerPhone;publicStringCustomerPostcode;publicvoiddisplayDetails()/显示顾客的信息的代码System.out.println(CustomerId);System.out.println(CustomerName);System.out.println(CustomerPhone);System.out.println(CustomerPostcode);,给方法传参数,传值调用引用调用,传值调用,calling()intpercent=10;System.out.println(“Before:percent=”+percent);called(percent);System.out.println(“After:percent=”+percentt);,called(intx)x=3*x;System.out.println(“Endofmethod:x=”+x);,10,30,percent=,x=,引用调用,calling()Personharry=newPerson();called(harry);,called(Personx)x.raiseSalary(200);,harry=,x=,Person,构造函数,声明构造函数的语法规则默认构造函数,构造函数的语法规则,一个新对象初始化的最终步骤是去调用对象的构造函数。构造函数必须满足以下条件:方法名必须与类名称完全相匹配;不要声明返回类型;不能被static、final、synchronized、abstract、native修饰。,默认构造函数,默认构造方法是没有参数的构造函数,你可以显式定义类的默认构造函数。当一个类没有包含构造函数时,Java将自动提供一个默认构造函数。该构造函数没有参数,用public修饰,而且方法体为空。格式如下:publicclassname()只要类中显式定义了一个或多个构造函数,而且所有显式定义的构造函数都带参数,那么将失去默认构造函数。,示例:构造函数,/第一个构造函数,无参数,默认给出长宽高Box()width=20;height=30;depth=15;/第二个构造函数,给出长宽高的参数Box(doublew,doubleh,doubled)width=w;height=h;depth=d;/第三个构造函数,给出另一个Box作参数Box(Boxr)width=r.getWidth();height=r.getHeight();depth=r.getDepth();,Boxboxes=newBox3;boxes0=newBox();boxes1=newBox(12,20,10);boxes2=newBox(boxes0);,访问说明符,信息隐藏是OOP最重要的功能之一,也是使用访问说明符的原因信息隐藏的原因包括:对任何实现细节所作的更改不会影响使用该类的代码防止用户意外删除数据此类易于使用,访问修饰符,public访问说明符,所有的类除了内部类(在其它类里的类)都能有public访问说明符。你能从任何Java程序中的任何对象里使用共有类、成员变量和方法。例子:,publicclassPublicClasspublicintpublicVariable;publicvoidpublicMethod().,publicclassApplicantpublicStringapplicantID;publicStringapplicantName;publicStringapplicantAddress;publicStringapplicantPosition;publicvoiddisplayDetails()System.out.println(“IamaApplicant”);,示例:public访问说明符,publicclassotherClasspublicstaticvoidmain(Stringargs)Applicantapplicant;applicant=newApplicant();applicant.displayDetails();,protected访问说明符,在类中声明为protected的变量、方法和内部类能被其子类所访问。你定义了一个protected成员,那么这个成员可以在以下情况下被访问:类本身相同包中的其它类子类(可以在相同包中或不同包中),packageHR;publicclassApplicantprotectedStringapplicantID;protectedStringapplicantName;protectedStringapplicantAddress;protectedStringapplicantPosition;protectedvoiddisplayDetails()System.out.println(“IamaApplicant”);,示例:protected访问说明符,packageOther;importHR.*;publicclasstestDifferentPackagepublicstaticvoidmain(Stringargs)Applicantapplicant;applicant=newApplicant();applicant.displayDetails();,private访问说明符,只有相同类的对象才能访问私有变量或方法。只能规定变量、方法和内部类是私有的。例子,privateclassApplicant/somecodeshere,Whywrong?,classApplicantprivateStringapplicantID;privateStringapplicantName;privateStringapplicantAddress;privateStringapplicantPosition;privatevoiddisplayDetails()System.out.println(“IamaApplicant”);,示例:private访问说明符,publicclasstestPrivateClasspublicstaticvoidmain(Stringargs)Applicantapplicant;applicant=newApplicant();applicant.displayDetails();,package访问说明符,如果我们没有规定访问说明符,那就是friendly(友元)或(package)的。friendly不是关键字。拥有友元访问符的类、变量或方法对包里所有的类来说都是可以访问的。,示例:package访问说明符,方法accessMe()已在类X中声明。下列表格告诉你从类Y和Z中访问方法accessMe()的可能性。,访问说明符,修饰符,staticfinalabstractnativetransientsynchronizedvolatile,static修饰符,类(static)变量类(static)方法静态初始化程序,static(静态域),用static修饰的域是仅属于类的静态域。静态域是类中每个对象共享的域。它们是类的域,不属于任何一个类的具体对象。静态域是一个公共的存储单元,任何一个类的对象访问它时,取到的都是相同的数值。,publicclassCountprivateintserialNumber;privatestaticintcounter;publicCount()counter+;serialNumber=counter;System.out.println(MyserialNumberis+serialNumber);.,static(静态域),publicstaticvoidmain(Stringargs)System.out.println(Atfirst,counter=+counter);Countcount1=newCount();System.out.println(aftercreatcount1,counter=+counter);Countcount2=newCount();System.out.println(Atlastcounter=+counter);System.out.println(count1.serialNumber“+count1.serialNumber);System.out.println(count2.serialNumber“+count2.serialNumber);System.out.println(count1.counter+count1.counter);System.out.println(count2.counter+count2.counter);System.out.println(Count.counter+Count.counter);,static(静态域),Count.counter/合法Count.serialNumber/非法,静态方法,成员方法分为类方法和实例方法。用static修饰的方法叫类方法,或静态方法。静态方法也和静态变量一样,不需创建类的实例,可以直接通过类名被访问。static方法不能被修饰成protected和abstract。,静态方法,publicclassWrongintx;voidmethod()x+;publicstaticvoidtest()x=1;/非法method();/非法publicstaticvoidmain(Stringargs)x=9;/非法method();/非法,堆区,Wrong对象实例变量x,Wrong对象实例变量x,Wrong.test()?,静态方法中不允许直接访问实例变量和实例方法。,静态方法,publicclassCorrectintx;voidmethod()x+;/合法publicstaticvoidmain(Stringargs)Correctr1=newCorrect();r1.x=9;/合法r1.method();/合法Correctr2=newCorrect();r2.x=10;/合法r2.method();/合法System.out.println(r1.x);System.out.println(r2.x);,堆区,Correct对象实例变量x,Correct对象实例变量x,引用变量r1,引用变量r2,静态初始化程序,类中可以包含静态代码块,它不存在于任何方法体中。当类被装载时,静态代码块只被执行一次。类中不同的静态块按它们在类中出现的顺序被依次执行。,publicclassSamplestaticinti=5;staticSystem.out.println(FirstStaticcodei=+i+);staticSystem.out.println(SecondStaticcodei=+i+);publicstaticvoidmain(Stringargs)Samples1=newSample();Samples2=newSample();System.out.println(Atlast,i=+i);,打印FirstStaticcodei=5SecondStaticcodei=6Atlast,i=7,final修饰符,最终域用final修饰的域,实际上就是Java中的常量。最终方法用final修饰的方法是最终方法。最终方法是不能被当前类的子类重新定义的方法。最终类如果一个类被final修饰符所修饰和限定,说明这个类不可能有子类。,abstract修饰符,由abstract修饰的方法叫抽象方法;由abstract修饰的类叫抽象类。抽象方法必须声明在抽象类中。抽象方法语法:abstractreturntypemethod_name(parameter_list);声明抽象类语法:abstractclass限制:抽象类不能被实例化。子类必须重载超类的抽象方法。抽象类必须有子类。,this关键字,this关键字引用当前实例在static方法中不能使用this关键字,publicclassThisTestintx;ThisTest(intx)this.x=x;method(this);voidmethod(ThisTestt)t.x+;/合法publicstaticvoidtest()this.x+;/非法,ThisTestt1=newThisTest(1);ThisTestt2=newThisTest(2);ThisTest.out.println(t1.x);ThisTest.out.println(t2.x);,堆区,ThisTest对象实例变量x,ThisTest对象实例变量x,引用变量t1,引用变量t2,重载,方法重载构造函数重载,方法重载(overload),对于类的方法(包括从父类中继承的方法),如果有两个方法的方法名相同,但参数不一致,那么可以说,一个方法是另一个方法的重载方法。重载方法必须满足以下条件:方法名相同;方法的参数类型、个数、顺序至少有一项不相同;方法的返回类型可以不同;方法的修饰符可以不同。,示例,/java.lang.Math类的用于取最大值的max方法,/有多个重载方法。publicstaticintmax(inta,intb)publicstaticlongmax(longa,longb)publicstaticfloatmax(floata,floatb)publicstaticdoublemax(doublea,doubleb),inta=Math.max(1,2);doubled=Math.max(1,2.0);,构造方法重载,Java支持对构造方法的重载,这样一个类就可以有很多个构造方法。,classBoxdoublewidth;doubleheight;doubledepth;Box()width=20;height=30;depth=15;,Box(doublew,doubleh,doubled)width=w;height=h;depth=d;BoxCons(BoxConsr)width=r.getWidth();height=r.getHeight();depth=r.getDepth();Box(doublelen)width=height=depth=len;,包,包允许将类组合成较小的单元(类似文件夹),使其易于查找和使用相应的类文件。有助于避免命名冲突。在使用许多类时,类和方法的名称很难决定。有时需要使用与其它类相同的名称。包基本上隐藏了类并避免了名称上的冲突。包允许在更广的范围内保护类、数据和方法,可以在包内定义类,而包外的代码不能访问该类。,“包将类名空间划分为更加容易管理的块,包既是命名机制也是可见度控制机制”,创建包,packagemypackage;publicclassCalculatepublicdoublevolume(doubleheight,doublewidth,doubledepth),语法:package包名;,导入包,importmypackage.Calculate;publicclassPackageDemopublicstaticvoidmain(Stringargs)Calculatecalc=newCalculate();,语法:importpackage_name.*;importpackage_name.class_name;,问题陈述,你的项目组已为Motel168旅馆的HR系统定义了类。在检查类结构之前,项目经理已经将其否定并要求你重做。Customer和VIPCustomer类的结构如下:,继承的概念,继承是一种在已有类的基础上创建新类的机制。已有类称为超类(superclass)、基类(baseclass)或父类(parentclass)新类称为子类(subclasschildclass)或派生类(derivedclass)。方法:创建一个共有属性的父类,再创建具有特殊属性的子类。,继承的类型,单继承,继承的类型,Child类,Mother类,Father类,多继承,继承的优点,代码的可重用性减少代码冗余父类的属性和方法可用于子类易于修改和维护,继承:类的层次,父类,子类,Chrysler类,Ford类,Trains类,Vehicles类,Planes类,Automobiles类,GM类,Chevrolet类,Malibu类,在Java中实现继承,extends关键字用于从超类派生类,换句话说,扩展超类的功能。一个类只允许有一个直接的父亲。(单继承机制)C+允许多继承Java通过接口方式来间接实现多继承语法,类的修饰符classextends/代码,编写一个父类使用extends关键字,编写子类,示例:在JAVA中实现继承,classApplicantStringapplicantName=HarryPot;StringapplicantPosition=Manger;Applicant()voiddisplayDetails()System.out.println(从父类Application中输出的信息);System.out.println(申请人姓名+applicantName);System.out.println(申请职位+applicantPosition);System.out.println(=);,publicclassCandidateextendsApplicantStringinterviewDate=12-July-2007;booleancandidateStatus=false;Candidate()voiddisplay()System.out.println(从子类Application中输出的信息);System.out.println(面试日期+applicantName);System.out.println(候选人状态+applicantPosition);System.out.println(候选人姓名+applicantName);System.out.println(候选职位+applicantPosition);,publicclassCandidateTestpublicstaticvoidmain(Stringargs)Candidatecandidate=newCandidate();candidate.displayDetails();candidate.display();,抽象类,抽象类定义了其子类的共同属性和行为。它用作基类派生相同种类的特定类。它定义了派生类的通用属性。抽象类不能被实例化,即不允许创建抽象类本身的实例。例子,abstractclassBaseabstractvoidmethod1();abstractvoidmethod2();classSubextendsBase/编译出错,Sub类必须声明为抽象类voidmethod1()System.out.println(method1);,示例:抽象类,抽象方法不具有任何实现代码,final关键字,final类:不能被继承final方法:不能被子类覆盖final变量:必须被显式的初始化,并且只能初始化一次,publicfinalclassApublicclassBextendsA/非法,publicclassApublicfinalintmethod()return1;publicclassBextendsApublicintmethod()/非法return2;,稍等一下,以下代码段在编译阶段产生错误:下列代码段在编译时产生错误:,abstractfinalclassCustomer/Customer类的代码,finalclassCustomer/Customer类的代码classVIPCustomerextendsCustomer/VIPCustomer类的代码,稍等一下,下列代码段在编译时产生错误:试确定错误产生的原因,并纠正错误。,abstractclassCustomerpublicstaticvoidmain(Stringargs)/创建类的对象Customerc=newCustomer();,接口,接口就是某个事物对外提供的一些功能的声明。可以利用接口实现多态,同时接口也弥补了Java单一继承的弱点。使用interface关键字定义接口。一般使用接口声明方法或常量,接口中的方法只能是声明,不能是具体的实现。,publicinterfaceInterfaceName/接口体,定义接口,语法:例子,publicinterfaceColorfinalintwhite=0;finalintblack=1;finalintred=2;.publicvoidchangeColor(intnewColor);/该方法没有方法体,实现接口的步骤,导入接口。使用implements关键字后跟接口的名字来说明类。保证类能实现在接口中定义的每种方法。用.java扩展名保存文件。编译applet或创建的应用程序。,示例:接口,publicinterfaceMyInterfacepublicvoidcalculatePerimeter(doubleheight,doublewidth);publicvoidcalculateVolume(doubleheight,doublewidth,doubledepth);,publicclassInterfaceDemoimplementsMyInterfacepublicvoidcalculatePerimeter(doubleheight,doublewidth)System.out.println(“theperimeteris”+2*(height+width);publicvoidcalculateVolume(doubleheight,doublewidth,doubledepth)System.out.println(“thevolumnis”+(height*width*depth);publicstaticvoidmain(Stringargs)MyInterfaced=newMyInterfaceDemo();d.calculatePerimeter(10.20);d.calculateVolume(9,10,11);,接口规则,类能实现许多接口。所有接口的方法是抽象的。所有接口的变量是public,static和final。在说明方法和变量时,不需要指定上述关键字。不需要在接口里说明private或protected方法或变量,因为方法必须在其它类里重载。接口的方法不能是final,因为final方法不能被任何类修改。,方法覆盖,例如:Rectangle(矩形)和Circle(圆)都是Shape(图)的子类。Shape类有calculateArea()方法。而计算图的面积的方法是不同的。因此calculateArea()方法以不同方式在类Rectangle和Circle里实现。,示例:方法覆盖,WheelChair(轮椅)类派生自Chair类。两个类都有方adjustHeight()。然而轮椅类的调整方法不同于其它椅子的调整方法。因此,轮椅类覆盖超类的adjustHeight()方法。,classChairpublicvoidadjustHeight()System.out.println(“Adjustchairheight”);,publicclassWheelChairextendsChairpublicstaticvoidmain(Stringargs)WheelChairwChair;wChair=newWheelChair();wChair.adjustHeight();Whatistheprogramoutput?,publicclassWheelChairextendsChairpublicvoidadjustHeight()System.out.println(“Adjustwheelchairheight”);publicstaticvoidmain(Stringargs)WheelChairwChair;wChair=newWheelChair();wChair.adjustHeight();Whatistheprogramoutput?,覆盖方法的规则,参数的顺序和重载方法的名字与超类的方法相同。被覆盖的和覆盖方法的返回类型必须相同。覆盖的方法不能比被覆盖的方法具有更少的访问权限。例如,如果在超类里说明为public的方法,不能在子类里用private关键字覆盖。覆盖的方法不能比超类方法有更多的异常。异常是在执行时间发生的错误。,多态性,多态性是指“多种形式”。它使用不同的实例而执行不同操作。多态性的实现有两种方式:覆盖实现多态性重载实现多态性,使用super,调用超类的构造方法。用来访问被子类的成员隐藏的超类成员。,子类调用父类构造方法,调用父类构造方法的语法为:super()或super(参数列表);super()方法始终指向调用类的父类,要调用父类构造方法,使用关键字super,在构造子类对象时,JVM会先调用父类的构造方法。子类构造方法中通过super语句调用父类构造方法。super必须是子类构造器的第一条语句。如果子类构造方法中没有通过super语句调用父类构造方法,那么JVM会调用父类的默认构造方法,如果不存在默认构造方法,将导致编译错误。,子类调用父类构造方法,调用父类构造方法,classApplicantStringapplicantName;Applicant(Stringstr)applicantName=str;System.out.println(从Application类里输出:);System.out.println(姓名为+applicantName);,publicclassCandidateextendsApplicantStringapplicantPosition;Candidate(Stringname,Stringposition)super(name);applicantPosition=position;System.out.println(从Candidate类里输出:);System.out.println(姓名为+applicantName+,+申请职位为+applicantPosition);/candidatesothercodes,Applicant(Stringstr)applicantName=str;System.out.println(“从Application类里输出”);System.out.println(“姓名为”+applicantName);,访问超类成员,classApplicantStringapplicantName=HarryPot;StringapplicantPosition=Manger;Applicant()/voiddisplayDetails()System.out.println(申请人姓名:+applicantName);System.out.println(申请职位:+applicantPosition);,publicclassCandidateextendsApplicantStringinterviewDate=12-July-2007;booleancandidateStatus=false;voiddisplayDetails()/调用超类的displayDetails()方法super.displayDetails();/显示候选人的信息System.out.println(面试时间:+interviewDate);System.out.println(候选人状态:+candidateStatus);/candidatesothercodes,实例分析,任务单,实例分析,步骤1:确定两个实体之间的关系VIPCustomer是Customer的一种。步骤2:确定继承的次序超类:Customer子类:VIPCustome

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论