《面向对象特征》PPT课件.ppt
1,第6讲 面向对象特征(2),武汉大学国际软件学院,2,接口是对abstract类的进一步扩展接口中的方法都是未实现的(类似于抽象方法),目的是在实现接口的类之间建立一种协议接口中的变量都是常量定义一个类符合某个或一组接口,利用implements,6.1 接口(interface),An interface is a named collection of method definitions(without implementations).An interface can also declare constants.,public interface 接口名 成员变量;方法声明;,class 类名 implements 接口1,接口2,3,接口名修饰public:无任何访问限制无修饰:仅限于本包中接口变量默认都是“public static final”public interface Months int JANUARY=1,FEBRUARY=2,MARCH=3,APRIL=4,MAY=5,JUNE=6,JULY=7,AUGUST=8,SEPTEMBER=9,OCTOBER=10,NOVEMBER=11,DECEMBER=12;,6.1.1 接口名修饰,4,6.1.2 接口方法,接口方法无修饰但在实现接口方法的类中,修饰符为public,interface Figure double half=0.5,pi=3.14159;void parameter();void area();,class Triangle implements Figure double b,h;Triangle(double u,double v)b=u;h=v;public void parameter()System.out.println(b+“+h);public void area()System.out.println(half*h*b);,class Circle implements Figure double x,y,r;Circle(double u,double v,double m)x=u;y=v;r=m;public void parameter()System.out.println(x+“+y+“+r);public void area()System.out.println(pi*r*r);,Triangle t=new Triangle(2,3);Circle c=new Circle(4,5,6);Figure f=t,c;for(int i=0;i f.length;i+)fi.parameter();fi.area();,5,6.1.3 接口的继承 extends,接口的继承 extends将多个接口合并为一个新的接口,interface DC int add(int x,int y);interface DB extends DC int sub(int x,int y);interface DA extends DB int mul(int x,int y);,interface DY int div(int x,int y);interface DX extends DY int mod(int x,int y);,class DD implements DA,DX public int add(int x,int y)return x+y;public int sub(int x,int y)return x-y;public int mul(int x,int y)return x*y;public int div(int x,int y)return x/y;public int mod(int x,int y)return x%y;,6,6.1.4 接口多重继承,利用接口实现多重继承(Multiple inheritance)class extends 父类 implements 接口,interface CanFight void fight();interface CanSwim void swim();interface CanFly void fly();,class ActionCharacter public void fight(),class Hero extends ActionCharacter implements CanFight,CanSwim,CanFly public void swim()public void fly(),7,6.1.5 接口合并时的命名冲突,interface A1 void f();interface A2 int f(int i);interface A3 int f();,class C public int f()return 4;,class C1 implments A1,A2 public void f()public int f(int i)return 5;,class C2 extends C implments A2 public int f(int i)return 5;,class C3 extends C implments A3 public int f()return 5;,class C4 extends C implements A1,/overload,/overload,/implements and overriding,8,6.1.6 接口继承中的命名冲突,interface BaseColors int RED=1,GREEN=2,BLUE=4;interface RainbowColors extends BaseColors int YELLOW=3,ORANGE=5,VIOLET=6;interface PrintColors extends BaseColors int YELLOW=8,CYAN=16,MAGENTA=32;interface LotsOfColors extends RainbowColors,PrintColors int FUCHSIA=17,CHARTREUSE=RED+90;,class DD implements LotsOfColors public static void main(String args)System.out.println(YELLOW);,class DD public static void main(String args)System.out.println(LotsOfColors.YELLOW);,reference to YELLOW is ambiguous,both variable YELLOW in RainbowColors and variable YELLOW in PrintColors match,9,为什么需要包?使Java类更容易发现和使用防止命名冲突进行访问控制 层次结构,特定的功能A package is a collection of related classes and interfaces providing access protection and namespace management.import,6.2 包(package),10,/Graphic.java filepublic abstract class Graphic./Circle.java filepublic class Circle extends Graphic implements Draggable./Rectangle.java filepublic class Rectangle extends Graphic implements Draggable./Draggable.java filepublic interface Draggable.,容易地决定那些类和接口是相互关联的知道从哪里找到提供图形功能的类和接口由于包建立了一个新的名字空间,所以你定义的类不会同其他包中的类名有冲突可以容许在同一个包中无访问限制,同时可对在本包外的访问进行限制,11,包的创建 package graphics;public class Circle extends Graphic implements Draggable.包的命名层次结构对应实际的目录结构com.sun.org.w3c.org.jalpha.,6.2.1 包的创建,12,包的使用仅仅公共的(public)包成员(类、接口)可以在其所定义的包外被访问三种方式利用包成员的规范名(包名+类名)引入(import)包成员名引入(import)整个包成员,6.2.2 包的使用,13,例 package graphics;public class Circle extends Graphic implements Draggable.利用包成员的规范名(包名+类名)graphics.Circle myCir=new graphics.Circle();引入(import)包成员名import graphics.Circle;Circle myCir=new Circle();引入(import)整个包成员import graphics.*;Circle myCir=new Circle();,6.2.3 包的引入,14,如何防止名字冲突package graphics;public class Circle./package mygraphics;public class Circle.,6.2.4 防止名字冲突,import graphics.*;import mygraphics.*;class Test/Circle c;,import graphics.*;import mygraphics.*;class Test graphics.Circle c=new graphics.Circle();mygraphics.Circle c=new mygraphics.Circle();,15,6.2.5 包与Java文件的对应关系,package org.jalpha;public class HelloWorld.,根目录d:src源文件d:srcorgjalphaHelloWorld.java 编译cd d:srcjavac orgjalphaHelloWorld.javaclass文件d:srcorgjalphaHelloWorld.class 执行(在根目录)cd d:src java 执行(在其他目录)d:java classpath d:src,16,6.2.5 包与Java文件的对应关系,package org.aloha;import org.jalpha.*;import org.w3c.*;public class Test.,class文件(org.jalpha)d:src1orgjalpha*.class class文件(org.w3c)d:src2orgw3c*.class Test.class文件的根目录 d:src执行(在根目录)d:src java classpath执行(在其他目录)d:java classpath,17,6.3 常用工具类,Java 2 Platform PackagesJavaTM 2 Platform,Standard Edition,v 1.4.1 API SpecificationJava语言基础类、Java类库定义描述见Java2SDK文档135个包(package)java.applet;java.awt;java.io;java.lang;java.sql;java.text;java.utiljavax.swing 2723个类(class)和接口(interface)实现d:j2sdk1.4.1_01jrelibrt.jar(22.4MB)jar tvf rt.jar|more,18,6.3.1 java.lang包,java.lang包Object类System类Math类基本数据类型的包装类字符串操作类String类StringBuffer类StringTokenizer类(java.util包)Runtime类,19,6.3.2 类,Class Object is the root of the class hierarchy.Every class has Object as a superclass.All objects,including arrays,implement the methods of this class.子类可以对Object类的方法进行重写,构造方法-public Object(),实例方法protected Object clone()throws CloneNotSupportedExceptionpublic boolean equals(Object obj)protected void finalize()throws Throwablepublic final Class getClass()public int hashCode()public final void notify()public final void notifyAll()public String toString()public final void wait()throws InterruptedExceptionpublic final void wait(long timeout)throws InterruptedExceptionpublic final void wait(long timeout,int nanos)throws InterruptedException,20,6.3.3 类,静态变量public static final InputStream in(标准输入流)public static final PrintStream out(标准输出流)public static final PrintStream err(标准错误输出流)静态方法public static void arraycopy(Object src,int srcPos,Object dest,int destPos,int length)public static void exit(int status)public static void gc()public static long currentTimeMillis(),21,获取当前时间public static long currentTimeMillis()Returns:the difference,measured in milliseconds,between the current time and midnight,January 1,1970 UTC(Universal time coordinated).,public static void main(String args)long start=System.currentTimeMillis();long end=System.currentTimeMillis();System.out.println(end-start);,22,6.3.4 类,静态变量public static final double Epublic static final double PI静态方法public static double abs(double a)public static double ceil(double a)public static double floor(double a)public static double max(double a,double b),23,6.3.5 基本数据类型的包装类,基本数据类型:byte,short,int,long,float,double,boolean,char 对应的包装类:Byte,Short,Integer,Long,Float,Double,Boolean,Character作用包装类对象中包含有一个对应基本类型的值提供有基本类型和字符串(String)之间的转换函数定义有一些常数和方法,24,常数定义,byte largestByte=Byte.MAX_VALUE;/127short largestShort=Short.MAX_VALUE;/32767int largestInteger=Integer.MAX_VALUE;/2147483647long largestLong=Long.MAX_VALUE;/9223372036854775807float largestFloat=Float.MAX_VALUE;/3.40282e+38double largestDouble=Double.MAX_VALUE;/1.79769e+308,25,基本类型和字符串(String)之间的转换Integer类举例字符串转换为整数public static int parseInt(String s)throws NumberFormatExceptionpublic static int parseInt(String s,int radix)throws NumberFormatException,String s=“123”;int i=Integer.parseInt(s);,parseInt(0,10)parseInt(473,10)parseInt(-0,10)parseInt(-FF,16)parseInt(1100110,2)parseInt(2147483647,10)parseInt(-2147483648,10)parseInt(2147483648,10)parseInt(99,8)parseInt(Kona,10)parseInt(Kona,27),returns 0returns 473returns 0returns-255returns 102returns 2147483647returns-2147483648throws a NumberFormatExceptionthrows a NumberFormatExceptionthrows a NumberFormatExceptionreturns 411787,26,基本类型和字符串(String)之间的转换Integer类举例整数转换为字符串public static String toString(int i)public static String toString(int i,int radix)public static String toBinaryString(int i)public static String toHexString(int i)public static String toOctalString(int i),int i=123;String s1=Integer.toString(i);String s2=Integer.toString(i,10);String s3=Integer.toString(i,2);String s4=Integer.toString(i,8);String s5=Integer.toString(i,16);String s6=Integer.toBinaryString(i);String s7=Integer.toHexString(i);String s8=Integer.toOctalString(i);,12312311110111737b11110117b173,27,6.3.6 字符串操作类,三个类类类类不同的应用场合,28,类字符串/字符序列构造方法public String()public String(bytebytes)public String(bytebytes,intoffset,intlength)public String(bytebytes,StringcharsetName)public String(charvalue)public String(charvalue,intoffset,intcount)public String(Stringoriginal),29,类字符串/字符序列构造方法的使用,String s=new String();char c=a,b,c;String s=new String(c);char c=语,言;String s=new String(c);,byte b=97,98,99;String s=new String(b);String s=“abc”;String s=“语言”;,30,类字符串/字符序列判断字符串相等的方法public boolean equals(ObjectanObject)判断是否是同一个对象,是ture;然后anObject是否为一个字符串对象,否false;判断是否内容相同public boolean equalsIgnoreCase(StringanotherString)判断逻辑与equals相同,仅仅在判断内容上不考虑大小写public int compareTo(Objecto)若o不是字符串对象,则抛错;若是则调用下面的函数public int compareTo(StringanotherString)判断两个字符串的内容是否相同,是0;否不等于0的整数public int compareToIgnoreCase(Stringstr)基本功能同上,仅仅在判断时不考虑大小写,31,类字符串/字符序列判断字符串相等的方法,String s1=java语言;String s2=JavA语言;System.out.println(s1.equals(s2);System.out.println(s1.equalsIgnoreCase(s2);System.out.println(pareTo(s2);System.out.println(pareToIgnoreCase(s2);,运行结果:false true 32 0,32,类字符串/字符序列获取长度public int length()字符串的长度,即包含多少个字符获取特定子串(substring)和字符public String substring(intbeginIndex)public String substring(intbeginIndex,intendIndex)beginIndex:起始索引位置(包含)endIndex:结束索引位置(不包含)public char charAt(intindex),33,类字符串/字符序列方法举例,String s1=java语言;String s2=JavA语言;System.out.println(s1.length();System.out.println(s2.length();System.out.println(s1.substring(0,4);System.out.println(s1.substring(4);System.out.println(s2.substring(0,4);System.out.println(s2.substring(4);System.out.println(s1.charAt(0);,运行结果:66java语言JavA语言j,34,类字符串/字符序列字符串前缀(prefix)/后缀(suffix)的判断public boolean startsWith(Stringprefix)判断字符串是否以一特定的字符串开头public boolean startsWith(Stringprefix,inttoffset)public boolean endsWith(Stringsuffix)判断字符串是否以一特定的字符串开头,System.out.println(java语言.startsWith(java);System.out.println(java语言.startsWith(ava,1);System.out.println(java语言.endsWith(语言);,35,类字符串/字符序列查询特定字符/字符串的位置public int indexOf(intch)该字符在字符串中第一次出现位置的索引值;否则返回-1public int indexOf(intch,intfromIndex)public int indexOf(Stringstr)public int indexOf(Stringstr,intfromIndex)public int lastIndexOf(intch)public int lastIndexOf(intch,intfromIndex)public int lastIndexOf(Stringstr)public int lastIndexOf(Stringstr,intfromIndex),36,类字符串/字符序列方法举例,String s=“java语言”;System.out.println(s.indexOf(a);System.out.println(s.indexOf(a,2);System.out.println(s.indexOf(“a”);System.out.println(s.indexOf(“语言”);System.out.println(s.lastIndexOf(a);System.out.println(s.lastIndexOf(v,1);System.out.println(s.lastIndexOf(“语言”);System.out.println(s.lastIndexOf(“v”,2);,运行结果:13143-142,37,类字符串/字符序列字符串转变为数组public byte getBytes()将字符串转变为一个字节数组public byte getBytes(StringcharsetName)throws UnsupportedEncodingException 按特定的字符编码格式将字符串转变为一个字节数组public char toCharArray()将字符串转变为一个字符数组,38,类字符串/字符序列方法举例,String s=java语言;char c=s.toCharArray();System.out.println(c.length);byte b=s.getBytes();System.out.println(b.length);b=s.getBytes(ISO8859-1);System.out.println(b.length);,运行结果:686,中文Windows操作系统:默认字符集 GB2312其他系统:默认字符集 ISO-8859-1,39,类字符串/字符序列字符串public String split(String regex),40,类字符串/字符序列其他方法public String concat(Stringstr)连接字符串 cares.concat(s)returns caress to.concat(get).concat(her)returns together public String replace(charoldChar,charnewChar)在字符串中进行字符替换 mesquite in your cellar.replace(e,o)returns mosquito in your collar”JonL.replace(q,x)returns JonL(no change),41,类字符串/字符序列其他方法public String trim()将字符串头尾的空格字符删除public String toLowerCase()字符串中字符转为小写public String toUpperCase()字符串中字符转为大写一些静态方法public static String valueOf(booleanb)public static String valueOf(charc)public static String valueOf(inti)public static String valueOf(longl)public static String valueOf(floatf)public static String valueOf(doubled),42,类字符串/字符序列Quiz,String s1=new String(“java”);String s2=new String(“java”);System.out.println(s1=s2);System.out.println(s1.equals(s2);System.out.println(pareTo(s2);,运行结果:falsetrue 0truetrue0falsetrue0,String s3=“java”;String s4=“java”;System.out.println(s3=s4);System.out.println(s3.equals(s4);System.out.println(pareTo(s4);,System.out.println(s2=s4);System.out.println(s2.equals(s4);System.out.println(pareTo(s4);,结论:String s1=“abc”;字符串常量对象(immutable)String s2=“abc”;不同常量对象共享同一对象其他字符串对象则可理解为对字符串常量对象进行了 一层包装,System.out.println(s2.intern()=s4);,true,43,类字符串/字符序列Quiz,package testPackage;class Test public static void main(String args)String hello=Hello,lo=lo;System.out.println(hello=Hello);System.out.println(Other.hello=hello);=hello);System.out.println(hello=(Hel+lo);System.out.println(hello=(Hel+lo);System.out.println(hello=(Hel+lo).intern();class Other static String hello=Hello;,运行结果:truetrue truetruefalsetrue,package other;public class Other static String hello=Hello;,结论:Strings computed by constant expressions are computed at compile time and then treated as if they were literals.Strings computed at run time are newly created and therefore distinct.,44,类一个可变(mutable)/动态的字符序列构造方法public StringBuffer()public StringBuffer(Stringstr)主要方法添加(append)和插入(insert,指定位置)public StringBuffer append(booleanb)public StringBuffer insert(intoffset,booleanb)boolean,char,char,double,float,int,long,String转换为字符串-public String toString(),45,类方法举例,String s=java语言;StringBuffer buffer=new StringBuffer(s);buffer.append(“easy”);buffer.insert(6,“is“);s=buffer.toString();System.out.println(s);,运行结果:java语言 is easy.,46,字符串的连接运算(Concatenation)“java”和“语言”String s=“java”+“语言”;String s=“java”.concat(“语言”);StringBuffer buffer=new StringBuffer(“java”);buffer.append(“语言”);String s=buffer.toString();常用第1种和第3种方法,47,字符串的连接运算(Concatenation)+与append方法比较,class MyTimer private final long start;public MyTimer()start=System.currentTimeMillis();public long getElapsed()return System.currentTimeMillis()-start;,public class AppDemo static final int N=47500;public static void main(String args)MyTimer mt=new MyTimer();String str1=;for(int i=1;i=N;i+)str1=str1+*;System.out.println(#1s time=+mt.getElapsed();mt=new MyTimer();StringBuffer sb=new StringBuffer();for(int i=1;i=N;i+)sb.append(*);String str2=sb.toString();System.out.println(#2s time=+mt.getElapsed();,运行结果:#1s time=138750#2s time=20,效率和代码优化,48,字符串的连接运算(Concatenation)+:算术运算符int a=1,b=2;String c=“men”;String s=a+b+c;3 men隐含结合率(a+b)+cString s=c+b+a;men 21,49,java.util.StringTokenizer类将一个字符串按特定的要求切分开One String more Tokens构造方法public StringTokenizer(Stringstr)按默认的分隔符将字符串分割 四个字符“tnrf”public StringTokenizer(Stringstr,Stringdelim)按指定的分割符将字符串分割方法public boolean hasMoreTokens()判断是否有tokenpublic String nextToken()得到下一个token,50,java.util.StringTokenizer类方法举例,String s=this is a test;StringTokenizer st=new StringTokenizer(s);while(st.hasMoreTokens()System.out.println(st.nextToken();,运行结果:thisis