第三讲java面向对象(上)课件

上传人:沈*** 文档编号:241655124 上传时间:2024-07-13 格式:PPT 页数:94 大小:816.50KB
返回 下载 相关 举报
第三讲java面向对象(上)课件_第1页
第1页 / 共94页
第三讲java面向对象(上)课件_第2页
第2页 / 共94页
第三讲java面向对象(上)课件_第3页
第3页 / 共94页
点击查看更多>>
资源描述
第三讲java面向对象(上)回顾2-1Java具有8种基本数据类型:byte、short、int、long、boolean、char、float及doubleJava中的运算符可划分为四个子集:算术运算符、位运算符、关系运算符、逻辑运算符&运算符适用于如下子集:逻辑和位。逻辑&以条件表达式为操作数,而位&则以数字为操作数2回顾2-2Java支持下列控制结构:选择(选择(if-else、switch)循环(循环(while、do-while、for)跳转(跳转(break、continue)break语句在循环中用于立即从当前循环终止控制或者终止所标识的循环continue 语句则是从其调用处跳至循环的开始处或者跳至所标识的循环开始处数组可用来将同一类型的数据存储在连续的内存位置3字符串创建一个String类的实例:String strName1=“Humpty dumpty”;/字符串字面量字符串字面量 String strName2=new String(Egg);两个或多个字符串可以用“+”运算符合并起来。例如:strName3=strName1+is the name of an +strName2;字符串的长度可以通过String类中的函数计算。例如:int numLength=strName2.length();也可将数字添加到字符串类型中。例如:String strVar=Mark+(1+1);String strVar=Mark+1+1;4字符串我们可以使用“+”来连接字符串以达到拼接字符串的目的.但“+”会产生一个新的String实例。如果程序对这种需求很多时,对象的生成是需要内存空间和时间,不断的生成String实例便是一个没有效率的行为。方法改进:使用StringBuffer的append方法替换“+”5字符串池Java程序可包含许多字符串字面量“字符串池”:用来存放在程序中创建的所有字符串字面量任何时候创建字符串字面量,系统都会搜索字符串池,查看是否存在该字符串字面量。SundayMondayHelloAptechWorld1234NString day=Monday;String weekday=Monday;字符串池字符串池6字符串池比较字符串对象:Strings1=newString(“hello”);Strings2=newString(“hello”);Strings3=“hello”;Strings4=“hello”;s1=s2?s3=s4?7String类方法charAt():返回字符串中某个特定位置的字符indexOf():返回字符串中某个特定字符或子字符串首次出现的索引toUpperCase():将字符串内的所有字符从小写改为大写 toLowerCase():将字符串内的所有字符从大写改为小写其它更多方法参见Java编程思想,4th,第13章8Lesson3:ClassesandObjects(Part1)面向对象(上)20139面向对象特征(上)【学习目标学习目标】本讲主要讲述java语言的面向对象技术,包括面向对象的基本概念、面向对象的程序设计方法及java中的类、包、对象及其面向对象的特性。通过本讲的学习,同学们可以使用面向对象技术编写java程序。【学习指南学习指南】应深刻理解各知识点的概念,使用上一讲的编程基础知识及面向对象技术,编写简单的java类,由浅至深,养成风格良好的编程习惯。【参考书】Java编程思想,4th,第5,6,7,8章疯狂Java讲义,第5章10第三讲面向对象(上)1.基本概念2.类的定义3.对象4.类的继承和多态5.接口和包11基本概念什么是编程语言?人和计算机进行交流的工具和手段编程语言的发展机器语言:0101001汇编语言:mov,push,add,call第三代语言:高级语言,以C语言为代表,过程式编程语言(ProceduralProgrammingLanguage)第四代语言:非过程化/面向对象的编程语言语言的发展:抽象的过程12面向对象(ObjectOriented-OO)面向对象编程(ObjectOrientedProgramming-OOP)面向对象是一种软件开发的方法,“面向对象的分析与设计”(OOA&OOD研究生课程)第一个面向对象的语言:Simula-67第一个成功的面向对象编程语言:SmalltalkC+,JAVA,C#,PERL等1.用客观世界中描述事物的方法来描述程序中要解决的问题2.万事万物都是对象3.程序便是成堆的对象,彼此通过消息的传递,请求其他对象进行工作基本概念13五个基本概念1.对象2.类3.封装性4.继承性5.多态性基本概念141.对象(object)everythingisanobject现实世界的对象:桌子、书、自行车、电视、狗、文件、表格、按钮、窗口对象包含两个特性状态:指对象本身的信息(内部信息/内部变量)行为:实现对信息的访问/对象的操作对象标志:代表对象的标识符基本概念151.对象(object)状态变量(variables)行为方法(method)对象就是变量和相关方法的软件集合一个对象可以由其他对象组合而成,窗口(按钮,菜单条,文本框,状态栏等)程序就是对象的集合,对象之间相互交互和通信完成任务Aprogramisabunchofobjectstellingeachotherwhattodobysendingmessages基本概念162.类(class)现实世界中,存在很多同类的对象,很多桌子、书、自行车一种原型,一种抽象,一种共性,一个模板Everyobjecthasatype实例(instance),某类对象的一个特定实体,类是对象的一个抽象表格(类)填入不同的个人信息不同的对象基本概念173.封装性对象本身的数据得到保护/隐藏其他对象仅仅需要知道对该对象的访问方法(接口/interface)即可好处模块化-每个对象的源文件可以是相互独立的,可以被不同的程序调用,每个对象是一块积木,可以搭建不同的形状信息隐藏-通常定义一个公共接口/方法实现对对象的访问,可以调整对象的私有信息和方法,而不会对其他调用它的对象产生影响可重用性基本概念184.继承性为什么会有继承?建立一个类后,发现另一个新的类有相同的特性,两个选择:重新定义一个新的类;在已有类的基础上,修改(加加/减减)父类和子类,子类继承(拥有)父类所有的数据和方法,同时子类可以有新的数据和方法,“青出于蓝,而胜于蓝”树型结构(层次化结构)根(基类)基本概念194.继承性运输工具航空运输工具陆地运输工具水上运输工具人力驱动引擎驱动二轮四轮客运货运基本概念204.继承性多重继承类A类B类C类D类F类Gn一个类拥有多个父类产生二义性,例类C和类D都有一个同名的方法,类G?nJava中仅仅支持单一继承,同时Java采用Interface(接口)实现多重继承而避免父类二义性基本概念215.多态性表现在继承中方法的重写子类从父类继承(extends扩展)而来多个子类同属一个父类,所有子类有相同的父类继承父类的方法在不同的子类中有不同的表现形式表现在用一个类中方法的重载基本概念22一个程序中同名的不同方法共存主要通过子类对父类方法的覆盖来实现不同类的对象可以响应同名的消息(方法),具体的实现方法却不同使语言具有灵活、抽象、行为共享、代码共享的优势,很好地解决了应用程序函数同名问题基本概念5.多态性235.多态性class Shape void draw()void erase()class Circle extends Shape void draw()System.out.println(Circle.draw();void erase()System.out.println(Circle.erase();基本概念class Square extends Shape void draw()System.out.println(Square.draw();void erase()System.out.println(Square.erase()“);class Triangle extends Shape void draw()System.out.println(Triangle.draw();void erase()System.out.println(Triangle.erase();245.多态性多态性publicclassTestpublicstaticShaperandShape()switch(int)(Math.random()*3)default:case0:returnnewCircle();case1:returnnewSquare();case2:returnnewTriangle();publicstaticvoidmain(Stringargs)Shapes=newShape9;for(inti=0;is.length;i+)si=randShape();for(inti=0;ijavac A.javax has private access in A a.x=100;print()has private access in A a.print();2 errors类成员的访问class A private int x;private void print()class B void test()A a=new A();a.x=100;a.print();40protected(保护变量/保护方法)容许类本身、子类(有一定限制)以及同一个包中所有类访问(先构造对象,再访问)类成员的访问class A protected int x;protected void print()class B void test()A a=new A();a.x=100;a.print();package abc;class A protected int x;protected void print()package xyz;import abc.A;class B extends A void test(A a,B b)a.x=100;a.print();b.x=100;b.print();/illegal/illegal/legal/legal41无修饰(友好变量/友好方法)容许类本身以及同一个包中所有类访问类成员的访问class A int x;void print()class B void test()A a=new A();a.x=100;a.print();package abc;class A int x;void print()package abc;class B void test()A a=new A();a.x=100;a.print();42小结名称访问权修饰符类本身子类包所有类公共public默认-保护protected*私有private*指子类与父类不在同一个包中的情况类成员变量的访问43static(静态变量/静态方法)类的变量/方法,独立于类的对象,可以直接根据类名调用class D static int A=12,B=34;static void print()class Test public static void main(String args)System.out.println(“A=“+D.A+“B=“+D.B);S.print();类成员变量44static(静态变量/静态方法)class Test public void print(int x)System.out.println(x);public static void main(String args)int x=3;print(x);D:javac Test.javaTest.java:9:non-static method print(int)cannot be referenced from a static context print(x);1 errorclass Test public void print(int x)System.out.println(x);public static void main(String args)int x=3;Test t=new Test();t.print(x);class Test public static void print(int x)System.out.println(x);public static void main(String args)int x=3;print(x);static方法中仅仅可以调用其他static方法类成员45final变量/方法final变量:定义一个常数,即变量值不能改变finaldoubleAVOGADRO=6.022e23;final类:不能有子类final方法:方法不能被重写(overriding)class ChessAlgorithm .final void nextMove(ChessPiece pieceMoved,BoardLocation newLocation).类成员变量46小结类:public,abstract,final,无修饰,private类成员publicprotectedprivate无修饰staticfinal类成员变量47方法:对象行为的描述完成某种功能的程序块定义:访问权限修饰符方法返回类型方法名()throws异常名方法体;方法参数的传递变量的作用域方法的重载(overloading)/重写(overriding)方法的递归调用类成员方法48访问控制修饰符公共访问控制符public被所有类访问默认访问控制符被同一包中其他类访问私有访问控制符private被该类自身访问保护访问控制符protected该类自身、同一个包中的其他类、其他包中的子类访问私有保护访问控制符privateprotected该类自身、所有子类访问类成员方法的访问49非访问控制修符静态方法static属于类的方法最终方法final不能被子类重新定义的方法抽象方法abstract只有方法说明,没有具体实现本地方法native以其他语言实现方法功能同步方法synchronized用于多线程程序中的协调和同步类成员方法的访问50例成员方法class Test public static void main(String args)double d_product;Area myArea;myArea=new Area();d_product=myArea.product();System.out.println(“myArea的面积是:”+d_product);class Area double width,height;void setV(double w,double h)width=w;height=h;double product()return width*height;51方法参数成员方法public static void main(String args)int x=3,y=4;Test p=new Test();System.out.println(x+y);p.addI(x,y);System.out.println(x+y);Vector c=new Vector();c.addElement(s1);c.addElement(s2);System.out.println(c.size();p.addV(c);System.out.println(c.size();import java.util.Vector;class Test private void addV(Vector v)v.addElement(s3);private void addI(int i1,int i2)i1+;i2+;形参和实参D:java Parameter3 43 423注意1:类型匹配注意2:基本类型与复合类型参数传递的结果不同52Java中的引用在Java中“引用”是指向一个对象在内存中的位置,在本质上是一种带有很强的完整性和安全性的限制的指针.指针可以有+,-运算,引用不可以运算.Pass by ValueIn Java methods,arguments are passed by value.When invoked,the method receives the value of the variable passed in.When the argument is of primitive type,pass-by-value means that the method cannot change its value.When the argument is of reference type,pass-by-value means that the method cannot change the object reference,but can invoke the objects methods and modify the accessible variables within the object.53基本类型的值传递3.143.14AB0 x2F0 x2FAB引用类型的地址传递54基本类型作为参数class Test int a,b;change(int i,int j)a=i;b=j;/调用:int m=0;int n=1;change(m,n);a=10a=10b=20b=20m m0 01 1n na=10a=10b=20b=20 i i0 01 1j j a ab b拷贝拷贝55引用类型作为参数class Test int a,b;Test(int i,int j)a=i;b=j;/可以在函数中改变对象状态 void change(Test obj)obj.a=50;obj.b=40;/调用:Test t=new Test(10,20);change(t);函数中只能改变函数中只能改变该对象的状态,该对象的状态,但不能改变该对但不能改变该对象的引用象的引用改变对象改变对象状态状态a=10a=10b=20b=201100111001t t1100111001objobja=50a=50b=40b=4056Day obj1=new Day(2002,5,30);Day obj1=new Day(2002,5,30);Day obj2=new Day(2003,7,23);Day obj2=new Day(2003,7,23);void swapobj(void swapobj(Day x,Day yDay x,Day y)Day temp=y;Day temp=y;y=x;y=x;x=temp;x=temp;调用:调用:swapobj(obj1,obj2);swapobj(obj1,obj2);引用本身引用本身按值传递按值传递Day2002,5,30Day2003,7,23obj11010obj21020 xy调用调用swapobj(obj1,obj2)swapobj(obj1,obj2)x1010y102057例:值传递与地址传递publicclassPassTestfloatm_float;voidchange1(intpi)pi=100;voidchange2(Stringps)ps=newString(“Right”);voidchange3(PassTestpo)po.m_float=100.0f;58publicstaticvoidmain(Stringargs)PassTestpt=newPassTest();inti=22;pt.change1(i);System.out.println(“ivalueis”+i);59Strings=newString(“Hello”);pt.change2(s);System.out.println(“svalueis”+s);pt.m_float=22.0F;pt.change3(pt);System.out.println(“Currentpt.m_floatis”+pt.m_float);/main()/class60程序运行结果ivalueis22svalueisHelloCurrentpt.m_floatis100.061方法的重载(overload)方法名相同,但方法的参数不同方法描述方法名(标识符)参数类型方法返回值绝对值abs(a)intint绝对值abs(a)longlong绝对值abs(a)floatfloatpublicstaticintabs(inta)publicstaticlongabs(longa)publicstaticfloatabs(floata)成员方法62方法重载方法重载也是Java实现多态性机制的一种方式。同一个类中多个方法有相同的名字,不同的参数列表,这种情况称为方法重载。63方法重载示例class Calculation public void add(int a,int b)int c=a+b;System.out.println(两个整数相加得两个整数相加得 +c);public void add(float a,float b)float c=a+b;System.out.println(两个浮点数相加得两个浮点数相加得+c);public void add(String a,String b)String c=a+b;System.out.println(两个字符串相加得两个字符串相加得 +c);class CalculationDemo public static void main(String args)Calculation c=new Calculation();c.add(10,20);c.add(40.0F,35.65F);c.add(早上早上,好好);编译器决定编译器决定调用版本调用版本64方法重载重载方法调用时,编译器根据参数的类型和数量来确定实际调用哪个重载方法返回类型不同并不足以构成方法重载(相同参数但是不同返回类型编译不通过)。class OverLoadDemo int i;void geti()i=1;int geti()return i;Duplicate method geti()in type OverLoadDemo65构造方法创建对象/实例化对象new例1:Applea=newApple();(创建对象)例2:Applea;(对象的说明)a=newApple();(实例化对象)1.对象的实例化通过构造方法(constructor)来实现2.构造方法的名字与类名相同3.构造方法没有返回值4.构造方法可以有多个,构成方法的重载(overload)66例:对象的实例化和初始化class jex6_8 public static void main(String args)Qangle q1=new Qangle();Qangle q2=new Qangle(20,50);Qangle q3=new Qangle(q1);System.out.println(q1.width()+“”+q1.height();System.out.println(q2.width()+“”+q2.height();System.out.println(q3.width()+“”+q3.height();class Qangle int a,h;Qangle()a=10;h=20;Qangle(int x,int y)a=x;h=y;Qangle(Qangle r)a=r.width();h=r.height();int width()return a;int height()return h;输出结果:10 201120 501210 20构造方法67再谈方法的重载(overload)构造方法class Tree int height;Tree()prt(“Planting a seeding”);height=0;Tree(int i)prt(“Creating new Tree that is”+i+“feet tall”);height=i;void info()prt(“Tree is”+height+“feet height”);void info(String s)prt(s+“:Tree is”+height+“feet height”);static void prt(String s)System.out.println(s);for(int i=0;i 5;i+)Tree t=new Tree(i);t.info();t.info(“my tree”);new Tree();68默认构造方法例classAppleintcolor;Applea=newApple();对象实例的判断:null例Applea;if(a=null)System.out.println(“Daydream”);构造方法运行时系统自动赋予一个空构造函数如 Apple()69再谈构造方法构造方法 class Cmethod Cmethod(boolean b)public static void main(String args)Cmethod c1=new Cmethod();Cmethod c2=new Cmethod(false);class Cmethod Cmethod(boolean b)public static void main(String args)/Cmethod c1=new Cmethod();Cmethod c2=new Cmethod(false);class Cmethod Cmethod(boolean b)Cmethod()public static void main(String args)Cmethod c1=new Cmethod();Cmethod c2=new Cmethod(false);运行时系统自动赋予一个空构造方法,仅仅当该类没定义构造方法的情况下70static变量的初始化class Smember static int i=100;static boolean b=true;char c=t;public Smember()public static void main(String args)Smember m1=new Smember();Smember m2=new Smember();不论产生多少个对象,属于类的静态变量只有一份,即只占有一份存储空间class Smember static int i;static boolean b;static i=100;b=true;System.out.println(“In static block”);char c=t;public Smember()System.out.println(“In constructor”);public static void main(String args)Smember m1=new Smember();Smember m2=new Smember();输出结果In static blockIn constructorIn constructor71方法的重写(overriding)子类重写父类的方法成员方法class Father void display();class Son extends Father void display();Father f=new Father();f.display();Son s=new Son();s.display();class Father void display();class Son extends Father int display();Thereturntypeisincompatiblewithfather.getit()class Father private void display();72抽象类(abstractclass)一个未完成的类仅仅抽象类可以包含抽象方法(abstractmethods)抽象方法:仅仅申明了方法,但未实现有访问修饰词返回值类型方法名参数列表无方法体73抽象类(abstractclass)abstract class Point int x=1,y=1;void move(int dx,int dy)x+=dx;y+=dy;alert();abstract void alert();abstract class ColoredPoint extends Point int color;class SimplePoint extends Point void alert()抽象方法:有访问修饰词、返回值类型、方法名和参数列表,无方法体74抽象类(abstractclass)抽象类不能被实例化,例Pointp=newPoint();子类继承抽象类时,必须重写抽象方法,否则仍为抽象类abstract class Point int x=1,y=1;void move(int dx,int dy)x+=dx;y+=dy;alert();abstract void alert();abstract class ColoredPoint extends Point int color;class SimplePoint extends Point void alert()Point p=new SimplePoint();75第三讲面向对象(上)1.基本概念2.类的定义3.对象4.类的继承和多态5.接口和包76对象引用对象的变量格式:对象名.变量名引用对象的方法格式:对象名.方法名例1Vectorv=newVector();v.addElement(“helloworld”);例2inta=1,2,3,4,5;intsize=a.length;例3System.out.println();77对象通过对象引用对象的成员变量和成员方法class Qangle int a,h;Qangle()a=10;h=20;Qangle(int x,int y)a=x;h=y;Qangle(Qangle r)a=r.width();h=r.height();void set(int x,int y)a=x;h=y;q1.set(30,40);q1.a=30;q1.h=40;目的相同第一方式更安全、更面向对象(数据封装)直接操纵变量78对象的释放将对象从内存中清除内存的管理(枯燥、容易出错)垃圾回收(GarbageCollection)垃圾搜集器(GarbageCollector)周期性地释放不再被引用的对象,自动完成手动完成,System.gc();publicstaticvoidgc()-Runsthegarbagecollector.The Java platform allows you to create as many objects as you want(limited,of course,by what your system can handle),and you dont have to worry about destroying them.The Java runtime environment deletes objects when it determines that they are no longer being used.This process is called garbage collection.79对象的使用访问对象的私有(private)成员通过定义一个公共方法来实现class Student private String name;private String id;Student(String s1,String s2)name=s1;id=s2;String getName()return name;void setName(String s)name=s;Student st=new Student(“aloha”,“001”);String n=st.getName();st.setName(“csma”);n=st.getName();80对象的使用对象作为方法的参数访问权限修饰符方法返回类型方法名(参数)throws异常名方法体;参数:类型变量名,类型:基本数据类型/复合类型(对象)参数的传递Passbyvalue81对象的使用对象的访问对象作为方法的返回值访问权限修饰符方法返回类型方法名(参数)throws异常名方法体;返回类型有返回值:基本数据类型/复合类型(对象)无返回值:void82对象的使用对象作为方法的返回值例:求两点坐标之间的中点坐标思路:(x1,y1)和(x2,y2)(x,y)x=(x1+x2)/2,y=(y1+y2)/2Spots1=newSpot(2,3);Spots2=newSpot(4,5);Spots=s1.midSpot(s2);83对象的使用数组:类型相同的一列元素简单的数组public class ArrayDemo public static void main(String args)int anArray =new int10;for(int i=0;i anArray.length;i+)anArrayi=i;System.out.print(anArrayi+);System.out.println();84对象的使用对象数组class Test public static void main(String args)int a=new int5;for(int i=0;i a.length;i+)System.out.println(ai);String s=new String5;for(int i=0;i s.length;i+)System.out.println(si);System.out.println(si.length();85对象的使用对象数组class Student private String name;private String id;Student(String s1,String s2)name=s1;id=s2;String getName()return name;void setName(String s)name=s;void display()System.out.println(name+“”+id);Student st=new Student10;for(int i=0;i st.length;i+)sti=new Student();for(int i=0;i st.length;i+)sti.display();86对象的使用对象作为另一个对象的成员变量class MobilePhone private String type;private Watch w;MobilePhone(String s)type=s;void setWatch(Watch a)w=a;long getTime()return w.getTime();class Watch long getTime()return System.currentTimeMillis();MobilePhone mp=new MobilePhone(“nokia”);Watch w=new Watch();mp.setWatch(w);long l=mp.getTime();public static long currentTimeMillis()the difference,measured in milliseconds,between the current time and midnight,January 1,1970 UTC87对象的使用关键词thisthis指当前对象应用1:加强程序可读性(this可有可无)88对象的使用例1:Demo1.java(调用变量)class Demo1 double x,y;Demo1(double i,double j)this.x=i;this.y=j;double ave()return(x+y)/2;public static void main(String args)Demo1 d=new Demo1(3,4);System.out.println(d.ave();89对象的使用例2:Demo2.java(调用方法)class Demo2 int x,y,z;Demo2(int a,int b)x=a;y=b;this.sort(a,b);void sort(int a,int b)int t;if(x y)t=x;x=y;y=t 90对象的使用例3:Demo3.java(调用方法)class Demo3 int x,y;Demo3(int a,int b)x=a;y=b;void change(int i,int j)x=i;y=j;this.sort();void sort()int t;if(x y)t=x;x=y;y=t 91对象的使用关键词thisthis指当前对象应用2:对同一个对象执行多次方法调用class Leaf int i=0;Leaf increment()i+;return this;void print()System.out.println(“i=”+i);Leaf x=new Leaf();x.increment().increment().increment().print();92对象的使用关键词thisthis指当前对象应用3:在一个构造函数中调用另一个构造函数class Flower String name;int price;Flower()this(tulip,10);Flower(String s,int i)name=s;price=i;void print()System.out.println(name +price);public static void main(String args)Flower f=new Flower();f.print();93谢谢!谢谢!
展开阅读全文
相关资源
正为您匹配相似的精品文档
相关搜索

最新文档


当前位置:首页 > 管理文书 > 施工组织


copyright@ 2023-2025  zhuangpeitu.com 装配图网版权所有   联系电话:18123376007

备案号:ICP2024067431-1 川公网安备51140202000466号


本站为文档C2C交易模式,即用户上传的文档直接被用户下载,本站只是中间服务平台,本站所有文档下载所得的收益归上传人(含作者)所有。装配图网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对上载内容本身不做任何修改或编辑。若文档所含内容侵犯了您的版权或隐私,请立即通知装配图网,我们立即给予删除!