一、Java语言的描述

1、1、发展:

Sun公司:Oka(基于C和C++)——Java(太平洋盛产咖啡的岛屿名)(1995)

2009.04  Sun公司被Oracle收购

1、2、特点:

1、2、1 面向对象:

封装(用抽象的数据类型将数据与基于数据的操作封装在一起)

继承(一个对象通过继承直接使用另一个对象的属性和方法)

多态(1、覆盖:子类重写父类方法    2、重载:在一个类中定义多个不同的方法实现多态)

1、2、2 平台无关:

概念:java语言编写应用程序不用修改就可以在不同的软硬件平台上运行。

分类:

源代码级:应用程序不用修改只需要重新编译就可以在不同平台上运行(像这个C++)。

目标代码级:Java靠JVM在目标大妈级实现平台无关。

1、2、3 安全性:

字节码进入解释器必须经过字节码校验器检查。

Java解释器决定程序中类的布局。

类装载器负责将来自网络的类装载到单独的内存区域。

客户端可以限制从网络上装载的类只能访问某些文件系统。

1、2、4 支持网络编程:

1、2、5 支持多线程:

概念:线程小于进程的并发单位(C++没有内置的多线程只能调用操作系的多线程功能)

Java支持多线程的两个方面:

Java环境本身就是多线程(若干个系统线程运行的时候、回收无用单元、系统维护)

Java内置类多线程机制(也就是我们平常所说的多线程)

1、2、6 编译与解释并存:

大部分的语言都是编译(C++)或解释型(Basic)的语言,但Java是编译与解释并存。

概念:

Java源程序:.java文件

源程序命名:1、.java后缀  2、有public修饰类,类名与文件名相同  3、没有public修饰,类名与文件名可不同

字节码:在JVM中的指令组,即.class文件,使用字节码的好处是跨平台。

Java代码执行过程:

.java—编译器—>.class—解释器—>二进制码

1、3、 Java技术三方面:

JavaSE:Java标准版(即我们所说的Java语言部分、是JavaEE的基础)

JavaME:Java精简版

JavaEE:Java企业版

1、4、Java程序的种类:

Application(应用程序):

标志(public static void mian(String args[]))

含main方法的是主类

主类不要求必须是public的

直接运行

Applet(小程序):

标志(继承JApplet或Applet的子类)即主类

主类要必须是public

嵌入HTML页面、在浏览器运行

二、Java语言的开发环境

2、1、开发工具JDK:

概念:Java SE Development Kits,由Java API(核心,作用:提供标准类库)、Java运行环境、测试工具的Java实用程序组成

文件结构:

2、2、环境变量:

Path:设置操作系统去寻找可执行文件(.exe、.com、.bat)路径顺序、最先找到为准。

ClassPath:设置JVM搜索类路径的顺序,即指定解释器到哪里去找.class及相关程序。

2、3、运行Java应用源程序:

编译: javac  test.java

运行:java  test

2、4、运行Java小程序的两种方法:

直接执行相应的.html文件。

利用小程序查看器AppletViewer运行Java小程序。

三、Java语言基础

3、1数据类型(2类)

基本数据类型:byte short int long  float double char boolean

package demo3_1;public class Main {private static char chartest;public static void main(String[] args) {
//              数据类型                         字节数      包装类         默认值      取值范围boolean boolean_=true;          //     1                      false        true/falsebyte byte_=3;                   //     1          Byte          0          -128~127short short_=3;                 //     2          Short         0          -32768~32767int int_=3;                     //     4          Integer       0          -2147483648~2147483647long long_=2147483648l;         //     8          Long          0L         -9223372036854775808~9223372036854775807float float_=34.0f;             //     4          Float         0.0F       负数:-3.4E+38~-1.4E-45    正数:1.4E-45~3.4E+38double double_=23.0;            //     8          Double        0.0D       负数:-1.7E+308~-4.9E-324    正数:4.9E-324~1.7E+308char char_='9';                 //     2                       'u\0000'    'u\0000'~'u\ffff'int inta=(int)'a';//97int intA=(int)'A';//65char chara=(char)97;//achar charA=(char)65;//Achar char0=(char)20320;//你//     boolean boolean=1;      int不能转化为boolean
//      short short__;
//      short__+=short_;        局部变量声明后不赋赋值会出现编译错误 (堆内存与栈内存)
//          long long_=2147483648;  long类型的变量赋值时不加L或l,超出int类型数据范围时报错,没有超出是不报错
//      float float_=34.0;      float类型变量赋值时不加f或F,直接报错,不加的话默认是double类型的数据类型
//      Unicode字符编码              65536个字符     'u\0000'~'u\ffff'  }}

引用数据类型:类 对象 String Date

3、2关键字及标识符:

关键字50个:

byte short int long float double char boolean true false null void

if else return for  do while case switch default  continue break

try catch finally throw throws

import  package

extends  implements

final static

this super

new class interface

private public protected abstract

native assert transient enum synchronized volatile instanceof

标志符(类名、变量名、方法名、数组名、文件名):

非关关键字

由 字母、数字、_、$  构成

不能以数字开头

3、3常量(不能被修改的固定值)

整型常量                   final int A=03,B=0x12,E=0X12,C=23,D=23l;

浮点型常量               final float A=2.8e-2f,B=345E7F; final double A=2.8e-2,B=345E9D;

布尔型常量               final boolean A=true;

字符型常量               'a' '9'  '\b' '\n' '\r' '\t' '\\' '\'' '\"' '\uxxxx'(转义符)

字符串型常量           final String A="dafdasfdsa\u1234"(可包含转义符)

3、4变量

概念:通过变量操纵内存中的数据,变量“先声明、后使用”

四要素:名字(标识符)、类型(决定值的范围、可进行的操作、占用内存的大小)、值、作用域

int a=12,b=03,c=0x3e,d;

3、5数据类型的转换

自动类型转换(2个条件:类型兼容、转换前比转换后的范围大)

(char、byte、short)---->int---->float---->double

byte---->short(byte+short---->int)

char与byte short之间不能够进行自动类型转换

boolean类型不能做类型转换

类型转换不影响原先变量的定义

强制类型转换(需求是:大转小)

(float)a/b            a/(float)b        (float)a/(float)b

字符串与其他类型的转换

字符串---->数值类型:Boolean.paseBoolean(String s) 其他同理

数值类型---->字符串:String str=""+2345;

3、6键盘输入数据

package demo3_6;import java.util.Scanner;public class Stream_in_out {public static void main(String args[]) {Scanner scanner=new Scanner(System.in);boolean boo=scanner.nextBoolean();System.out.println(boo);byte bytevalue=scanner.nextByte();System.out.println(bytevalue);short shortvalue=scanner.nextShort();System.out.println(shortvalue);int intvalue=scanner.nextInt();System.out.println(intvalue);long longvalue=scanner.nextLong();System.out.println(longvalue);float floatvalue=scanner.nextFloat();System.out.println(floatvalue);double doublevalue=scanner.nextDouble();System.out.println(doublevalue);String  str1=scanner.nextLine();//接受回车键前的所有字符System.out.println("str1:"+str1);String  str2=scanner.next();//略去有效字符前的空格、回车、tab键,到空格、回车、tab键结束。System.out.println("str2:"+str2);char charvalue=scanner.next().charAt(0);//输入单个字符System.out.println("char:"+charvalue);}
}

3、7运算符及表达式

算术运算符:+、-、*、/、%、++、--

关系运算符:>、>=、<、<=、==、!=

逻辑运算符:&、|、!、^、&&、||

位运算符:   &、|、^、~、>>、<<、>>>

赋值运算符:=、+=、-=、*=、/=、%=、|=、&=、^=、>>=、<<=、>>>=

条件表达式:(表达式1)?(表达式2):(表达式3)

优先级:

. [] ()

++ -- ! ~ + - instanceof

new

* / %

+ -

<< >> >>>

< > <= >=

== !=

&

^

!

&&

||

?:

= += -= *= /= %= <<= >>= >>>= &= ^= |=

四、流程控制

4、1、顺序结构

4、2、分支结构

4、2、1 if else

4、2、2 switch

4、3、循环结构

4、3、1while

4、3、2do-while

4、3、3for

4、3、4break continue

package demo4_2;
//三个数中的最大数,最小数
import java.util.Scanner;public class Main {public static void main(String[] args) {int a,b,c,min,max;Scanner scanner=new Scanner(System.in);a=scanner.nextInt();b=scanner.nextInt();c=scanner.nextInt();if(a>b) {max=a;min=b;}else {max=b;min=a;}max=c>max?c:max;min=c<min?c:min;System.out.println("max:"+max);System.out.println("min:"+min);}}
package demo4_2;
//if else 嵌套循环
import java.util.Scanner;public class Main1 {public static void main(String[] args) {int score;char grade;Scanner scanner=new Scanner(System.in);score=scanner.nextInt();if(score>=90) {grade='A';}else if(score>=80) {grade='B';}else if(score>=80) {grade='C';}else if(score>=70) {grade='D';}else if(score>=60) {grade='E';}else {grade='F';}System.out.println(grade);}
}
package demo4_2;
//switch case结构
import java.util.Scanner;public class Main2 {public static void main(String[] args) {Scanner  scanner=new Scanner(System.in);int a=scanner.nextInt();int b=scanner.nextInt();char c=scanner.next().charAt(0);int result;switch (c) {//仅字符/整数类型case '+':result=a+b;System.out.println(result);break;case '-':result=a-b;System.out.println(result);break;case '*':result=a*b;System.out.println(result);break;case '/':result=a/b;System.out.println(result);break;default:System.out.println("输入字符有误");break;}      }}
package demo4_2;
//switch case
import java.util.Calendar;
import java.util.Scanner;public class Main3 {public static void main(String[] args) {Scanner scanner=new Scanner(System.in);Calendar calendar=Calendar.getInstance();int year=calendar.get(calendar.YEAR);System.out.println(year);int month=scanner.nextInt();int day;switch (month) {case 2:if(0==year%4&&0!=year%100||0==year%400) {day=29;}else {day=28;}System.out.println(day);break;case 1:case 3:case 5:case 7:case 8:case 12:day=31;System.out.println(day);break;default:day=30;System.out.println(day);break;}}}
package demo4_2;
//循环结构
import java.util.Scanner;public class Mian7 {public static void main(String[] args) {Scanner scanner=new Scanner(System.in);//1、int n;do {n=scanner.nextInt();}while(n<=0);//2、int i=1,sum=0;while(i<=n) {sum+=i++;}System.out.println(sum);//3、int numsum=0;for(int j=0;j<=10;j++) {numsum+=j;}System.out.println(numsum);}
}
package demo4_2;
//水仙花数:
public class Test3 {public static void main(String args[]) {for(int i=1;i<10;i++) {for(int j=0;j<10;j++) {for(int k=0;k<10;k++) {int num=i*100+j*10+k;int num2=i*i*i+j*j*j+k*k*k;if(num==num2) {System.out.println(num);}}}}for(int i=100;i<=999;i++) {int a=i/100;int b=(i-a*100)/10;int c=i-a*100-b*10;if(i==(a*a*a+b*b*b+c*c*c)) {System.out.print(i+" ");}}}
}

五、数组及字符串

5、0数组基本知识

5、0、1内存分类:

堆内存:new字符创建的对象(java中数组属于对象)。

栈内存:基本类型变量、对象的引用变量(int a[]=new int[10] 即这里的a变量,也即对象在内存中的首地址)。

int a[]=null;将引用变量赋予null值,表示该引用变量不指向任何的对象。

数组:

数组中的所有数据类型相同。

数据类型可以是基本数据类型、也可以是对象。

5、1、一维数组

5、1、1声明及初始化

package demo5_1;
//一维数组
import java.util.Arrays;public class Main {public static void main(String[] args) {//       动态分配内存int array[];//声明数组,并不分配内存,并且也不允许分配内存,此时数组还不可用
//      int array[10];错误array=new int[10];//分配内存,数组可用,并且每个元素都有一个默认值,整数:0、浮点数:0.0、字符:"\0"、boolean:false、引用类型的变量:nullarray[0]=12;for(int i=0;i<array.length;i++) {System.out.print(array[i]+"  ");}    int array1[]= {12,3,23,4,5,67,78,23,56};//声明数组,并不分配内存,并且也不允许分配内存,此时数组还不可用
//      int array1[9]= {12,3,23,4,5,67,78,23,56};//错误Arrays.sort(array1);//排序函数System.out.println();for(int i=0;i<array1.length;i++) {System.out.print(array1[i]+"  ");}int a=Arrays.binarySearch(array1, 56);//二分查找函数System.out.println("a:"+a);int  array2[]=Arrays.copyOf(array1, 3);//拷贝部分元素到另一个数组中for(int i=0;i<array2.length;i++) {System.out.print(array2[i]+"  ");}System.out.println(Arrays.equals(array1, array2));}
}

5、1、2

5、1、3

5、2、二维数组

5、2、1声明及初始化

package demo5_1;
//二维数组:
public class Main1 {public static void main(String[] args) {int array[][]=new int[2][];//对int array1[][]=new int[2][3];//对int array2[][];array2=new int[2][];//对int array3[][]= {{1,2,3,4},{2,3,4}};//对//       int array3[2][4]= {{1,2,3,4},{2,3,4}};//错for(int i=0;i<array3.length;i++) {for(int j=0;j<array3[i].length;j++) {System.out.print(array3[i][j]+"  ");}System.out.println();}//       int array2[2][]=new int[][];//错
//      int array3[][3]=new int[][];//错
//      int array4[][]=new int[][3];//错}}

5、2、2

5、2、3

5、3字符串

5、3、1声明及初始化

package demo5_1;
//字符串:
public class Main2 {public static void main(String[] args) {String string=new String("string");String str1="string";String str4="string";String str2="str";String str3="ing";str3=str2+str3;System.out.println(str1.equals(str4));System.out.println(str1.equals(string));System.out.println(str1.equals(str3));System.out.println(str1==string);System.out.println(str1==str4);System.out.println(str1==str3);}
}

5、3、2关键函数的源码:

5、3、3 String---->char str[]:

5、3、4char str[]---->String

5、3、5常用方法:

length()、equals()、substring(int beginIndex)、substring(int beginIndex,int endIndex)、charAt(int Index)、indexOf(String str)

replace(char oldChar,char newChar)、trim()、toLowerCase()、toUpperCase()

5、3、6 String、StringBuffer、StringBuilder的区别

1、速度:

String:字符串常量,对String的任何改变都会生成新的String对象。StringBuffer、StringBuilder字符串变量,对其的任何改变都不会产生新的对象。

2、安全:

StringBuffer方法被synchronized关键子修饰,线程安全,StringBuilder方法没有这个修饰,多线程并发时不能保证安全,但StringBuilder速度最快,所以单线程时,优先使用StringBuilder。

3、如何选择:

少量操作字符串时:String

单线程大量操作字符串:StringBuilder

多线程大量操作字符串:StringBuffer

5.4练习

六、类与对象

1、类:对某一类事物的描述,抽线概念上的定义,将数据及对数据的相关操作进行封装,形成特殊的数据结构。

类的特点:继承、封装、多态

对象:某类的具体个体,即实例。

构成:

成员变量(属性):非静态与静态变量(又叫类变量)

成员方法(行为):非静态与静态方法(又叫类方法)、构造函数与函数重载

2、类定义:

2、1类结构

[类修饰符] class 类名{

[修饰符] 变量类型 变量名[=初值]

static{ }

[修饰符]  返回值数据类型 方法名(参数1,参数2,参数3){

语句序列;

return[表达式];

}

}

修饰符:

public(可被任何对象访问)、abstract(抽象类)、final(非继承类)、缺省(相同包中才能访问)

注意:abstract 与final不能同时修饰一个类

2、1、1创建对象

package demo6_1;public class Cylinder{private double radius;int height;double pi=3.14;void area() {System.out.println("面积:="+pi*radius*radius);}void volume() {System.out.println("体积:="+pi*radius*radius*height);}public static void main(String args[]) {Cylinder volu=new Cylinder();volu.area();volu.volume();}}

2、1、2静态初始化器

格式:static  {     }

package demo6_2_4;public class TestStaticStruct {private static int intvariable;static {intvariable=10;}static {intvariable=2;}public static void main(String[] args) {TestStaticStruct testStaticStruct=new TestStaticStruct();System.out.println(testStaticStruct.intvariable);}
}

构造方法与静态初始化器的区别:

构造方法对每个新创建的对象初始化,静态初始化器是对类自身进行初始化。

构造方法是在用new运算符创建新对象时由系统自动执行,而静态初始化器一般不能由程序来调用,他是所属类被加载入内存时由系统执行调用;

构造方法执行次数与对象创建个数挂钩,但静态初始化器在类被加载入内存时执行一次,与创建多少个对象无关。

多个静态初始化器他们在类的初始化时会依次执行。

2、2成员变量:非静态与静态变量(又叫类变量)、成员变量与局部变量

类型:基本数据类型变量、对象、数组

定义:[修饰符] 变量类型 变量名[=初值]

修饰符:

public、private、 protected、缺省、fina、static、transient、 volatile

package demo6_2_2;public class TestBianliang {//访问控制修饰符public int publict;//allprivate int privatet;//仅己类protected int protectedt;//己类、同一包、子类int queshengt;//己类、同一包//其他修饰符final int finalt=0;//必须申明时赋值,之不能改变static int statict;//所有实例共享transient int transientt;//系统保留、暂无特别作用的临时变量。volatile int volatilet;//同时被几个线程控制修改。public int getPublict() {return publict;}public void setPublict(int publict) {this.publict = publict;}public int getPrivatet() {return privatet;}public void setPrivatet(int privatet) {this.privatet = privatet;}public int getProtectedt() {return protectedt;}public void setProtectedt(int protectedt) {this.protectedt = protectedt;}public int getQueshengt() {return queshengt;}public void setQueshengt(int queshengt) {this.queshengt = queshengt;}public static int getStatict() {return statict;}public static void setStatict(int statict) {TestBianliang.statict = statict;}public int getTransientt() {return transientt;}public void setTransientt(int transientt) {this.transientt = transientt;}public int getVolatilet() {return volatilet;}public void setVolatilet(int volatilet) {this.volatilet = volatilet;}public int getFinalt() {return finalt;}public static void main(String args[]) {TestBianliang testBianliang=new TestBianliang();testBianliang.setStatict(10);TestBianliang testBianliang2=new TestBianliang();testBianliang2.setStatict(testBianliang.getStatict()+10);System.out.println(testBianliang2.getStatict());System.out.println(testBianliang.getStatict());}}

2、2、1普通(实例)成员变量与类(静态)成员变量:

普通(实例)成员变量:没有被static修饰的变量,访问方式:对象.变量、每个实例对象独立拥有一个实例成员变量,必须创建实例才可以使用。

类(静态)成员变量:被static修饰的成员变量,    访问方式:对象.变量、类名.变量、类变量被所有的对象公有、在内存的公共存储单元中、无需创建实例即可调用。

package demo6_2_4;public class TestStaticBianliang {//一、成员变量分类区分private int a=34;//普通成员变量private static double d =90.00;//类成员变量public static void main(String[] args) {TestStaticBianliang testStaticBianliang=new TestStaticBianliang(); //测试成员变量System.out.println("普通变量访问:"+testStaticBianliang.a);System.out.println("类变量访问方式1:"+testStaticBianliang.d);System.out.println("类变量访问方式2:"+TestStaticBianliang.d);}}

2、2、2成员变量与局部变量(方法内变量)

成员变量可被上诉修饰符修饰,但局部变量只能被final修饰

成员变量存储在堆中、局部变量存储在栈中

成员变量随对象创建而存在、局部变量随方法的调用而产生

成员变量自动赋予初值(被final修饰没有被static修饰的变量必须显示赋值)、局部变量必须显示赋值

也即:成员变量系统自动赋初值,可声明时可以不赋值(static final除外)、局部变量申明时必须赋值、除基本变量外其余变量均为引用变量。

2、3成员方法:非静态与静态方法(又叫类方法)、构造函数与函数重载

作用:对类中的成员变量进行操作、实现内部功能的机制、同时是与外部进行交互的重要窗口。

定义:

[修饰符]  返回值数据类型 方法名(参数1,参数2,参数3){

语句序列;

return[表达式];

}

修饰符:public、private、protected、缺省、final、static、abstract、synchronized、native

package demo6_2_3;public abstract class TestFunction {//任何对象public void testPublic() {System.out.println("testPublic");}//己类private void testPrivate() {System.out.println("testPrivate");}//己类、子类、同包类protected void testProtected() {System.out.println("testProtected");}//己类、同包类void testQueShen() {System.out.println("testQueShen");}//此方法不能被子类覆盖public final void testFinal() {System.out.println("testFinal");}//可使用类名.的方式调用此方法,无需创建对象public static void testStatic() {System.out.println("testStatic");}//抽象方法public abstract void testAbstract();//同步方法、用于在多线程环境下去出控制土同步问题public  synchronized void testSychronized() {System.out.println("testSychronized");}//本地修饰符public native void testNative();}

2、3、1非静态与静态方法(又叫类方法):

非静态方法:调用(对象.方法)、被某个对象私有。

静态方法:   调用 (对象.方法   类名.方法)、被所有对象共有、存储于类的公共区域、只能访问静态成员、不允许this和super关键字存在。

package demo6_2_4;public class TestStaticBianliang {//一、成员变量分类区分private int a=34;//普通成员变量private static double d =90.00;//类成员变量//二、普通成员方法区分//1、静态成员方法:不能使用静态的成员public static void testStaticFunction() {System.out.println("我是静态变量");
//      System.out.println(a);报错:尝试使用非静态成员变量System.out.println(d);//使用静态成员
//      testNotStaticFunction();报错:尝试使用非静态方法staticFunction();//调用静态方法}//2、非静态成员方法:静态成员非静态成员都可以使用public void testNotStaticFunction() {System.out.println("我是非静态变量");System.out.println(a);//使用非静态成员变量System.out.println(d);//使用静态成员变量testStaticFunction();//调用静态方法notStaticFunction();//调用非静态方法}public void notStaticFunction() {System.out.println("我是非静态方法(非类方法)");}public static void staticFunction() {System.out.println("我是静态方法(非类方法)");}public static void main(String[] args) {TestStaticBianliang testStaticBianliang=new TestStaticBianliang();   //测试成员变量System.out.println("普通变量访问:"+testStaticBianliang.a);System.out.println("类变量访问方式1:"+testStaticBianliang.d);System.out.println("类变量访问方式2:"+TestStaticBianliang.d);}//静态方法中不能使用this关键字。
/*  public static int getA() {return this.a;}*/}

2、3、2构造函数:公有构造函数、私有构造函数

package demo6_2_4;public class TestStructure {private int intVariable;private byte byteVariable;private short shortVariable;private long longVariable;private double doubleVariable;private float floatVariable;private char charVariable;private boolean booleanVariable;//无参构造函数//在没有有参构造函数存在时,系统默认给每个类创建一个无参构造函数public TestStructure() {//super();this(89);//构造参数间相互调用}//一个参数的构造函数public TestStructure(int intVariable) {super();this.intVariable = intVariable;}//私有构造函数,只有在类内部才能够调用private TestStructure(int intVariable, byte byteVariable) {super();this.intVariable = intVariable;this.byteVariable = byteVariable;}//部分参数构造函数public TestStructure(int intVariable, byte byteVariable, short shortVariable, long longVariable) {this(30);//构造参数间相互调用this.intVariable = intVariable;this.byteVariable = byteVariable;this.shortVariable = shortVariable;this.longVariable = longVariable;}//全部参数构造函数public TestStructure(int intVariable, byte byteVariable, short shortVariable, long longVariable,double doubleVariable, float floatVariable, char charVariable, boolean booleanVariable) {super();this.intVariable = intVariable;this.byteVariable = byteVariable;this.shortVariable = shortVariable;this.longVariable = longVariable;this.doubleVariable = doubleVariable;this.floatVariable = floatVariable;this.charVariable = charVariable;this.booleanVariable = booleanVariable;}public static void main(String[] args) {TestStructure testStructure=new TestStructure();}
}

构造方法名与类名相同。

构造方法没有返回值、也不能写void。

构造方法作用是完成对类对象的初始化工作。

构造方法一般不能由编程人员显示调用,而是new关键字来调用。

创建一个类的同时系统会自动的调用该类构造方法为新对象初始化。

2、3、3函数重载

package demo6_2_4;public class TestChongZai {public void testChongZai() {System.out.println("testChongZai无参");}public void testChongZai(int a) {System.out.println("testChongZai无参");}public void testChongZai(int a,int b) {System.out.println("testChongZai 两个参数"+a+"   "+b);}public void testChongZai(int a,int b,int c) {System.out.println("testChongZai 三个参数"+b+"    "+c);}public void testChongZai(int a,int b,int c,int d) {System.out.println("testChongZai 四个参数"+a+"   "+b+"   "+c+"   "+d);}public static void main(String[] args) {TestChongZai testChongZai=new TestChongZai();testChongZai.testChongZai();testChongZai.testChongZai(10);testChongZai.testChongZai(10, 20);testChongZai.testChongZai(100, 200, 3400);testChongZai.testChongZai(100, 2000, 400, 700);}
}

多态的一种表现形式、方法名必须相同、参数列表不同(参数个数、类型)、仅是返回值不同不能称之为重载。

2、4方法参数传递

2、4、1以变量为参数调用方法

类作为一个封装体,封装了属性和方法,在进行参数传递时,方法括号内的参数可以是 基本数据类型、引用数据类型。

package demo6_2_4;public class TestFunctionDiaoyong {private int testvalue;TestFunctionDiaoyong testFunctionDiaoyong;public static void main(String[] args) {TestFunctionDiaoyong testFunctionDiaoyong=new TestFunctionDiaoyong();testFunctionDiaoyong.setObjectvalue(testFunctionDiaoyong);TestFunctionDiaoyong testFunctionDiaoyong2=testFunctionDiaoyong.getTestFunctionDiaoyong();System.out.println(testFunctionDiaoyong2.getTestvalue());}public int getTestvalue() {return testvalue;}public void setTestvalue(int testvalue) {//以基本类型变量为参数的方法调用this.testvalue = testvalue;}public void setObjectvalue(TestFunctionDiaoyong testFunctionDiaoyong) {//以引用类型为参数的方法调用this.testFunctionDiaoyong=testFunctionDiaoyong;}public TestFunctionDiaoyong getTestFunctionDiaoyong() {return testFunctionDiaoyong;}}

注意点:

public void setTestvalue(int testvalue),public void setObjectvalue(TestFunctionDiaoyong testFunctionDiaoyong),方法中的参数无论是基本类型还是对象均是局部变量,有效范围仅限于方法内部,一旦离开此方法,它们就会失去作用。

注意this关键字的使用,在方法参数与类成员变量同名情况下不用this及有this的区别。没有this关键字指定,默认方法内部使用参数,有this指定即是类成员变量。

2、4、2以数组作为参数或返回值的方法调用

数组作为参数、数组作为返回值:

package demo6_2_4;
public class TestArrayCanShu {public static void main(String[] args) {int array[]= {2,3,1,4,5,5,4,3,-1,-2,9};int arrayResult[][]=getMinAndLocation(array);System.out.println("最小元素下标:"+arrayResult[0][0]);System.out.println("最大元素值:"+arrayResult[0][1]);}public static int[][] getMinAndLocation(int array[]){int result[][]=new int[1][2];result[0][0]=0;result[0][1]=array[0];for(int i=0;i<array.length;i++) {if(array[i]<result[0][1]) {result[0][0]=i;result[0][1]=array[i];}}return result;}
}

注意:java语言在给被调用方法的参数赋值时,只采用传值方式,所以基本类型数据的传递是该数据的本身,而引用数据类型传递也是这个变量值本身,即对象的引用变量,而非对象本身,通过方法调用可以改变对象的内容,但对象的引用变量不能改变。

总结:参数是基本数据类型时,值传、参数是引用数据类型变量,传地址(本质上是传值,把引用变量的值传递过去,也即将对象地址传递了过去,不懂的见上图)。

2、4、3匿名对象,略过。

2、5对象的应用

2、5、1复习下变量类型:

基本类型变量:byte、short、int、long、float、double、char、boolean

引用类型变量:即类所创建的对象,引用类型变量保存内存中的对象的首地址,可以直接相互赋值,指向同一个变量。(不懂见上图创建对象部分)

2、5、2对象赋值与比较

package demo6_2_4;public class TestObject {private int a;public void  getA() {System.out.println(a);}public void setA(int a) {this.a = a;}public TestObject(int a) {super();this.a = a;}public void ComparyObject(TestObject testObject) {if(this==testObject) {System.out.println("对象相等");}else {System.out.println("对象不相等");}}public static void main(String[] args) {TestObject obj1=new TestObject(10);TestObject obj2=new TestObject(10);//对象赋值(拷贝)TestObject obj3=obj1;//指向同一对象,两个引用对数据的各种改变均针对此对象obj1.getA();obj3.setA(20);obj1.getA();//对象比较方法1obj1.ComparyObject(obj3);obj1.ComparyObject(obj2);//对象比较方法2System.out.println(obj1.equals(obj2));System.out.println(obj1.equals(obj3));}
}

2、5、3对象(引用类型)做方法参数或返回值:

package demo6_2_4;public class Person {private int age;public int getAge() {return age;}public void setAge(int age) {this.age = age;}public Person(int age) {super();this.age = age;}public Person getAgePull(Person person) {if(this.age>person.age) {return this;}else {return  person;}}public static void main(String[] args) {Person person=new Person(10);Person person2=new Person(20);Person person3=person.getAgePull(person2);System.out.println(person3.getAge());}}

2、5、4类类型的数组

第五章介绍过,数组中可以存放任何类型的数据,当热也包括对象类型。

package demo6_2_4;public class ObjectArray {private int age;private String  name;public ObjectArray(int age, String name) {super();this.age = age;this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public String getName() {return name;}public void setName(String name) {this.name = name;}public void show(){System.out.println("姓名:"+name+"  "+"年龄:"+age);}public static void main(String[] args) {ObjectArray per[]=new ObjectArray[3];per[0]=new ObjectArray(23,"张三");per[1]=new ObjectArray(12,"李四");per[2]=new ObjectArray(89,"王五");per[0].show();per[1].show();per[2].show();}
}

对象数组做参数进行方法调用

package demo6_2_4;public class TestObjectArray {private int age;public TestObjectArray(int age) {super();this.age = age;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public static int getMinAge(TestObjectArray obj[]) {int min=Integer.MAX_VALUE;for(int i=0;i<obj.length;i++) {if(min>obj[i].getAge()) {min=obj[i].getAge();}}return min;}public static void main(String[] args) {TestObjectArray objectArray[]=new TestObjectArray[3];objectArray[0]=new TestObjectArray(12);objectArray[1]=new TestObjectArray(234);objectArray[2]=new TestObjectArray(10);System.out.println(TestObjectArray.getMinAge(objectArray));}
}

小结:

1、java程序中可定义多个类,但只能有一个类是public的,此情况下文件名与public类名相同,没有public类,文件命名任意。

2、java对象实体和对象引用的关系?

对象引用的目的地才是对象的实体:
在java引用对象的赋值中,实际上是对引用的赋值;而对象实体不发生变换。
特别能够说明问题的是在引用型对象用final 关键字修饰的时候,表示引用的确定而不是对象实体的不可变。
final StringBuffer s = new StringBuffer();
s.append("abc") ;
这样是可以的,因为s引用指向确定的StringBuffer 对象,对象实体变化是可以的。
但是如果是String的话,就不可以显式的更改了。

3、java中应用程序main方法的定义为何是public static void main() 类型的?

java虚拟机装载运行时是调用mian()方法开始的,所以必须有main()方法,由于是在类外调用main()方法所以访问控制修饰符必须是public的,由于运行一个程序前没有创建main方法所在类的对象而是通过类名来直接调用,所以是static类型的。

七、内部类

1、成员内部类:作外部类成员存在和使用、就像成员变量和成员方法一样

成员内部类依赖外部类对象创建

成员内部类不能有static成员

成员内部类可随意访问外部类成员

外部类通过内部类对象访问内部类成员

package demo7_InnerClass;public class TestOutClassInnerClass {private int outVariable;//外部类方法访问内部类成员public void getOutVariable() {System.out.println("外部类方法"+" "+"外部内变量值:"+outVariable);InnerClass innerClass=new InnerClass();innerClass.innerVariable+=10;System.out.println("外部类方法调用内部类"+" "+"内部类变量值:"+innerClass.innerVariable);}//内部类public  class InnerClass{
//      static int a=10;private int innerVariable;public void getInnerVariable() {System.out.println("内部类方法");}public void getOutVariableAndFunction() {System.out.println("使用外部类成员变量"+" "+outVariable);outVariable+=10;System.out.println("使用外部类成员变量结束"+" "+outVariable);getOutVariable();}}public InnerClass getInnerClass() {return new InnerClass();}public static void main(String[] args) {TestOutClassInnerClass testOutClassInnerClass=new TestOutClassInnerClass();TestOutClassInnerClass.InnerClass innerClass=testOutClassInnerClass.getInnerClass(); TestOutClassInnerClass.InnerClass innerClass2=testOutClassInnerClass.new InnerClass();innerClass.getOutVariableAndFunction();innerClass2.getOutVariableAndFunction();TestOutClassInnerClass testOutClassInnerClass1=new TestOutClassInnerClass();TestOutClassInnerClass.InnerClass innerClass3=testOutClassInnerClass1.getInnerClass(); TestOutClassInnerClass.InnerClass innerClass4=testOutClassInnerClass1.new InnerClass();innerClass3.getOutVariableAndFunction();innerClass4.getOutVariableAndFunction();}
}

2、静态内部类:被static修饰的内部类

静态内部类创建不需要依赖外部类

不能使用任何外部类非static的成员

package demo7_InnerClass;public class TestStaticInnerClass {private int out_publicVariable;private static int out_staticVariable;public void outClassFunction() {System.out.println("外部类普通方法被调用");}public static void outClassStaticFunction() {System.out.println("外部类静态方法被调用");}public void TestInnerClass() {StaticInnerCalss staticInnerCalss=new StaticInnerCalss();//静态内部类内部类的创建System.out.println(staticInnerCalss.in_publicVariable);System.out.println(staticInnerCalss.in_staticVariable);System.out.println(StaticInnerCalss.in_staticVariable);}//static innerClasspublic static class StaticInnerCalss{private int in_publicVariable;private static int in_staticVariable;public void InnerClassFunction() {System.out.println(out_staticVariable);
//          System.out.println(out_publicVariable);访问非静态类型的变量出错out_staticVariable+=1;
//          outClassFunction();访问外部类非静态方法失败outClassStaticFunction();//访问外部类静态方法}}public static void main(String[] args) {TestStaticInnerClass testStaticInnerClass=new TestStaticInnerClass();System.out.println(testStaticInnerClass.out_staticVariable);StaticInnerCalss staticInnerCalss=new StaticInnerCalss();staticInnerCalss.InnerClassFunction();System.out.println(testStaticInnerClass.out_staticVariable);StaticInnerCalss staticInnerCalss1=new StaticInnerCalss();staticInnerCalss1.InnerClassFunction();System.out.println(testStaticInnerClass.out_staticVariable);}}

3、局部内部类

方法内部类和作用域内部类没有访问修饰符,方法或作用域中的内部类对包围他的方法和作用域之外的任何东西都不可见。/

3、1方法内部类

package demo7_InnerClass;public class TestFunctionClass {public String  testFunctionClass(){final String name="方法内的局部内部类";int m=200;class Inner{private int data;public String  function() {data=10+m;return name+data;}}Inner inner=new Inner();return name+inner.function();}public static void main(String[] args) {TestFunctionClass testFunctionClass=new TestFunctionClass();System.out.println(testFunctionClass.testFunctionClass());}}

3、2作用域内部类

package demo7_InnerClass;
public class TestLocationClass {public String getFruit() {final String name="苹果";String string="";if(name.equals("苹果")) {class InnerClass{private String fruit;public void setFruit() {fruit="apple";}}InnerClass innerClass=new InnerClass();innerClass.setFruit();string=name+innerClass.fruit;}return string;}public static void main(String[] args) {TestLocationClass testLocationClass=new TestLocationClass();System.out.println(testLocationClass.getFruit());}
}

4、匿名内部类

匿名内部类后面的分号不可缺

匿名内部类没有访问修饰符

new 匿名内部类、这个类一定要存在(先定义的接口)

被匿名内部类使用的方法的形参必须用final修饰

匿名内部类不能有构造方法

package demo7_InnerClass;
public class TestInner {public InnerClass getInnerClass(final String name) {return new InnerClass(){private String name1;@Overridepublic void setName() {// TODO Auto-generated method stubname1="姓名"+name;}@Override       public String getName() {// TODO Auto-generated method stubreturn name1;}};//千万别少分号}public static void main(String[] args) {TestInner testInner=new TestInner();InnerClass innerClass=testInner.getInnerClass("张三");innerClass.setName();System.out.println(innerClass.getName());}
}

八、继承、抽象类与接口、包:抽象类和接口是对类概念的一个拓展

1、继承

目的:代码重用、进一步抽象

注意:单继承,子承父。

1、1子类创建

extends关键字

所有类间接的是Object的子类

每个能用父类的对象的地方都能够使用子类对象,但是父类的对象不一定是子类的对象

子类能够继承父类非private的成员

调用子类的构造函数前会先调用父类的无参构造函数

package demo8_abstractClass_Interface;
//父类
class Person{private String name;private int age;public Person() {System.out.println("父类的构造参数");}public void setNameAndAge(String name,int age) {this.age=age;this.name=name;}public void show() {System.out.println("姓名:"+name+" "+"年龄:"+age);}
}
//子类
class Student extends Person{private String department;public Student() {System.out.println("子类构造函数被调用");}public void setDepartment(String department) {this.department=department;System.out.println("我是"+department+" 系的学生");}}
//主类:测试类
public class TestExtends {public static void main(String args[]) {Student student=new Student();student.setNameAndAge("张三", 23);//子类调用父类的方法student.setDepartment("计算机");//子类调用自己的方法student.show();//子类调用父类的方法}}

1、2调用父类特定的构造方法

super(参数列表)调用父类的构造参数

子类通过super(参数列表)调用父类的构造方法时,如果参数列表为空时,父类没有相应无参构造函数调用报错

super()与this()功能相似,super()子类调用父类的构造方法,而this()是同个类里面构造函数之间相互调用

super()与this()都只能位于构造方法的第一行,所以两者无法处于同一个构造函数中

super()与this()关键子都不能位于static块中,因两者都是对象

package demo8_abstractClass_Interface;
//父类
class Person{private String name;private int age;public Person() {System.out.println("父类的无参构造函数");}public Person(String name, int age) {super();System.out.println("父类的有参构造函数");this.name = name;this.age = age;}public void show() {System.out.println("姓名:"+name+" "+"年龄:"+age);}
}
//子类
class Student extends Person{private String department;public Student() {super();System.out.println("子类无参构造函数被调用");}public Student(String department,int age,String name) {super(name,age);System.out.println("子类有参构造函数被调用");this.department=department;System.out.println("我是"+department+" 系的学生");}}
//主类:测试类
public class TestExtends {public static void main(String args[]) {Student student=new Student("计算机", 23,"哈哈哈哈");Student student2=new Student();student.show();student2.show();}
}

1、3子类访问父类的成员

super.成员变量名

super.成员函数名

package demo8_abstractClass_Interface;//父类
class Person{protected String name;protected int age;public Person() {System.out.println("父类的无参构造函数");}public Person(String name, int age) {super();System.out.println("父类的有参构造函数");this.name = name;this.age = age;}public void show() {System.out.println("姓名:"+name+" "+"年龄:"+age);}}
//子类
class Student extends Person{private String department;public Student() {super();System.out.println("子类无参构造函数被调用");}public Student(String department,int age,String name) {super.age=age;//子类调用父类成员变量super.name=name;super.show();//子类调用父类的成员方法System.out.println("子类有参构造函数被调用");this.department=department;System.out.println("我是"+department+" 系的学生");}}
//主类:测试类
public class TestExtends {public static void main(String args[]) {Student student=new Student("计算机", 23,"哈哈哈哈");Student student2=new Student();student.show();student2.show();}}

1、4覆盖

方法名、返回值、参数列表完全相同

子类不能覆盖父类中申明为final或static类型的方法

覆盖是子类可扩大父类访问权限但是不能够缩小访问权限

package demo8_abstractClass_Interface;//父类
class Person{protected String name;protected int age;public Person() {System.out.println("父类的无参构造函数");}public Person(String name, int age) {super();System.out.println("父类的有参构造函数");this.name = name;this.age = age;}protected void show() {System.out.println("姓名:"+name+" "+"年龄:"+age);}}//子类
class Student extends Person{private String department;public Student() {super();System.out.println("子类无参构造函数被调用");}public Student(String department,int age,String name) {super.age=age;//子类调用父类成员变量super.name=name;this.department=department;}public void show() {//子类覆盖父类中的方法System.out.println("部门:"+department);}}//主类:测试类
public class TestExtends {public static void main(String args[]) {Student student=new Student("计算机", 23,"哈哈哈哈");student.show();}}

子类方法改为private时:测试覆盖的权限扩展问题

1、5父类访问子类的成员

仅限覆盖发生时。

向上转型:将子类的对象由父类引用,默认类型。Person per=new Student("计算机",34,"张三")

向下转型:将父类的对象由子类引用,得显示类型转换。Student stu=(Student)per;

package demo8_abstractClass_Interface;
//父类
class Person{protected String name;protected int age;public Person() {System.out.println("父类的无参构造函数");}public Person(String name, int age) {super();System.out.println("父类的有参构造函数");this.name = name;this.age = age;}protected void show() {System.out.println("姓名:"+name+" "+"年龄:"+age);}
}
//子类
class Student extends Person{private String department;public Student() {super();System.out.println("子类无参构造函数被调用");}public Student(String department,int age,String name) {super.age=age;//子类调用父类成员变量super.name=name;this.department=department;}protected void show() {System.out.println("部门"+department);}protected void subShow() {System.out.println("部门"+department);}
}//主类:测试类
public class TestExtends {public static void main(String args[]) {Person per=new Student("计算机", 23,"哈哈哈哈");per.show();
//      per.subShow();报错}
}

1、6不能被继承的成员及最终类

static final+变量 :常量、申明立即赋值(只能这样)、仅一次赋值

final+变量:两种赋值方法:定义是赋初值+构造方法中赋初值、仅一次赋值

final+方法:不能被子类覆盖但能够继承

private修饰/final类中的方法:不能被继承、不能被重载

1、7Object类

所有类都直接或间接的是Object的子类

源码:


public class Object {private static native void registerNatives();static {registerNatives();}public final native Class<?> getClass();public native int hashCode();public boolean equals(Object obj) {return (this == obj);}protected native Object clone() throws CloneNotSupportedException;public String toString() {return getClass().getName() + "@" + Integer.toHexString(hashCode());}public final native void notify();public final native void notifyAll();public final native void wait(long timeout) throws InterruptedException;public final void wait(long timeout, int nanos) throws InterruptedException {if (timeout < 0) {throw new IllegalArgumentException("timeout value is negative");}if (nanos < 0 || nanos > 999999) {throw new IllegalArgumentException("nanosecond timeout value out of range");}if (nanos > 0) {timeout++;}wait(timeout);}public final void wait() throws InterruptedException {wait(0);}protected void finalize() throws Throwable { }
}

可被覆盖的方法:

测试代码:

package demo8_abstractClass_Interface;class TestObject{private int age;@Overridepublic String toString() {return "TestObject [age=" + age + "]";}@Overrideprotected void finalize() throws Throwable {// TODO Auto-generated method stubsuper.finalize();System.out.println("垃圾回收前执行的函数");}}public class TestObjectClass {public static void main(String[] args) {Object object=new Object();TestObject testObject=new TestObject();TestObject testObject1=new TestObject();TestObject testObject2=testObject;TestObject testObject3=testObject;Class obj=testObject.getClass();System.out.println(obj.getName());System.out.println(obj.getSuperclass());System.out.println(obj.isInterface());System.out.println(testObject.getClass());System.out.println(testObject.hashCode());System.out.println(testObject1.hashCode());System.out.println(testObject2.hashCode());System.out.println(testObject.equals(object));System.out.println(object.toString());System.out.println(testObject.toString());try {testObject3.finalize();} catch (Throwable e) {// TODO Auto-generated catch blocke.printStackTrace();}}}

结果:

instanceof:对象运算符

package demo8_abstractClass_Interface;
class Book{private String name;@Overridepublic String toString() {// TODO Auto-generated method stubreturn super.toString();}public void show() {Object object=this;if(object instanceof Book) { System.out.println("是BOOK的对象");}if(object instanceof EnglishBook) { System.out.println("是EnglishBook的对象");}}}class EnglishBook extends Book{private int page;@Overridepublic String toString() {// TODO Auto-generated method stubreturn super.toString();}public void show() {Object object=this;if(object instanceof Book) { System.out.println("是BOOK的对象");}if(object instanceof EnglishBook) { System.out.println("是EnglishBook的对象");}}
}public class TestInstanceof {public static void main(String[] args) {Book book=new Book();book.show();EnglishBook englishBook=new EnglishBook();englishBook.show();}}

2、抽象类

抽象类不能够直接创建对象,由其子类实现所有抽象方法后即可创建对象、不实现所有抽象方法子类依旧是抽象类。

抽象类不一定含抽象方法(可是含普通方法)、但含抽象方法的类一定是抽象类。

抽象类的成员变量可由任何修饰符修饰。

抽象方法可以有构造函数。略显多余,因为其不能创建对象。

抽象方法没有{}。

abstract 不能和final修饰一个类。

abstract不能和private、static、final、native修饰同一方法。

package demo8_abstractClass_Interface;abstract class Shape{protected String name;public Shape(String name) {super();this.name = name;}abstract public double getArea();abstract public double getLength();}class Cricle extends Shape{private static final double PI=3.14;private double radius;public Cricle(String name, double radius) {super(name);this.radius = radius;}@Overridepublic double getArea() {// TODO Auto-generated method stubreturn PI*radius*radius;}@Overridepublic double getLength() {// TODO Auto-generated method stubreturn 2*PI*radius;}}class Rectangle extends Shape{private double length;private double height;public Rectangle(String name, double length, double height) {super(name);this.length = length;this.height = height;}@Overridepublic double getArea() {// TODO Auto-generated method stubreturn length*height;}@Overridepublic double getLength() {// TODO Auto-generated method stubreturn 2*(length+height);}}
public class TestAbstractClass {public static void main(String[] args) {Cricle cricle=new Cricle("圆", 2);System.out.println(cricle.getArea());System.out.println(cricle.getLength());Rectangle rectangle=new Rectangle("长方形", 12, 4);System.out.println(rectangle.getLength());System.out.println(rectangle.getArea());}}

3、接口

3、1定义

接口不能够创建对象,只有实现该接口抽象方法的类才可一创建对象

实现接口时抽象方法须声明为public的

接口可做引用类型来使用,可定义接口类型的变量和数组。

接口中的成员变量只能是public static final,即为常量

package demo8_abstractClass_Interface;
interface IShape{final double PI=3.14;public abstract double getArea();public abstract double getLength();
}
class Cricle2 implements IShape{private double radius;private String name;public Cricle2(double radius, String name) {super();this.radius = radius;this.name = name;}@Overridepublic double getArea() {// TODO Auto-generated method stubreturn PI*PI*radius;}@Overridepublic double getLength() {// TODO Auto-generated method stubreturn 2*PI*radius;}
}
class Regctangle2 implements IShape{private double height;private double length;public Regctangle2(double height, double length) {super();this.height = height;this.length = length;}@Overridepublic double getArea() {return 2*height*length;}@Overridepublic double getLength() {return 2*(height+length);}
}
class Test{public static void main(String args[]) {Cricle2 cricle2=new Cricle2(12, "圆");System.out.println(cricle2.getArea());System.out.println(cricle2.getLength());Regctangle2 regctangle2=new Regctangle2(78, 2);System.out.println(regctangle2.getLength());System.out.println(regctangle2.getArea());}
}

3、2接口的多重继承

与父接口重名的成员变量被隐藏、方法被覆盖

多实现

package demo8_abstractClass_Interface;interface Face1{double PI=3.14;
}
interface Face2{void getArea();
}
interface Face3{void getLength();
}class TestInfaceExtends implements Face1,Face2,Face3{private String name;private double radius;public TestInfaceExtends(String name, double radius) {super();this.name = name;this.radius = radius;}@Overridepublic void getLength() {// TODO Auto-generated method stubSystem.out.println(2*PI*radius);}@Overridepublic void getArea() {// TODO Auto-generated method stubSystem.out.println(PI*radius*radius);}}class Test1{public static void main(String[] args) {TestInfaceExtends testInfaceExtends=new TestInfaceExtends("圆", 3);testInfaceExtends.getArea();testInfaceExtends.getLength();}
}

多重继承

package demo8_abstractClass_Interface;interface Face1{double PI=3.14;
}
interface Face2{void getArea();
}
interface Face3 extends Face2,Face1{void getLength();
}class TestInfaceExtends implements Face3{private String name;private double radius;public TestInfaceExtends(String name, double radius) {super();this.name = name;this.radius = radius;}@Overridepublic void getLength() {// TODO Auto-generated method stubSystem.out.println(2*PI*radius);}@Overridepublic void getArea() {// TODO Auto-generated method stubSystem.out.println(PI*radius*radius);}}class Test1{public static void main(String[] args) {TestInfaceExtends testInfaceExtends=new TestInfaceExtends("圆", 3);testInfaceExtends.getArea();testInfaceExtends.getLength();}
}

4、包

1、目的:区别类名空间的机制,因为多个类可能重名、毕竟public类名与文件名要求相同。

2、同一文件中的各种类/接口:均在一包下,包由import引入,由ClassPath下的路径去找包。

3、Java语言的常用包(所有包详见(JDK8在线参考手册):https://docs.oracle.com/javase/8/docs/api/index.html):

3、1java.lang(提供java最基础的类、每个java程序默认引用java.lang包)

Object类、数据类型包装类、字符串类、数学类、系统和运行时类、类操作类、错误及异常处理类、线程类、过程类

3、2java.io

基本/文件/过滤/管道/随机  输入/输出流。

3、3java.awt/swing

抽象窗口类:绘图、各种控件、布局管理、事件类

3、4java.util

数据输入类、日期类、链表类、向量、哈希表、栈类、树类

3、5javax.swing.JApplet

3、6java.net

访问网络资源、套接字、服务器端套接字类、数据报打包类、数据报通信类

3、7java.sql

jdbc连接数据库

3、8java.text

Format、DataFormat、SimpleDateFormat提供各种文本或日期格式

5、java语言的垃圾回收机制

5、1 单独开一个线程用于垃圾回收、自动垃圾回收

5、2 引用计数器的数值为0时对象可以被回收

5、3 程序员通过System.gc与Runtime.gc 提示垃圾回收器执行垃圾回收、但不可强制垃圾回收器回收对象。

5、4 对象被释放前,由垃圾回收器调用finalze方法(讲object类时有提及)。

6、总结:

1、为什么子类构造函数执行之前需要去默认调用父类的无参构造函数 ?

为了初始化父类的某些私有成员。

2、this与super有什么特殊含义?

this:调用本类的成员方法及成员变量、调用本类其他构造方法。

super:子类调用父类的构造函数、子类访问父类的成员变量与成员方法。

3、接口与抽象类的区别?

3、1、接口成员变量public static final 而抽象类成员变量为任意访问控制修饰符

3、2、接口成员方法为public abstract 而抽象类可含抽象方法与普通方法

3、3、接口不能有构造函数,而抽象类可以有

3、4、接口间可以多继承,并可以被一个类实现,而抽象类只能单继承

4、Java为什么要使用内部类?

java接口+内部类  :可以解决Java单继承的问题。

九、异常处理

基于JDK1.8下的error与exception思维导图:

异常抛出两种方式:系统自动抛出(仅限系统运行时异常)、指定方法抛出异常

异常处理的两种形式:try_catch_finally自己处理、throw/throws抛往上层调用机构处理抛出异常。

注意:非运行时异常,Java必须处理。对运行时异常Java可不做处理、由java运行时系统来处理。

多异常处理:try-catch-catch-finally

package demo9;public class TestExeception {public static void main(String[] args) {int num[]= {1,2,3,4};for(int i=0;i<5;i++) {try {System.out.print(num[i]+" ");System.out.println("5/0:"+5/0);}catch (ArithmeticException e) {System.out.println("除数为0");}catch (ArrayIndexOutOfBoundsException e) {System.out.println("下标越界");}finally {System.out.println("finally");}}}
}

异常执行语句次序:

两个判断:try程序块中是否有异常产生、产生的异常是否与catch后的异常类型匹配。

catch块中:主要输出异常相关信息、包括异常名、产生异常的方法名。

多个catch:子类异常比父类异常先捕获,否则编译不同过,报如下截图错误。

try中一个异常产生后、其后代码均不执行,finally中一般对一些资源做清理工作。

catch块中有System.exit(0)程序不执行finally中语句,有return语句先执行finally再返回。

抛出异常:

1、抛出异常的方法与调用方法处理异常

1、1方法体内部抛出异常:throw(抛出系统自定义的异常没有什么意义,这种情况一般是抛出我们自定义的异常)

package demo9;public class TestFunctionException {public static void main(String[] args) {int a=5,b=0;try {if(b==0) {throw new ArithmeticException();}else {System.out.println(a+"/"+b+"="+a/b);}}catch (ArithmeticException e) {System.out.println("异常:"+e+"被抛出了");e.printStackTrace();}}}

一个方法没有对自己所产生的异常进行捕获,那么调用该函数的方法就应该捕获处理异常。

package demo9;public class TestFunctionException_function {public static double muti(int n) {if(n<0) {throw new IllegalArgumentException("求负数阶乘异常");}double s=1;for(int i=1;i<=n;i++) {s=s*i;}return s;}public static void main(String args[]) {try {int m=Integer.parseInt(args[0]);System.out.println(m+"!="+muti(m));} catch (ArrayIndexOutOfBoundsException e) {System.out.println("命令行中没有参数");}catch (NumberFormatException e) {System.out.println("应该输入一个整数");}catch (IllegalArgumentException e) {System.out.println("出现的异常是"+e.toString());}finally {System.out.println("程序运行结束");}}}

1、2方法头部抛异常:throws

package demo9;public class TestFunctionException_throw {public static void check(String str1)throws NullPointerException {if(str1.length()>2) {str1=null;System.out.println(str1.length());}char ch;for(int i=0;i<str1.length();i++) {ch=str1.charAt(i);if(!Character.isDigit(ch));{throw new NumberFormatException();}}}public static void main(String[] args) {int num;try {check("2s");num=Integer.parseInt("2s");if(num>60) {System.out.println("成绩为:"+num+" 及格");}else {System.out.println("成绩为:"+num+" 不及格");}}catch (NullPointerException e) {System.out.println("空指针异常:"+e.toString());}catch (NumberFormatException e) {System.out.println("输入不是数值类型");}catch (Exception e) {System.out.println("命令行没有提供参数");}finally {System.out.println("程序执行结束");}}
}

2、由方法抛出异常交系统处理

在main方法头部throws抛出异常:

package demo9;import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;public class TestSystemExeception {public static void main(String[] args) {String str;BufferedReader buf;buf=new BufferedReader(new InputStreamReader(System.in));while(true) {try {System.out.print("请输入字符串");str=buf.readLine();if(str.length()>0) {break;}else {throw new IOException();}} catch (IOException e) {System.out.println("必须输入字符串");continue;}}String string=str.toUpperCase();System.out.println("转换后的字符串为:"+string);}
}

自定义异常:用于处理用户程序中可能产生的特定的运行时异常。

步骤:

1、声明异常类、直接或间接extendsThrowable、推荐extends Exeception。

2、定义属性、方法,习惯加两个构造方法,分别是没有参数和含有字符串的参数。

注意:用户自定的异常不能够有系统自动抛出,只能够借助throw语句来定义何种情况算是产生这种异常。

package demo9;class TestMyselfExeception extends Exception {double radius;public TestMyselfExeception(double radius) {super();this.radius = radius;}@Overridepublic String toString() {return "半径r="+radius+"不是一个正数";}}class Cricle{private double radius;public void setRadius(double r)throws TestMyselfExeception{if(r<0) {throw new TestMyselfExeception(r);}else {radius=r;}}public void show() {System.out.println("面积为= "+3.14*radius*radius);}public static void main(String args[]) {Cricle cricle=new Cricle();try {cricle.setRadius(-2.0);} catch (TestMyselfExeception e) {System.out.println("自定义异常"+e.toString());}cricle.show();}}

十、Java语言的输入输出与文件处理

1、所用API均在Java.io包中。

2、相关概念:

流:计算机各部件之间的数据流动。

缓冲流:以字节为单位,建立缓冲区、目的是提高数据传输效率。

字节流:处理字节数据(InputStream/OutputStream)一次读8位二进制数,多应用于处理图片、音频。可以处理文本文件、但不推荐,因为字节流不能直接操作Unicode字符,所以中文会乱码。

字符流:处理字符数据(Reader/Writer),Java中的字符采用16位的Unicode编码,16位二进制数,多用于处理文本文件。

输入流/输出流:如下图

3、基于JDK1.8下的输入/输出流框架思维导图:

4、InputStream:源码


package java.io;public abstract class InputStream implements Closeable {private static final int MAX_SKIP_BUFFER_SIZE = 2048;public abstract int read() throws IOException;public int read(byte b[]) throws IOException {return read(b, 0, b.length);}public int read(byte b[], int off, int len) throws IOException {if (b == null) {throw new NullPointerException();} else if (off < 0 || len < 0 || len > b.length - off) {throw new IndexOutOfBoundsException();} else if (len == 0) {return 0;}int c = read();if (c == -1) {return -1;}b[off] = (byte)c;int i = 1;try {for (; i < len ; i++) {c = read();if (c == -1) {break;}b[off + i] = (byte)c;}} catch (IOException ee) {}return i;}public long skip(long n) throws IOException {long remaining = n;int nr;if (n <= 0) {return 0;}int size = (int)Math.min(MAX_SKIP_BUFFER_SIZE, remaining);byte[] skipBuffer = new byte[size];while (remaining > 0) {nr = read(skipBuffer, 0, (int)Math.min(size, remaining));if (nr < 0) {break;}remaining -= nr;}return n - remaining;}public int available() throws IOException {return 0;}public void close() throws IOException {}public synchronized void mark(int readlimit) {}public synchronized void reset() throws IOException {throw new IOException("mark/reset not supported");}public boolean markSupported() {return false;}}

5、OutputStream:源码

package java.io;public abstract class OutputStream implements Closeable, Flushable {public abstract void write(int b) throws IOException;public void write(byte b[]) throws IOException {write(b, 0, b.length);}public void write(byte b[], int off, int len) throws IOException {if (b == null) {throw new NullPointerException();} else if ((off < 0) || (off > b.length) || (len < 0) ||((off + len) > b.length) || ((off + len) < 0)) {throw new IndexOutOfBoundsException();} else if (len == 0) {return;}for (int i = 0 ; i < len ; i++) {write(b[off + i]);}}public void flush() throws IOException {}public void close() throws IOException {}}

6、从键盘输入一串字符,写入文件,在将文件中的内容显示到屏幕。

package demo10_Stream;import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;public class TestStream {public static void main(String[] args) throws IOException {FileInputStream fileInputStream;FileOutputStream fileOutputStream = null;int ch;int data;fileInputStream=new FileInputStream(FileDescriptor.in);try {fileOutputStream=new FileOutputStream("E:\\PROJECT\\eclipse\\java\\java_project\\repository\\bin\\demo10_Stream\\myfile.txt");} catch (FileNotFoundException e) {System.out.println("文件没找到");e.printStackTrace();}System.out.println("输入字符串,以#符号结束!!");while((ch=fileInputStream.read())!=(int)'#') {fileOutputStream.write(ch);}fileInputStream.close();fileOutputStream.close();fileInputStream=new FileInputStream("E:\\PROJECT\\eclipse\\java\\java_project\\repository\\bin\\demo10_Stream\\myfile.txt");fileOutputStream=new FileOutputStream(FileDescriptor.out);while(fileInputStream.available()>0) {data=fileInputStream.read();fileOutputStream.write(data);}fileInputStream.close();fileOutputStream.close();}}

7、使用字节流完成图片二进制图片文件复制:

package demo10_Stream;import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;public class TestImage {public static void main(String[] args) throws IOException {try {FileInputStream fileInputStream=new FileInputStream("E:\\PROJECT\\eclipse\\java\\java_project\\repository\\bin\\demo10_Stream\\image.png");FileOutputStream fileOutputStream=new FileOutputStream("E:\\PROJECT\\eclipse\\java\\java_project\\repository\\bin\\demo10_Stream\\image1.png");System.out.println("文件大小:"+fileInputStream.available());byte[] b=new byte[fileInputStream.available()];fileInputStream.read(b);fileOutputStream.write(b);fileInputStream.close();fileOutputStream.close();} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();}}
}

8、使用字节流完成图片二进制视频文件复制:

package demo10_Stream;import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;public class TestImage {public static void main(String[] args) throws IOException {try {FileInputStream fileInputStream=new FileInputStream("E:\\PROJECT\\eclipse\\java\\java_project\\repository\\bin\\demo10_Stream\\video.mp4");FileOutputStream fileOutputStream=new FileOutputStream("E:\\PROJECT\\eclipse\\java\\java_project\\repository\\bin\\demo10_Stream\\video1.mp4");System.out.println("文件大小:"+fileInputStream.available());byte[] b=new byte[fileInputStream.available()];fileInputStream.read(b);fileOutputStream.write(b);fileInputStream.close();fileOutputStream.close();} catch (FileNotFoundException e) {e.printStackTrace();}}}

9、 过滤输入输出流(输入输出时决定按几个字节来操作):

DataInputStream/DataOutputStream:java中按基本数据类型读写的数据流。(下面这段代码有问题,while循环判断条件最后一次读取'\0'时抛出异常,但不知道是怎么回事)。

package demo10_Stream;import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;/**
*@auther:
*@version: 2018年11月25日下午2:11:20
*@description: 测试数据输入输出流的用法
*/public class TestDataInputOut {/*** @param args* @auther: * @version: 2018年11月25日下午2:50:37* @description:main方法*/public static void main(String[] args) {FileOutputStream fileOutputStream;FileInputStream fileInputStream;DataOutputStream dataOutputStream;DataInputStream dataInputStream;
//      写文件try {fileOutputStream=new FileOutputStream("E:\\PROJECT\\eclipse\\java\\java_project\\repository\\src\\demo10_Stream\\testDataIO.txt");dataOutputStream=new DataOutputStream(fileOutputStream);dataOutputStream.writeInt(100);dataOutputStream.writeByte(20);dataOutputStream.writeShort(100);dataOutputStream.writeLong(2000000000);dataOutputStream.writeFloat(20.04F);dataOutputStream.writeDouble(20.098765);dataOutputStream.writeBoolean(false);dataOutputStream.writeChar('c');dataOutputStream.writeChars("adoahgaohgioahgaioh");} catch (Exception e) {}
//      读文件try {fileInputStream=new FileInputStream("E:\\PROJECT\\eclipse\\java\\java_project\\repository\\src\\demo10_Stream\\testDataIO.txt");dataInputStream=new DataInputStream(fileInputStream);System.out.println(dataInputStream.readInt());System.out.println(dataInputStream.readByte());System.out.println(dataInputStream.readShort());System.out.println(dataInputStream.readLong());System.out.println(dataInputStream.readFloat());System.out.println(dataInputStream.readDouble());System.out.println(dataInputStream.readBoolean());System.out.println(dataInputStream.readChar());char chare;while((chare=dataInputStream.readChar())!='\0') {System.out.print(chare);}dataInputStream.close();} catch (IOException e) {e.printStackTrace();System.out.println("文件未找到!!!!");}}
}

10、标准输入输出流:

前面的例子中,Java程序与外设之间进行数据交换时,均需要建立一个输入输出流的对象,完成与外设之间的连接,但对于标准的输入输出流则不需用。

一般计算机系统、标准输入流是指:键盘;标准输出流:屏幕显示器。

java 中标准输入输出流的包:java.lang.System

System.in、System.out、System.err这三个对象在java源程序编译时自动装载。

package demo10_Stream;import java.io.IOException;/**
*@auther:胡波
*@version: 2018年11月25日下午6:44:08
*@description:
*/public class TestSystem {/*** @param args* @auther: 胡波* @version: 2018年11月25日下午6:46:46* @description:main函数*/public static void main(String[] args) {byte[] b=new byte[128];System.out.println("请输入字符:");try {int count=System.in.read(b);System.out.println("输入的是:");for(int i=0;i<count;i++) {System.out.print(b[i]+" ");}System.out.println();for(int i=0;i<count-2;i++) {System.out.print((char)b[i]+" ");}System.out.println();System.out.println("输入字符的个数为:"+count);Class inClass=System.in.getClass();Class outClass=System.out.getClass();System.out.println("in所在的类是:"+inClass);System.out.println("out所在的类是:"+outClass);} catch (IOException e) {e.printStackTrace();}}
}

注意:'\n'、'\r';即回车符和换行符均被当作两个字符。

11、Reader和Writer类的源码:

Writer源码:


package java.io;public abstract class Writer implements Appendable, Closeable, Flushable {private char[] writeBuffer;private static final int WRITE_BUFFER_SIZE = 1024;protected Object lock;protected Writer() {this.lock = this;}protected Writer(Object lock) {if (lock == null) {throw new NullPointerException();}this.lock = lock;}public void write(int c) throws IOException {synchronized (lock) {if (writeBuffer == null){writeBuffer = new char[WRITE_BUFFER_SIZE];}writeBuffer[0] = (char) c;write(writeBuffer, 0, 1);}}public void write(char cbuf[]) throws IOException {write(cbuf, 0, cbuf.length);}abstract public void write(char cbuf[], int off, int len) throws IOException;public void write(String str) throws IOException {write(str, 0, str.length());}public void write(String str, int off, int len) throws IOException {synchronized (lock) {char cbuf[];if (len <= WRITE_BUFFER_SIZE) {if (writeBuffer == null) {writeBuffer = new char[WRITE_BUFFER_SIZE];}cbuf = writeBuffer;} else {    // Don't permanently allocate very large buffers.cbuf = new char[len];}str.getChars(off, (off + len), cbuf, 0);write(cbuf, 0, len);}}public Writer append(CharSequence csq) throws IOException {if (csq == null)write("null");elsewrite(csq.toString());return this;}public Writer append(CharSequence csq, int start, int end) throws IOException {CharSequence cs = (csq == null ? "null" : csq);write(cs.subSequence(start, end).toString());return this;}public Writer append(char c) throws IOException {write(c);return this;}abstract public void flush() throws IOException;abstract public void close() throws IOException;}

Reader源码:


package java.io;public abstract class Reader implements Readable, Closeable {protected Object lock;protected Reader() {this.lock = this;}protected Reader(Object lock) {if (lock == null) {throw new NullPointerException();}this.lock = lock;}public int read(java.nio.CharBuffer target) throws IOException {int len = target.remaining();char[] cbuf = new char[len];int n = read(cbuf, 0, len);if (n > 0)target.put(cbuf, 0, n);return n;}public int read() throws IOException {char cb[] = new char[1];if (read(cb, 0, 1) == -1)return -1;elsereturn cb[0];}public int read(char cbuf[]) throws IOException {return read(cbuf, 0, cbuf.length);}abstract public int read(char cbuf[], int off, int len) throws IOException;private static final int maxSkipBufferSize = 8192;private char skipBuffer[] = null;public long skip(long n) throws IOException {if (n < 0L)throw new IllegalArgumentException("skip value is negative");int nn = (int) Math.min(n, maxSkipBufferSize);synchronized (lock) {if ((skipBuffer == null) || (skipBuffer.length < nn))skipBuffer = new char[nn];long r = n;while (r > 0) {int nc = read(skipBuffer, 0, (int)Math.min(r, nn));if (nc == -1)break;r -= nc;}return n - r;}}public boolean ready() throws IOException {return false;}public boolean markSupported() {return false;}public void mark(int readAheadLimit) throws IOException {throw new IOException("mark() not supported");}public void reset() throws IOException {throw new IOException("reset() not supported");}abstract public void close() throws IOException;
}

12、FileReader和FileWriter读写文件:

FileReader读取文件内容

package demo10_Stream;import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;/**
*@auther:
*@version: 2018年11月25日下午7:16:34
*@description: FileReader实验代码
*/
public class TestFileReader {/*** @param args* @auther: * @version: 2018年11月25日下午7:30:18* @description:main函数*/public static void main(String[] args) {char []chars=new char[500];try {FileReader fileReader=new FileReader("E:\\PROJECT\\eclipse\\java\\java_project\\repository\\src\\demo10_Stream\\test.txt");int num=fileReader.read(chars);String string=new String(chars, 0, num);System.out.println("读取的字符个数为:"+num+",其内容如下:");System.out.println(string);fileReader.close();} catch (FileNotFoundException e) {e.printStackTrace();}catch (IOException e) {e.printStackTrace();}}}

FileWriter写入文件:

package demo10_Stream;import java.io.FileWriter;
import java.io.IOException;/**
*@auther:
*@version: 2018年11月26日上午10:41:52
*@description: 测试FileWriter的实验代码
*/
public class TestFileWriter {public static void main(String[] args) {try {FileWriter fWriter=new FileWriter("E:\\PROJECT\\eclipse\\java\\java_project\\repository\\src\\demo10_Stream\\testfileWriter.txt", true);char charbuf[]= {'h','n'};String string="欢迎使用java!!!";fWriter.write(charbuf);fWriter.write(string);fWriter.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}

13、bufferedWriter、bufferedReader(带缓冲区的文件读写):

1、buffferedReader读取文件、并输出内容:

package demo10_Stream;
/**
*@auther:胡波
*@version: 2018年12月9日下午6:38:53
*@description:
*/import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;public class TestBufferReader {public static void main(String args[]) {String thisLine;int count=0;try {FileReader fReader=new FileReader("E:\\PROJECT\\eclipse\\java\\java_project\\repository\\src\\demo10_Stream\\test.txt");BufferedReader bufferedReader=new BufferedReader(fReader);while((thisLine=bufferedReader.readLine())!=null) {count++;System.out.println(thisLine);}System.out.println("读出数据行数:"+count);}catch(IOException e){System.out.println("error");}}
}

2、bufferedWriter写文件内容:

package demo10_Stream;import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;/**
*@auther:胡波
*@version: 2018年12月9日下午7:48:10
*@description:
*/
public class TestBufferWriter {public static void main(String args[]) throws IOException {String string=new String();try {BufferedReader bufferedReader=new BufferedReader(new FileReader("E:\\PROJECT\\eclipse\\java\\java_project\\repository\\src\\demo10_Stream\\test.txt"));BufferedWriter bufferedWriter=new BufferedWriter(new FileWriter("E:\\PROJECT\\eclipse\\java\\java_project\\repository\\src\\demo10_Stream\\test1.txt"));while((string=bufferedReader.readLine())!=null) {System.out.println(string);bufferedWriter.write(string);bufferedWriter.newLine();//写入回车换行符}bufferedWriter.flush();bufferedWriter.close();bufferedReader.close();} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();}}
}

14、计算机程序运行时,数据保存在系统内存中,由于关机时内存中的数据全部丢失,所以必须把那些需要长期保存的数据存放磁盘文件中,需要时载从文件中读出来,因此文件的输入输出操作重要性不言而喻。

1、java.io包中:定义一个File类专门用来管理磁盘文件及文件夹,不负责数据的输入输出,每一个File类对象表示一个磁盘文件或文件夹,其对象属性中包含了对文件及文件夹的操作,对磁盘文件的顺序读写。

2、文件/文件夹属性测试:

package demo10_Stream;import java.io.File;/**
*@auther:胡波
*@version: 2018年12月9日下午8:49:00
*@description:
*/
public class TestFile {public static void main(String[] args) {// TODO Auto-generated method stubString string_of_filedir="E:\\PROJECT\\eclipse\\java\\java_project\\repository\\src\\demo10_Stream";String string_of_filedir1="E:\\PROJECT\\eclipse\\java\\java_project\\repository\\src\\demo10_Stream";File fdir1=new File(string_of_filedir);File fdir2=new File(string_of_filedir1);System.out.println("exists:"+fdir1.exists());System.out.println("isFile:"+fdir1.isFile());System.out.println("isDirectory:"+fdir1.isDirectory());System.out.println("getName:"+fdir1.getName());System.out.println("getPath:"+fdir1.getPath());System.out.println("length:"+fdir1.length());System.out.println("canRead:"+fdir1.canRead());System.out.println("canWrite:"+fdir1.canWrite());System.out.println("equals:"+fdir1.equals(fdir2));String str[]=fdir1.list();for(int i=0;i<str.length;i++) {System.out.println("str["+i+"]:  "+str[i]);}}}

3、文件随机访问:

RandomAccessFile:java.io 包中定义的类,任意位置、任意文件的读写,任意读写而不是顺序读写。

package demo10_Stream;import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;public class TestRandomAccessFile {public static void main(String[] args) throws IOException {// TODO Auto-generated method stubStringBuffer stringBufferDir=new StringBuffer();System.out.println("输入文件路径:");char ch;while((ch=(char)System.in.read())!='\r') {stringBufferDir.append(ch);}File dir=new File(stringBufferDir.toString());System.out.println("请输入欲读文件名:");StringBuffer stringBufferFileName=new StringBuffer();char c;while((c=(char)System.in.read())!='\r') {stringBufferFileName.append(c);}stringBufferFileName.replace(0, 1, "");File readFrom=new File(dir,stringBufferFileName.toString());if(readFrom.isFile()&&readFrom.canRead()&&readFrom.canWrite()) {RandomAccessFile raFile=new RandomAccessFile(readFrom, "rw");while(raFile.getFilePointer()<raFile.length()) {System.out.println(new String(raFile.readLine().getBytes("ISO-8859-1"),"GBK"));//解决读取乱码问题}raFile.close();}else {System.out.println("文件不可读");}}
}

15、测试部分。                                                                                                                                                                                  1、创建指定的文件夹、在该文件夹下创建指定名称的文件、利用文件读写流向该文件写入一行文本内容,在利用文件读写流读出该刚才写入该文件的内容。(注意文件的转码问题)

package demo10_Stream;import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;public class TestDemo {public static void main(String[] args) {// TODO Auto-generated method stubFile file_dir=new File("E:\\Eclipse_workspace\\maven_project\\JavaBasis\\src\\demo10_Stream\\testCreatFile");//     创建文件夹if(!file_dir.exists()) {file_dir.mkdir();}//       在指定文件夹下创建文件if(file_dir.isDirectory()) {File newFile=new File(file_dir,"newfile.txt");if(!newFile.exists()) {try {newFile.createNewFile();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}System.out.println("文件名:"+newFile.getName());System.out.println("文件夹名:"+newFile.getParent());}}try {File file_rw=new File("E:\\Eclipse_workspace\\maven_project\\JavaBasis\\src\\demo10_Stream\\testCreatFile\\newfile.txt");//创建输入流:RandomAccessFile randomAccessFile = null;if(file_rw.canRead()&&file_rw.canWrite()&&file_rw.exists()) {randomAccessFile=new RandomAccessFile(file_rw, "rw");}byte[] bytes="在文本中写入一行文本内容".getBytes();//String.getBytes()方法自动调用系统默认的编码方式byte[] bytes2="在文本中写入一行文本内容2".getBytes();//String.getBytes()方法自动调用系统默认的编码方式randomAccessFile.write(bytes);randomAccessFile.write('\r');randomAccessFile.write(bytes2);//创建输出流:RandomAccessFile randomAccessFile2=null;if(file_rw.canRead()&&file_rw.canWrite()&&file_rw.exists()) {randomAccessFile2=new RandomAccessFile(file_rw, "rw");}while(randomAccessFile2.getFilePointer()<randomAccessFile2.length()) {//编码转换System.out.println(new String(randomAccessFile2.readLine().getBytes("ISO-8859-1"),"GBK"));}} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();System.out.println("文件不存在");} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();System.out.println("将文本信息写入文件时发生错误");}}}

2、 产生15个 20到9999之间的随机整数,  然后利用BufferedWriter类将其写入到file2.txt中,之后再读取该文件中的数据然后对其进行一个冒泡排序。

代码略。读者可以自己思考下,后面我会贴出代码。

十一、泛型和容器类

1、泛型: JDK5开始引入。

1、1简介:将数据类型参数化,减少类型转换,减少类型强制转换ClassCastException.

1、2分类:

1、2、1泛型类(即声明成员变量、成员方法参数或返回值时使用<T>中的类型)

注意:

创建泛型类的对象时必须指明泛型代表的具体类型。(这也是泛型类与泛型方法的区别

自动包装:如第20行,形参为Integer类型接受实参为int类型,将int自动包装为Integer。

自动解包装:如第21行,自动解包装。

T的值:必须是引用类型,包括类,接口,甚至是类型变量。是基本类型会出错

1、2、2泛型接口

1、2、3泛型方法

(将方法返回值前面加上<T>即可注意保持参数类型和返回值类型的泛型参数类型相同

泛型方法不一定非要在泛型类中,两者没有必然的联系。

调用泛型方法时,没必要指明泛型的具体类型。编译器有一个类型参数推断(只发生在赋值语句)。

package demo11;public class TestGenericFunction {public static void main(String[] args) {// TODO Auto-generated method stubInteger intArray[]= {1,2,3,4,5,6,7,8,9};String strArray[]= {"ceshi","hadahg","的李康康的","科技当","大","哈","修好大"};int testint[]= {1,2,3,4,5,6,7,8,9};display(intArray);display(strArray);//display(testint);为基本类型会出错}public static <T>void display(T[] list){for(int i=0;i<list.length;i++) {System.out.print(list[i]+"  ");}}
}

2、容器:

java基础覆盖——知识库搭建-1相关推荐

  1. Java从入门到实战总结-1.1、Java基础之环境搭建和eclipse安装

    Java从入门到实战总结-1.1.Java基础之环境搭建和eclipse安装 文章目录 Java从入门到实战总结-1.1.Java基础之环境搭建和eclipse安装 1.Hello Java 1.1. ...

  2. Java基础语法-环境搭建及入门

    1. Java概述 1.1 Java语言背景介绍(了解) 语言:人与人交流沟通的表达方式 计算机语言:人与计算机之间进行信息交流沟通的一种特殊语言 Java语言是美国Sun公司(Stanford Un ...

  3. java写一个外网访问的接口_【JAVA基础】一个案例搞懂类、对象、重载、封装、继承、多态、覆盖、抽象和接口概念及区别(中篇)...

    0 前言 初学JAVA时,总会对一些概念一知半解,相互混淆,不明其设计的用意,如类.对象.重载.封装.继承.多态.覆盖.抽象类.接口概念.为便于理解和巩固,本文将基于一个案例及其变形,展现各个概念的定 ...

  4. JAVA基础知识学习全覆盖

    文章目录 一.JAVA基础知识 1.一些基本概念 1.Stringbuffer 2.局部变量成员变量 3.反射机制 4.protect 5.pow(x,y) 6.final ,finally,fina ...

  5. Java基础第一讲:Java的故事和Java编程环境搭建

    { Android学习指南 } 适于自学的ANDORID学习指南,基于ANDROID 2.2.2.3.3及3.0版本讲解 <ANDROID学习指南>目录 RSS Java基础第一讲:Jav ...

  6. 【Java开发语言 01】第一章 Java语言概述(基础常识+Java语言概述+Java程序运行机制及运行过程+Java语言环境的搭建+开发体验hello world+错误:编码GBK的不可映射字符)

    java入门-第一章Java语言概述 1基础常识 软件开发 人机交互方式 常用的DOS命令(win系统,有一些直接通过命令执行的) 2 Java语言概述 什么是计算机语言 关于面向对象和面向过程 Ja ...

  7. Java基础:01Java语言概述(常见的DOS命令,Java语言的特点、核心机制、环境搭建,HelloWorld,注释,Java API 文档)

    Java基础:01Java语言概述 一.常见的DOS命令 二.Java语言的特点 面向对象性 健壮性 跨平台型 三.Java两种核心机制 1. Java虚拟机 2. 垃圾回收 四.Java语言的环境搭 ...

  8. Java开发环境的搭建与基础语法(温习知识点)

    复习昨日内容 * Java语言概述* Java语言概述&发展史[了解]* Java的跨平台[了解]* JDK JRE JVM 有什么作用[理解] * Java开发环境的搭建 * JDK的下载与 ...

  9. Java基础部分 阶段一(语法基础)1、开发环境搭建(计算机编程及开发语言)

    day01 一.编程基础 计算机=硬件+软件 软件分为:系统软件.应用软件 软件开发:使用编程语言进行编写能够实现若干功能的应用. (1)编译型(直接二进制) 优点:执行效率高 缺点:平台依赖重,跨平 ...

最新文章

  1. 安装SQL Server 2012示例数据库
  2. ASCX呼叫ASPX.CS的方法
  3. nginx 获取真实ip
  4. Linux Centos6.5在哪里输入命令
  5. linux的系统移植——交叉编译工具集
  6. django 1.8 官方文档翻译: 3-1-1 URL调度器
  7. 华为手机遮挡html页面,手机知识:华为手机老是显示屏幕被遮挡
  8. LeaRun.Java可视化流程简单配置过程
  9. Spark入门基本操作
  10. .NET 开源GIS解决方案一 概述
  11. android4.4中添加方案,Android4.0-4.4 添加实体按键振动支持的方法(java + smali版本)
  12. 《Head First 设计模式》例子的C++实现(4 单件模式)
  13. 常用moment时间总结
  14. Excel多条件筛选不重复项
  15. 使用Java自动化方法模拟Android手机点击、触屏事件
  16. vue 重写element input限制字数
  17. matlab草稿本,解读草稿本——这个学具,你可千万不能忽视
  18. flutter clean
  19. 双机(51单片机)串行通信最基本的方法
  20. 随机数rand和srand的用法

热门文章

  1. 【Qt教程】2.6 - Qt5 自定义控件封装
  2. Java:源文件名、公共类名、main()方法之间关系
  3. 使用html+css仿搜狐网址页面布局
  4. HttpComponents入门解析
  5. 敏捷开发一千零一问系列之五:怎样让队员主动要活?
  6. SpringBoot------集成PageHelper分页功能
  7. 【学习随笔】iquery初涉
  8. soap协议有get方式
  9. MySQL Membership
  10. Kerberos工作流:一个简单示例