文章目录

  • Capter 3 面对对象基础概念
    • 3.1 主要特性
    • 3.2 类与对象
      • 3.2.1 类与对象的基本概念
      • 3.2.2 类与对象的基本定义
      • 3.2.3 引用数据
      • 3.2.3封装性
        • 用private封装(setterANDgetter)
      • 3.2.4 构造方法
      • 3.2.5 匿名对象
      • 3.2.6 数组
        • 一维数组
        • 二维数组
        • 数组与方法参数的传递
        • 数组小练习(未完待续......)
          • 冒泡排序
  • 待办
      • 数组的操作方法
      • 对象数组
    • 3.2.7 String的基本类型操作
      • 字符与字符串
      • 字节与字符串
      • 字符串的比较
      • 字符串的替换
      • 字符串的截取
      • 字符串的拆分
      • 字符串的其他操作
        • 字符串的连接
        • 大小写转义
      • 去掉左右空格
      • 字符串的长度
      • 判断空字符串
      • 首字母大写
    • 3.2.8 this关键字
      • 本类属性
      • 本类方法
      • 当前对象
    • 3.2.9 引用传递
      • 实例
    • 3.2.10 数据表与简单的java映射
      • 雇佣关系
      • 城市与省份的关系
    • 3.2.11 对象比较
    • 3.2.12 static关键字
    • 3.2.13代码块
    • 3.2.14内部类
  • Capter 4 面对对象高级知识
    • 4.1继承性
      • 4.1.1 继承的实现
      • 4.1.2 继承的限制
    • 4.2 覆写
      • 4.2.1方法的覆写
        • 重载与覆写的区别:
      • 4.2.2 属性的覆盖
        • this和super的区别:
    • 4.3 继承案例(未完待续.....)
    • 4.4 final关键字
    • 4.5多态性
    • 4.6抽象类
    • 4.7接口
      • 抽象类和接口的区别
    • 4.8Object类
  • Capter 5 包
    • 5.1包的定义
    • 5.2包的导入
    • 5.3系统常见包
    • 5.4 jar命令
    • 5.4 访问控制权限
    • 5.4 命名规范
  • Capter 6 异常地捕捉及处理
  • Capter 6 Eclipse的使用
  • Capter 8 Java新特性
    • 8.1可变参数
    • 8.2 foreach循环
    • 83 静态导入
  • Capter 9 多线程
  • Capter 10 Java常用库类(未完待续)
    • 10.1 StringBuffer
    • 10.2 RinTime类
    • 10.3 System类
    • 10.4 对象克隆
  • Capter 11 Java IO编程
    • 文件操作类File
      • 创建文件
      • 创建带路径的文件
      • 取得文件或目录的信息
      • 列出目录信息--listFiles
      • 利用递归列出目录结构-- print(result[i]);//递归调用
    • 字节流与字符流
      • 字节输出流:OutputStream
    • 文件内容的输出
      • 字节输入流:InputStream
      • 输入流与输出流的部分总结:

Capter 3 面对对象基础概念

3.1 主要特性

  • 封装
  • 继承
  • 多态

3.2 类与对象

3.2.1 类与对象的基本概念

提问:什么是类?
在面对对象中类和对象是最基本,最重要的组成单元,类实际上是表示一个客观世界中某类群体的一些基本特征抽象,属于抽象的概念集合。
类实际上是对象操作的模板,但是类不能直接使用,必须通过实例对象来使用

3.2.2 类与对象的基本定义


//声明成员变量(属性)class 类名称{数据类型 属性(变量);//定义方法的内容public 返回值的数据类型 方法名称(参数1,参数2){程序语句;[return 表达式;]}}
class Book{String title;double price;public void getInfo(){System.out.println("图书名称:"+title+"价格:"+price );}}

灵魂拷问:为什么getInfo()不用加static
回答:调用形式不同。在主类中定义,并且由主方法直接调用的方法必须加上static,但是因为Book类的getInfo()方法将会由对象调用,与之前的调用形式不同,所以暂时不用加上static

类定义完成后,不可以直接使用

格式:声明并实例化对象
类名称 对象名称=new 类名称()
当一个对象实例化之后就可以按照如下的方式利用对象操作类的结构
1.对象.属性
2.对象.方法()
class Book{String title;double price;public void getInfo(){System.out.println("图书名称:"+title+"价格:"+price );}}
public class one{public static void main(String[] args) {Book book=new Book();book.title="java开发";book.price=89.9;book.getInfo();}
}

报错原因:你自己想!朕累了~~

package capterThree;public class one {class Book{String title;double price;public void getInfo(){System.out.println("图书名称:"+title+"价格:"+price );}}
public class TestDemo{public static void main(String[] args) {Book book=new Book();book.title="java开发";book.price=89.9;book.getInfo();}
}
}
  • 只要看见了关键字new不管何种情况下,都表示要开辟新的堆内存空间
  • 使用对象时一定需要一块对应的堆内存空间,而堆内存空间的开辟需要通过关键字new来完成,每一个对象在刚刚实例化后,里面的属性的内容都是其对应数据类型的默认值
  • 没有进行实例化操作的话,会出现控制性异常(NullPointerException)

3.2.3 引用数据

不同的名字(栈内存)指向了同一个实体(堆内存)

分析:bookB=bookA这句话表明bookB的内存将指向bookA的内存空间,也表示bookA对应的堆内存空间同时被bookB所指向,即:两个不同的栈内存指向了同一块栈内存空间,所以当bookB修改属性的时候,会直接影响bookA对象的内容。

public class one{public static void main(String[] args) {Book bookA=new Book();Book bookB=null;bookA.title="java开发";bookA.price=89.9;bookB=bookA;//表示bookB的内存将指向bookA的内存空间,最终bookA与bookB值相等bookB.price=69.9;bookA.getInfo();bookB.getInfo();}
}
public class one{public static void main(String[] args) {Book bookA=new Book();Book bookB=new Book();bookA.title="java开发";bookA.price=89.9;bookB=bookA;//表示bookB的内存将指向bookA的内存空间,最终bookA与bookB值相等bookB.price=100.01;bookA.getInfo();}
}

3.2.3封装性

用private封装(setterANDgetter)

package capterThree;class Book{private String title;private double price;public void getInfo(){System.out.println("图书名称是:"+title+"价格是:"+price);}
}
public class one{public static void main(String[] args) {Book book=new Book();book.title="java开发";book.price=89.9;book.getInfo();}
}

········································································
所有在类中定义的属性都要求使用private声明,如果属性需要被外部所使用,那么按照相对应的setter,getter方法

  • setter:public void setTitle(String t)//有参
  • getter:public String getTitle()//无参
package capterThree;class Book{private String title;public String getTitle() {return title;}public void setTitle(String title) {this.title = title;}public double getPrice() {return price;}public void setPrice(double price) {this.price = price;}private double price;public void getInfo(){System.out.println("图书名称是:"+title+"价格是:"+price);}
}
public class one{public static void main(String[] args) {Book book=new Book();book.setTitle("JAVA开发");book.setPrice(69.9);book.getInfo();}
}

3.2.4 构造方法

灵魂拷问:什么是构造方法?

构造方法本身是一种特殊的用法,他只在新对象实例化的时候调用,定义的原则是:方法名称与类名称相同,没有返回值类型声明,以进行重载

...public Book(String title,Double price){//构造调用方法setTitle(title);//调用本类方法setPrice(price);}
...public class one{public static void main(String[] args) {Book book=new Book("JAVA开发",16.9);//声明并实例化对象book.getInfo();//调用方法}
}

构造方法的重载

构造方法的核心作用
在类对象实例化时设置属性的初始化内容。

  • 属性(必须封装,同时提供getter,setter)
  • 构造方法
  • 普通方法

3.2.5 匿名对象

public class one{public static void main(String[] args) {new Book("JAVA开发",15.9).getInfo();}
}
package capterThree;class Emp{private int empno;private String ename;private String job;private double sal;private double comm;public int getEmpno() {return empno;}public void setEmpno(int empno) {this.empno = empno;}public String getEname() {return ename;}public void setEname(String ename) {this.ename = ename;}public String getJob() {return job;}public void setJob(String job) {this.job = job;}public double getSal() {return sal;}public void setSal(double sal) {this.sal = sal;}public double getComm() {return comm;}public void setComm(double comm) {this.comm = comm;}public Emp(){}public Emp(int eno, String ena, String j, int i, double s, double c){empno=eno;ename=ena;job=j;sal=s;comm=c;}public void getInfo(){System.out.println(empno+ename+job+sal+comm);}}public class one {public static void main(String[] args) {Emp e=new Emp(777,"11","12",12,12,5);e.getInfo();}}


总结:

  • 类名称必须存在意义(Book,Emp)
  • 类中所以的属性必须private封装,封装后的属性必须提供setter和getter
  • 类中可以提供任意多个构造方法,但是必须保留一个无参构造方法
  • 类中不允许出现任何输出语句,所有信息输出必须交给被调用处输出
    - 类中需要提供一个取得对象完整信息的方法,暂定为getInfo(),而且返回String类型的数据

3.2.6 数组

一维数组

数据类型 数据名称[]=new 数据类型[长度];
int data[]=new int[5];
数据类型[] 数据名称=new 数据类型[长度];
int[] data=new int[5];

a[i]是数,i从0-a.length,小心数组越界

package capterThree;public class two {public static void main(String[] args) {int a[]=new int[]{1,2,3};for(int i=0;i<a.length;i++){System.out.print(a[i]+"、");}}
}


二维数组

Core:外层循环是控制数据的行内容,内层循环是控制数据的列内容

package capterThree;public class two {public static void main(String[] args) {int a[][]=new int[][]{{1,2,3},{4,5,6},{7,8,9}};for(int i=0;i<a.length;i++){for(int j=0;j<a.length;j++){System.out.print(a[i][j]+"|");}System.out.println();}}}

数组与方法参数的传递

package capterThree;public class Three {public static void main(String[] args) {int data[]=new int[]{1,2,3};change(data);//int tempt[]=datafor(int i=0;i< data.length;i++){System.out.print(data[i]+"|");}}public static void change(int tempt[]){for(int i=0;i< tempt.length;i++){tempt[i]*=2;}}
}

数组小练习(未完待续…)

冒泡排序
package capterThree;public class Three {public static void main(String[] args) {int data[]=new int[]{1,4,5,3,8,9,5,7,3};sort(data);print(data);}public static void sort(int arr[]){for(int i=0;i<arr.length;i++){for(int j=0;j<arr.length-1;j++){if(arr[j]>arr[j+1]){int t=arr[j];arr[j]=arr[j+1];arr[j+1]=t;}}}}public static void print(int tempt[]){for(int i=0;i< tempt.length;i++){System.out.print(tempt[i]+"|");}System.out.println();}
}

待办

  • 数组的倒置

数组的操作方法

java.util.Arrays.sort(data);

package capterThree;public class Three {public static void main(String[] args) {int data[]=new int[]{7,9,5,4,3,8};java.util.Arrays.sort(data);print(data);}public static void print(int tempt[]){for(int i=0;i< tempt.length;i++){System.out.print(tempt[i]+"|");}}}


System.arraycopy(dataA,2,dataB,2,3);

package capterThree;public class Three {public static void main(String[] args) {int dataA[]=new int[]{7,9,5,4,3,8};int dataB[]=new int[]{11,22,33,44,55,66};System.arraycopy(dataA,2,dataB,2,3);print(dataB);//        java.util.Arrays.sort(data);
//        print(data);}public static void print(int tempt[]){for(int i=0;i< tempt.length;i++){System.out.print(tempt[i]+"|");}}}

对象数组

  • 对象数组的动态初始化

如果使用了动态数组的初始化,在默认情况下,数组的每一个元素都是其对应的默认值是Null

类名称 对象数组名称=new 类名称[长度];
Book books[]=new Book[3];

package capterThree;class Book{private String title;private double price;public String getTitle() {return title;}public void setTitle(String title) {this.title = title;}public double getPrice() {return price;}public void setPrice(double price) {this.price = price;}
public Book(){}public Book(String t, Double p){title=t;price=p;}
public void getInfo(){System.out.println("图书名称:"+title+"价格:"+price);
}
}
public class Four {public static void main(String[] args) {Book books[]=new Book[3];books[0]=new Book("JAVA",16.6);books[1]=new Book("C",15.5);books[2]=new Book("Python",14.4);for (int i=0;i< books.length;i++){books[i].getInfo();}}
}

  • 对象数组的静态初始化
    类名称 对象数组名称=new 类名称[实例化对象,实例化对象,...];
public class Four {public static void main(String[] args) {Book books[]=new Book[]{new Book("JAVA",12.2),new Book("JAVA",12.2),new Book("JAVA",12.2)};for (int i=0;i< books.length;i++){books[i].getInfo();}}}

3.2.7 String的基本类型操作

字符与字符串

NO. 方法名称 类型 描述
1 public String(char[] value) 构造 将部分字符数组变为String类对象
2 public String(char[] value),int offset,int count 构造 将部分字符变为String
3 public char charA(int index) 普通 返回指定索引对应的字符信息
4 public char[] toCharArray() 普通 将字符串以字符组的形式返回
package capterThree;public class Five {public static void main(String[] args) {String str="Hello";char c=str.charAt(1);System.out.println(c);}
}

package capterThree;public class Five {public static void main(String[] args) {String str="Hello";char[] c=str.toCharArray();for(int i=0;i<c.length;i++){System.out.print(c[i]+",");}}
}

package capterThree;public class Five {public static void main(String[] args) {String str="hello";char[] c=str.toCharArray();for(int i=0;i<c.length;i++){c[i]-=32;}System.out.println(new String(c));System.out.println(new String(c,1,2));}
}


Question:给定一个字符串判断其是否是数字组成

package capterThree;public class Five {public static void main(String[] args) {String str = "Hello32323";int flag=isNumber(str);
if(flag==0){System.out.println("有数字");
}elseSystem.out.println("没数字");}public static int isNumber(String tempt) {int flag=0;char[] c = tempt.toCharArray();for (int i = 0; i < c.length; i++) {if (c[i] > '0' && c[i] < '9')flag=0;elseflag=1;}return flag;}
}

字节与字符串

NO. 方法名称 类型 描述
1 public String(byte[] bytes) 构造 将全部字节数组变为字符串
2 public String(byte[] bytes,int offset,int length) 构造 将部分字节数组变为字符串
3 public String getBytes() 普通 将字符串变为字节数组
4 public String getBytes(String charsetName) throws UnsupportedEncodingException 普通 进行编码转换
package capterThree;public class Six {public static void main(String[] args) {String str="helloworld";byte[] b=str.getBytes();for(int i=0;i<b.length;i++){b[i]-=32;}System.out.println(new String(b));System.out.println(new String(b,0,5));
//        System.out.println(b,5,5);}
}

字符串的比较

NO. 方法名称 类型 描述
1 public boolean equals(String anObject) 普通 进行相等判断,区分大小
2 public boolean equalsIgnoreCase(String anotherString) 普通 进行相等判断,不区分大小
3 public int compareTo(String anotherString) 普通 判断两个字符串的大小(>0;<0;=0)
package capterThree;public class Six {public static void main(String[] args) {String stra="HELLO";String strb="Hello";System.out.println(stra.equals(strb));System.out.println(stra.equalsIgnoreCase(strb));
//        System.out.println(stra.compareTo(strb));if(stra.compareTo(strb)>0){System.out.println("大于");}else{System.out.println("小于");}}
}

package capterThree;public class Six {public static void main(String[] args) {String str="helloworld";String  stra="##@@hello**";System.out.println(str.indexOf("world"));System.out.println(str.indexOf("l"));System.out.println(str.indexOf("l",5));System.out.println(str.lastIndexOf("o"));if(str.indexOf("world")!=-1){System.out.println("查询到该数据了");}if(str.contains("hello")){System.out.println("查询到该数据了");}System.out.println(stra.startsWith("##"));System.out.println(stra.startsWith("@@",2));System.out.println(stra.endsWith("**"));}
}

字符串的替换

package capterThree;public class Six {public static void main(String[] args) {String str="helloworld";
String ra=str.replace("o","_");
String rb=str.replaceFirst("o","_");System.out.println(ra);System.out.println(rb);}
}

字符串的截取

package capterThree;public class Six {public static void main(String[] args) {String str="helloworld";
String ra=str.substring(5);
String rb=str.substring(0,5);System.out.println(ra);System.out.println(rb);}
}

字符串的拆分

package capterThree;public class Six {public static void main(String[] args) {String str="hi hello woo th yjuu";
String result[]=str.split(" ");
//String result[]=str.split(" ",4);
for (int i=0;i< result.length;i++){System.out.print(result[i]+",");
}}
}

字符串的其他操作

字符串的连接
package capterThree;public class Six {public static void main(String[] args) {String str="hi".concat(",GMX");System.out.println(str);
}
}

大小写转义
package capterThree;public class Six {public static void main(String[] args) {//String str="hi".concat(",GMX");
//        System.out.println(str);String str="(*(*Hello(*(*";System.out.println(str.toUpperCase());System.out.println(str.toLowerCase());
}
}

去掉左右空格

package capterThree;public class Six {public static void main(String[] args) {String str=" Hello world ";System.out.println(str);System.out.println(str.trim());
}
}

字符串的长度

package capterThree;public class Six {public static void main(String[] args) {String str=" Hello world ";System.out.println(str.length());
}
}

判断空字符串

package capterThree;public class Six {public static void main(String[] args) {String str="helloWorld";System.out.println(str.isEmpty());System.out.println("".isEmpty());
}
}

首字母大写

package capterThree;public class Six {public static void main(String[] args) {String str="helloWorld";System.out.println(initcap(str));
}
public static String initcap(String temp){return temp.substring(0,1).toUpperCase()+temp.substring(1);
}
}

3.2.8 this关键字

本类属性

访问类属性都要加上this,.使用this关键字明确表示访问类的属性

   public BBook(String title,double price){this.title=title;this.price=price;}

本类方法

  • this本质上指的就是明确进行本类结构的标记,而除了访问类中的属性外,也可以进行类中方法的调用
  public void print(){System.out.println("AAAA");}public void getInfo(){this.print();System.out.println("图书名称是:"+title+"价格是:"+price);}
package capterThree;class emp{private int empno;private String empname;private double salary;private String dept;public int getEmpno() {return empno;}public void setEmpno(int empno) {this.empno = empno;}public String getEmpname() {return empname;}public void setEmpname(String empname) {this.empname = empname;}public double getSalary() {return salary;}public void setSalary(double salary) {this.salary = salary;}public String getDept() {return dept;}public void setDept(String dept) {this.dept = dept;}public emp(){this(0,"无名氏",0.0,"未定");}public emp(int empno){this(empno,"临时工",800.0,"后勤部");}public emp(int empno,String empname){this(empno,empname,2000.0,"技术部");}public emp(int empno,String empname,double salary,String dept){this.empno=empno;this.empname=empname;this.salary=salary;this.dept=dept;}public String getInfo(){return "编号是:"+empno+"姓名是:"+empname+"工资是:"+salary+"部门是"+dept;}
}public class seven {public static void main(String[] args) {emp realuta=new emp();emp resultb=new emp(111);emp reaultb=new emp(222,"陆杨");emp reaultc=new emp(333,"陆杨",8000.0,"外科");System.out.println(realuta.getInfo());System.out.println(resultb.getInfo());System.out.println(reaultb.getInfo());System.out.println(reaultc.getInfo());}
}

  • 一点小BUG(与上方的String方法进行比较,自己解决吧~~~,其实依旧不太明白return之类的,唉~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~)
 public void getInfo(){System.out.println("编号是:"+empno+"姓名是:"+empname+"工资是:"+salary+"部门是"+dept);}realuta.getInfo();reaultb.getInfo();reaultc.getInfo();resultb.getInfo();

当前对象

3.2.9 引用传递

package capterThree;class Message{private int num=10;public  Message(int num){this.num=num;}public int getNum() {return num;}public void setNum(int num) {this.num = num;}
}public class eight {public static void main(String[] args) {Message msg=new Message(20);fun(msg);System.out.println(msg.getNum());}public static void fun(Message tempt){//这里是message四要与Message类进行连接tempt.setNum(100);}
}


字符串的传递

基本数据类型传递就是值传递,将String也看做是值传递就能够解决问题

package capterThree;class Message{String str="hello";
public Message(String str){this.str=str;
}public String getStr() {return str;}public void setStr(String str) {this.str = str;}
}public class eight {public static void main(String[] args) {Message msg=new Message("HII");fun(msg);System.out.println(msg.getStr());}public static void fun(Message tempt){tempt.setStr("HOOOOOOOOOOOOO");}
}
实例
package capterThree;class Member{private int mid;private String name;private Car car;public int getMid() {return mid;}public void setMid(int mid) {this.mid = mid;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Car getCar() {return car;}public void setCar(Car car) {this.car = car;}public Member(){}public Member(int mid,String name){this.mid=mid;this.name=name;}public void getInfo(){System.out.println("人员编号是:"+mid+"姓名是:"+name);}
}
class Car{private Member member;private String pname;public Member getMember() {return member;}public void setMember(Member member) {this.member = member;}public String getPname() {return pname;}public void setPname(String pname) {this.pname = pname;}public Car(){}public Car(String pname){this.pname=pname;}public void getInfo(){System.out.println("车的名字是:"+pname);}
}
public class nine {public static void main(String[] args) {Member a=new Member(1,"张杰");Car c=new Car("宝马");a.setCar(c);c.setMember(a);a.getCar().getInfo();c.getMember().getInfo();}
}

  • 代码优化+child
package capterThree;class Member{private int mid;private String name;private Car car;private Member child;public Member getChild() {return child;}public void setChild(Member child) {this.child = child;}public int getMid() {return mid;}public void setMid(int mid) {this.mid = mid;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Car getCar() {return car;}public void setCar(Car car) {this.car = car;}public Member(){}public Member(int mid,String name){this.mid=mid;this.name=name;}public void getInfo(){System.out.println("人员编号是:"+mid+"姓名是:"+name);}
}
class Car{private Member member;private String pname;public Member getMember() {return member;}public void setMember(Member member) {this.member = member;}public String getPname() {return pname;}public void setPname(String pname) {this.pname = pname;}public Car(){}public Car(String pname){this.pname=pname;}public void getInfo(){System.out.println("车的名字是:"+pname);}
}
public class nine {public static void main(String[] args) {Member m=new Member(1,"张杰");Member cnd=new Member(2,"李闯");Car c=new Car("宝马");Car cc=new Car("奔驰");m.setCar(c);c.setMember(m);cnd.setCar(cc);cc.setMember(cnd);m.setChild(cnd);m.getCar().getInfo();c.getMember().getInfo();m.getChild().getInfo();m.getChild().getCar().getInfo();}
}

3.2.10 数据表与简单的java映射

雇佣关系
package capterThree;
class employee{private int empno;private String ename;private String job;private double sal;private double comm;private employee mgr;private Dept dept;public employee(){}
public employee(int empno,String ename,String job,double sal,double comm){this.empno=empno;this.ename=ename;this.job=job;this.sal=sal;this.comm=comm;
}
public void getInfo(){System.out.println("雇员编号:"+empno+"姓名"+ename+"工作:"+job+"工资"+sal+"佣金"+comm);
}public int getEmpno() {return empno;}public void setEmpno(int empno) {this.empno = empno;}public String getEname() {return ename;}public void setEname(String ename) {this.ename = ename;}public String getJob() {return job;}public void setJob(String job) {this.job = job;}public double getSal() {return sal;}public void setSal(double sal) {this.sal = sal;}public double getComm() {return comm;}public void setComm(double comm) {this.comm = comm;}public employee getMgr() {return mgr;}public void setMgr(employee mgr) {this.mgr = mgr;}public Dept getDept() {return dept;}public void setDept(Dept dept) {this.dept = dept;}
}
class Dept{private int deptno;private String dname;private String loc;private employee emps[];public Dept(){}
public Dept(int deptno,String dname,String loc){this.deptno=deptno;this.dname=dname;this.loc=loc;
}
public void getInfo(){System.out.println("部门编号:"+deptno+"名称"+dname+"位置"+loc);
}public int getDeptno() {return deptno;}public void setDeptno(int deptno) {this.deptno = deptno;}public String getDname() {return dname;}public void setDname(String dname) {this.dname = dname;}public String getLoc() {return loc;}public void setLoc(String loc) {this.loc = loc;}public employee[] getEmps() {return emps;}public void setEmps(employee[] emps) {this.emps = emps;}
}
public class ten {public static void main(String[] args) {Dept dept=new Dept(10,"生产","纽约");employee ea=new employee(001,"李美","服务员",2000.0,22.4);employee eb=new employee(002,"李梅","收银员",2400.0,25.7);employee ec=new employee(003,"MEIZU","经理",5000.0,100.4);ea.setMgr(eb);eb.setMgr(ec);ea.setDept(dept);eb.setDept(dept);ec.setDept(dept);// private Emp emps[];dept.setEmps(new employee[]{ea,eb,ec});ea.getInfo();ea.getMgr().getInfo();ea.getDept().getInfo();dept.getInfo();for (int i=0;i<dept.getEmps().length;i++){if(dept.getEmps()[i].getMgr()!=null){dept.getEmps()[i].getMgr().getInfo();}}}
}

城市与省份的关系
class Province{private int pid;private String name;private city cities[];public int getPid() {return pid;}public city[] getCities() {return cities;}public void setCities(city[] cities) {this.cities = cities;}public void setPid(int pid) {this.pid = pid;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Province(int pid, String name){this.pid=pid;this.name=name;}public void getInfo(){System.out.println("省份编号:"+this.pid+"名称"+this.name);}
}
class city{private int cid;private String name;private Province province;public Province getProvince() {return province;}public void setProvince(Province province) {this.province = province;}public int getCid() {return cid;}public void setCid(int cid) {this.cid = cid;}public String getName() {return name;}public void setName(String name) {this.name = name;}public city(){}public city(int cid, String name){this.cid=cid;this.name=name;}public void getInfo(){System.out.println("城市编号:"+this.cid+"城市名称"+this.name);}}
public class eleven {public static void main(String[] args) {//按照两部完成//第一步设置数据,第二不则是根据结构取出数据//1.先准备好独立的对象Province pro=new Province(1,"北京");city c1=new city(1001,"唐山");city c2=new city(1002,"秦皇岛");city c3=new city(1003,"石家庄");//2,设置关系c1.setProvince(pro);c2.setProvince(pro);c3.setProvince(pro);
//        city c[]=new city[]{c1,c2,c3};pro.setCities(new city[]{c1,c2,c3});c2.getProvince().getInfo();for (int i=0;i<pro.getCities().length;i++){pro.getCities()[i].getInfo();}}
}

3.2.11 对象比较

package capterThree;class BBook{private String title;public String getTitle() {return title;}public void setTitle(String title) {this.title = title;}public double getPrice() {return price;}public void setPrice(double price) {this.price = price;}private double price;public BBook(String title,double price){this.title=title;this.price=price;}public void getInfo(){System.out.println("图书名称是:"+title+"价格是:"+price);}
}
public class Six{public static void main(String[] args) {BBook booka=new BBook("Java开发",16.9);BBook bookb=new BBook("Java开发",16.9);if(booka.getTitle().equals(bookb.getTitle())&&booka.getPrice()==bookb.getPrice()){System.out.println("是同一个对象");}else {System.out.println("不是同一个对象");}}
}

3.2.12 static关键字

一个类的主要组成部分就是属性和方法(分别为构造方法和普通方法),而每一个对象都分别拥有各自的属性内容(不同对象的属性保存在不同的堆内存中),如果类中的某个属性希望定义为公共属性(所有对象都可以使用的属性),则可以在声明前加上关键字static

  • 可以看出pub的值都改了
  • 公共属性,有任何一个对象修改了此属性的内容,都会有影响
名称 用法
栈内存空间 保存所有的对象名称(更准确的说法是保存引用的堆内存空间的地址)
堆内存空间 保存每个对象的具体属性内容
全局数据区 保存static类型的属性
全局代码区 保存所有的方法定义
package capterThree;class BBook{private String title;static String pub="清华大学出版社";public String getTitle() {return title;}public void setTitle(String title) {this.title = title;}public double getPrice() {return price;}public void setPrice(double price) {this.price = price;}private double price;public BBook(String title,double price){this.title=title;this.price=price;}public static String getPub() {return pub;}public static void setPub(String pub) {BBook.pub = pub;}public void getInfo(){System.out.println("图书名称是:"+title+"价格是:"+price+"出版社是:"+pub);}
}
public class Six{public static void main(String[] args) {BBook booka=new BBook("Java开发",16.9);BBook bookb=new BBook("Android开发",16.9);booka.pub="北京大学出版社";booka.getInfo();bookb.getInfo();}
}

static和非static的区别:
所有的非static属性都需要实例化对象才可以访问,但是static属性不受实例化对象的控制
一般在共享属性的时候回使用static关键字,出现的频率并不是特别高

public class Six{public static void main(String[] args) {BBook booka=new BBook("Java开发",16.9);BBook bookb=new BBook("Android开发",16.9);BBook.pub="dsadada";booka.getInfo();}
}

Static定义方法

-private进行封装后BBook.pub = "dsadada"就不可用了变为BBook.setPub("dsadada");

   private static String pub="清华大学出版社";public static String getPub() {return pub;}public static void setPub(String pub) {BBook.pub = pub;}BBook.setPub("dsadada");

总结:static定义的方法和属性都不受实例化对象的控制,也就是说都属于独立类的功能,但是这个时候会出现一个特别麻烦的问题,此时类中的方法就变为了static和非static两种,这两组方法之间的调用也将受到如下的控制

  • static()方法不能直接访问非static属性或方法,只能嗲用static属性或方法
  • 所有的static定义的结构,不受实例化对象的控制,即可以在没有实例化对象的时候访问

Static主方法
不需要实例化对象

package capterThree;public class thieteen {public static void main(String[] args) {fun();}public static void fun(){System.out.println("你好");}
}

需要实例化对象

package capterThree;public class thieteen {public static void main(String[] args) {//        fun();new thieteen().fun();}public  void fun(){System.out.println("你好");}
}

3.2.13代码块

3.2.14内部类

Capter 4 面对对象高级知识

4.1继承性

4.1.1 继承的实现

继承性严格来说就是指扩充一个类已有的功能

class 子类 extends 父类{}

继承的格式说明

  • 对于extends而言,应该翻译为扩充,但是为了理解方便,统一将其称为继承
  • 子类又被称为派生类
  • 父类又被称为超类(super class)

继承父类

package capterThree;
class Person{private int age;private String 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;}}
class studens extends Person{//具体的操作方法public void studens(){System.out.println();}}
public class fourtenn {public static void main(String[] args) {studens stu=new studens();stu.setAge(19);stu.setName("张三");System.out.println("姓名:"+stu.getName()+"年龄:"+stu.getAge());}
}


子类扩充

package capterThree;
class Person{private int age;private String 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;}}
class studens extends Person{//具体的操作方法private String schoolName;public String getSchoolName() {return schoolName;}public void setSchoolName(String schoolName) {this.schoolName = schoolName;}
}
public class fourtenn {public static void main(String[] args) {studens stu=new studens();stu.setAge(19);stu.setName("张三");stu.setSchoolName("向阳高中");System.out.println("姓名:"+stu.getName()+"年龄:"+stu.getAge()+"学校名称:"+stu.getSchoolName());}
}

4.1.2 继承的限制

  1. .JAVA不允许多重继承,但是允许多层继承,继承层数不要过多

多重继承

class A{}
class B{}
class C extends A,B{}

多层继承

class A{}
class B extends A{}
class C extends B{}
  1. 子类在继承父类的时候,严格来讲会继承父类的全部操作,但是对于所有的私有操作属于隐式继承,而所有的非私有操作属于显示继承
package capterThree;class A{private String msg;public String getMsg() {return msg;}public void setMsg(String msg) {this.msg = msg;}
}
class B extends A{}
public class Fifteen {public static void main(String[] args) {B one=new B();one.setMsg("hhh");System.out.println(one.getMsg());}
}

B类中一定存在msg属性,但是此属性是通过父类继承而来的,但是在B类里面不能针对msg属性进行直接访问,因为他在A类中属于私有声明,只能利用getter/setter方法进行属性的访问

  1. 在子类对象构造前一定会默认调用父类的构造(默认使用无参构造),以保证父类的对象先实例化,子类对象后实例化
package capterThree;class AA{public AA(){//无参构造方法System.out.println("我是A");}
}
class BB extends AA{public BB(){System.out.println("我是B");}
}
public class sixteen {public static void main(String[] args) {new BB();}
}


等价于

class BB extends AA{public BB(){super();System.out.println("我是B");}
}

父类提供无参构造函数的时候,写不写super()都是可以的,但是如果父类中没有无参构造函数,则必须明确的使用super()调用父类直嘀咕的参数的构造方法

package capterThree;class AA{public AA(String title){//无参构造方法System.out.println("我是A,title="+title);}
}
class BB extends AA{public BB(String title){super(title);System.out.println("我是B");}
}
public class sixteen {public static void main(String[] args) {new BB("Hello");}
}

如果一个类中有多个构造方法之间使用this()互相调用,那么至少要保留一个构造方法作为出口,而这个出口一定会去调用父类构造,这也解释了为什么一个简单的JAVA类一定要保留一个无参构造方法

4.2 覆写

4.2.1方法的覆写

子类定义属性或者方法的时候,有可能出现 定义的属性或方法与父类同的情况

Before:

package capterThree;class AA{public void fun(){System.out.println("AA");}
}
class BB extends AA{}
public class sixteen {public static void main(String[] args) {BB b=new BB();b.fun();}
}


After:

package capterThree;class AA{void fun(){System.out.println("AA");}
}
class BB extends AA{public void fun(){System.out.println("BB");
}
}
public class sixteen {public static void main(String[] args) {BB b=new BB();b.fun();}
}


True:

class AA{void fun(){System.out.println("AA");}
}
class BB extends AA{public void fun(){System.out.println("BB");
}
}

False:

class AA{public void fun(){System.out.println("AA");}
}
class BB extends AA{void fun(){System.out.println("BB");
}
}
重载与覆写的区别:

NO. 区别 重载 覆写
1 英文单词 Overloading Override
2 发生范围 发生在一个类里面 发生在继承关系中
3 定义 方法名称相同,参数的类型及个数不同 方法名称相同,参数的类型,个数相同,方法返回值相同
4 权限 没有权限的限制 被覆写的方法不能拥有比父类更为严格的访问控制权限

4.2.2 属性的覆盖

super.属性:调用父类的指定属性

package capterThree;
class AAA{String info="HHHHHHH";}
class BBB extends AAA{int info=100;public void print(){System.out.println(super.info);System.out.println(this.info);}
}public class seventeen {public static void main(String[] args) {BBB b=new BBB();b.print();}
}

this和super的区别:
NO. 区别 this super
1 功能 调用本类构造,本类方法,本类属性 子类调用父类构造,父类方法,父类属性
2 形式 先查找本类中是否存在有指定的调用结构,如果有则直接调用,如果没有调用父类定义 不查找子类,直接调用父类
3 特殊 表示本类的当前对象

4.3 继承案例(未完待续…)

package capterThree;
class Array{private int data[];//定义数组操作类private int foot;public  Array(int len){if(len>0){this.data=new int[len];}else {this.data=new int[1];}}public boolean add(int num){if(this.foot<this.data.length){this.data[this.foot++]=num;return true;}return false;}public int[] getData(){return this.data;}
}public class eighteen {public static void main(String[] args) {Array arr=new Array(3);System.out.print(arr.add(20)+",");System.out.print(arr.add(30)+",");System.out.print(arr.add(40)+",");System.out.print(arr.add(100)+",");System.out.println();int[] tempt=arr.getData();for (int i=0;i< tempt.length;i++){System.out.print(tempt[i]+",");}}}

4.4 final关键字

在Java中final被称为终结器,即:任何子类都不能继承final声明的父类

final class A{}
class B extends A{}

使用final定义的方法不能被子类所覆写

用final定义好的变量就成为了常量,不可以更改值

4.5多态性

  • 方法的多态性:复载与重写
    • 重载:同一个方法名称,根据不同的参数类型及个数可以完成不同的功能
    • 覆写:同一个方法,根据实例化的子类多想不同,所完成的功能也不同
  • 对象的多态性:父子类对象的转换
    – 向上转型:子类对象变成父类对象,格式:父类 子类对象=子类实例,自动转换
    – 向下转型:父类对象变成子类对象,格式:子类 子类对象=(子类)父类实例,强制转换
package capterThree;class AAAA{public void print(){System.out.println("你好A");}
}
class BBBB extends AAAA{public void print(){System.out.println("你好B");}
}
public class sevent {public static void main(String[] args) {BBBB b = new BBBB();//实例化的是子类对象b.print();}
}
public class sevent {public static void main(String[] args) {AAAA a = new BBBB();//实例化的是子类对象,向上转型a.print();}
}

向下转型是有前提条件的:必须向上发生转型才可以发生向下转型

public class sevent {public static void main(String[] args) {AAAA a = new BBBB();//实例化的是子类对象,向上转型BBBB b=(BBBB)a;//对象需要强制的向下转型b.print();//调用被子类所覆写的方法}
}

4.6抽象类

abstract  class AAAA{public void fun(){System.out.println("你好A");}public abstract void print();
}

使用抽象类的原则

  1. 抽象类必须有子类,即每一个抽象类一定要被子类继承(使用extends关键字),但是在JAVA中每一个子类只能继承一个抽象类,所以具备单继承局限
  2. 抽象类的子类(子类不是抽象类)必须覆写抽象类中的全部抽象方法(强制子类覆写)
  3. 依靠对象的向上转型的特点,可以通过抽象类的子类完成抽象类的实例化对象操作
package capterThree;abstract  class AAAA{public void fun(){System.out.println("你好A");}public abstract void print();}
class BBBB extends AAAA{public void print(){System.out.println("你好B");}}
public class sevent {public static void main(String[] args) {AAAA a = new BBBB();//实例化的是子类对象,向上转型a.print();//调用被子类所覆写的方法}
}

抽象类的限制

  1. 抽象类里面由于会存在一些属性,那么在抽象类中一定会存在构造方法,目的是为属性初始化,并且子类对象实例化时依旧满足先执行父类构造再调用子类构造的情况
  2. 抽象类不能使用final定义,因为抽象类必须与子类,而final定义的类不能有子类
    3.抽象类中可以没有任何抽象方法,但是只要是抽象类,就不能直接使用关键字new进行实例化
package capterThree;abstract class Action{public static final int EAT=1;public static final int SLEEP=5;public static final int WORK=7;public void command(int flag){switch (flag){case EAT:this.eat();break;case SLEEP:this.sleep();break;case  WORK:this.work();break;}}public abstract void eat();public abstract void sleep();public abstract void work();
}
class Human extends Action{public void eat(){System.out.println("人补充能量");}public void sleep(){System.out.println("人在睡觉");}public void work(){System.out.println("人正在工作");}
}
class Pig extends Action{public void eat(){System.out.println("猪补充能量");}public void sleep(){System.out.println("猪在睡觉");}public void work(){}
}
class Robot extends Action{public void eat(){System.out.println("机器人补充能量");}public void sleep(){}public void work(){System.out.println("机器人正在工作");}}
public class eightt {public static void main(String[] args) {fun(new Robot());fun(new Pig());fun(new Human());}public static void fun(Action act){act.command(Action.EAT);act.command(Action.SLEEP);act.command(Action.WORK);}
}

4.7接口

前:利用抽象类可以实现对子类覆写的功能,但是抽象类的子类存在宇哥很大的问题–单继承局限,为了打破这一局限,就需要JAVA接口来解决

接口的定义
如果一个类只是由抽象方法和全局常量组成,那么在这种情况下不会将其定义成一个抽象类, 而只会将其定义成接口

interface A{public static final String MSG="YOOI";public abstract void print();
}

简化写法
为了准确定义,强烈建议在接口蒂尼方法时一定要加上public

  public void print();

interface A{public static final String MSG="YOOI";public void print();
}

接口的使用原则

  1. 接口必须要有子类,但是此时一个子类可以使用implemets关键字实现多接口,避免单继承原则
  2. 接口的子类(如果不是抽象类),必须要覆写接口中的全部抽象方法
  3. 接口的对象可以利用子类对象的向上转型进行实例化操作
package capterThree;import org.omg.CORBA.PUBLIC_MEMBER;interface W{public static final String MSG="YOOI";public void print();
}
interface Q{public abstract void  get();
}
class X implements W,Q{public void print(){System.out.println("W接口的方法");}public void get(){System.out.println("B接口的方法");}
}
public class ninet {public static void main(String[] args) {X x=new X();W w=x;Q q=x;w.print();q.get();System.out.println(W.MSG);}
}

package capterThree;
interface USB{public  void start();public void close();
}
class Computer{public void plugin(USB usb){usb.start();usb.close();}
}
class Flash implements  USB{public void start(){System.out.println("U盘开始使用");}public void close(){System.out.println("U盘弹出");}
}
class Print implements USB{public void start(){System.out.println("打印机开始使用");}public void close(){System.out.println("打印机停止工作");}
}
public class twent {public static void main(String[] args) {Computer com=new Computer();com.plugin(new Flash());com.plugin(new Print());}
}


接口的应用–工厂设计模式

package capterThree;
class Factory{public static Fruit getInstance(String className){if("apple".equals(className)){return new Apple();}else if("orange".equals(className)){return new Orange();}else return null;}}interface  Fruit{public void eat();
}
class Apple implements  Fruit{public void eat(){System.out.println("***吃苹果");}
}
class Orange implements Fruit{public void eat(){System.out.println("***吃橘子");}
}
public class to {public static void main(String[] args) {// Fruit f=new Apple();子类实例化父类的对象Fruit f=Factory.getInstance("orange");f.eat();}
}


接口的应用–代理设计模式

package capterThree;
interface Network{public void browse();
}
class Real implements Network{public void browse(){System.out.println("上网浏览信息");}
}
class Proxy implements  Network{private Network network;public Proxy(Network network){this.network=network;}public void check(){}public void browse(){this.check();this.network.browse();}
}public class tt {public static void main(String[] args) {Network net=null;net=new Proxy(new Real());net.browse();}
}

抽象类和接口的区别
NO. 区别 抽象类 接口
1 关键字 abstract interface
2 组成 构造方法,普通方法,抽象方法,static方法,常量,变量 抽象方法,全局常量
3 子类使用 class 子类 extends 抽象类 class 子类 imples 接口,接口,接口…
4 关系 抽象类可以实现多个接口 接口不能继承抽象类,却可以继承多个父接口
5 权限 可以使用各种权限 只能使用public权限
6 限制 单继承局限 没有单继承局限

相同点:

7 子类 抽象类和接口必须有子类,子类必须要覆写全部的抽象方法
8 实例化对象 依靠子类对象的向上转型进行对象的实例化

为了更好的说明集中关系,下面有一个简短的分析
现在要定义一个动物,动物拥有公共标准即哺乳动物,卵生动物,这种方是接口的继承关系
哺乳动物又可以划分为人,狗,猫,因为由于不表示具体的事务标准,因此可以使用抽象类来进行表示
如果想要表示出工人或者是学生的概念,肯定是一个具体的定义,因此需要使用的方式
在所有的设计中,接口是最先被设计出来的,因此接口的设计很重要

4.8Object类

Object类是所有类的父亲

package capterThree;
class Bnook{private String title;private double price;public Bnook(String title,double price){this.title=title;this.price=price;}public String getTitle() {return title;}public void setTitle(String title) {this.title = title;}public double getPrice() {return price;}public void setPrice(double price) {this.price = price;}public String toString(){return "书名:"+this.title+"价格:"+this.price;}
}public class tf {public static void main(String[] args) {Bnook b=new Bnook("JAVA开发",18.9);// b.toString();System.out.println(b);}
}

package capterThree;
class Bnook {private String title;private double price;public Bnook(String title, double price) {this.title = title;this.price = price;}public String getTitle() {return title;}public void setTitle(String title) {this.title = title;}public double getPrice() {return price;}public void setPrice(double price) {this.price = price;}public boolean equals(Object obj) {if (this == obj) {return true;}if (obj == null) {return false;}if (!(obj instanceof Bnook)) {return false;}Bnook book = (Bnook) obj;if (this.title.equals(book.title) && this.price == book.price) {return true;}return false;}public String toString(){return "书籍名称:"+this.title+"书籍价格:"+this.price;}
}public class tf {public static void main(String[] args) {Bnook b=new Bnook("JAVA开发",18.9);Bnook c=new Bnook("JAVA开发",18.9);System.out.println(b.equals(c));}
}

Capter 5 包

5.1包的定义

  • 在Java程序中包主要用于将不同功能的文件进行切割
  • 所谓的包实际上指的是文件夹
  • 在Java中使用package关键字来定义包,此语句必须卸载*.java的首行

5.2包的导入

package com.yootk.util;
public class Message{public void print(){sytem.out.println("hello world");
}
}
package com.yootk.util;
import com.yootk.util.Message
public class TestMessage{Message msg=new Message();
msg.print()
}
}

5.3系统常见包

NO. 包名称 作用
1 java.lang 基本的包,像String这样的类就保存在此包中,在JDK 1.0事如果想编写程序,则必须手工导入此包,但是随后的JDK版本解决了该问题,所以此包现在为自动导入
2 java.lang.reflect 反射机制的包,是java.lang 的子包,在java反射机智中将会为读者介绍
3 java.util 工具包,一些常用的库类,日期操作等在此包中
4 java.text 提供了一些文本的处理类库
5 java.sql 数据库操作包,提供了各种数据库操作的类和接口
6 java.net 完成网络编程
7 java.io 输入,输出及文件处理操作处理
8 java.awt 包含构成抽象窗口工具集(abstract window toolkits)的多个类,这些类被用来构建和管理应用程序的图形用户界面(GUI)
9 javax.swing 用于建立图形用户界面,此包的组件相对于java.awt包而言是轻量级组件
10 java.applett 小应用程序开发包

5.4 jar命令

使用jar命令针对*,class文件进行压缩

  • -c:创建一个新的文件
  • -v:生成标准的压缩信息
  • -f:由用户自己制定一个*.jar的文件名称

5.4 访问控制权限

NO. 范围 private default protected public
1 在同一包的同一类
2 同一包的不同类
3 不同包的子类
4 不同包的非子类

理解:private只能在一个类中访问,default只能在一个包中访问,protected 在不同包的子类,public在不同包的非子类

5.4 命名规范

  • 类名称:每一个单词的首字母大写:TestDemo
  • 变量名称:每一个单词的首字母小写,之后每隔单词的首字母大写:studentClass
  • 方法名称:每一个单词的首字母小写,之后每一个单词的首字母大写:getInfo()
  • 包名称:所有字母小姐,例如:cn.mldnjava.util

Capter 6 异常地捕捉及处理

Capter 6 Eclipse的使用

Capter 8 Java新特性

8.1可变参数

package capterThree;public class tx {public static void main(String[] args) {System.out.println(add(1,2,3));System.out.println(add(12,13,14,15));}public static int add(int...data){int sum=0;for(int i=0;i< data.length;i++){sum+= data[i];}return sum;}
}

8.2 foreach循环

public class tx {public static void main(String[] args) {int[] data=new int[]{1,3,4,6,8,13};for (int x:data) {System.out.print(x+".");}}}

83 静态导入

如果某个类中定义的方法全部都属于static型的方法,那么其他类型要引用此类时则必须先使用Import导入所需要的包,在使用条件‘类名称.方法()调用’

package capterThree;
import capterThree.MyMath;class MyMath{public static int add(int x,int y){return x+y;}public static int div(int x,int y){return x/y;}
}public class tx {public static void main(String[] args) {System.out.println("加法操作:"+MyMath.add(2,4));System.out.println("除法操作:"+MyMath.add(6,3));}}

package capterThree;
import static capterThree.MyMath.*;class MyMath{public static int add(int x,int y){return x+y;}public static int div(int x,int y){return x/y;}
}public class tx {public static void main(String[] args) {System.out.println("加法操作:"+add(2,4));System.out.println("除法操作:"+div(6,3));}}

Capter 9 多线程

参考只上一个发布内容

Capter 10 Java常用库类(未完待续)

10.1 StringBuffer

10.2 RinTime类

10.3 System类

10.4 对象克隆

Capter 11 Java IO编程

如果文件存在则删除文件,如果文件不存在,则创建该文件

文件操作类File

创建文件

package IO;import java.io.File;
import java.io.IOException;public class two {public static void main(String[] args) throws IOException {File file=new File("d://test.txt");if(file.exists()){file.delete();}else{System.out.println(file.createNewFile());}}
}
  • 在实际的开发中,如果要定义File类对象往往会使用如下形式的操作代码

File file=new File(“d:”+File.separator+“test.txt”)//设置文件路径

-createNewFile() mkdirs():创建多级目录

创建带路径的文件

package IO;import java.io.File;
import java.io.IOException;public class one {public static void main(String[] args) throws IOException {File file=new File("d:"+File.separator+"demo"+File.separator+"hello"+File.separator+"yook"+File.separator+"test.text");if(!file.getParentFile().exists()){file.getParentFile().mkdirs();}else {System.out.println(file.createNewFile());}}
}

取得文件或目录的信息

package IO;import java.io.File;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;public class three {public static void main(String[] args) {File file=new File("d:"+File.separator+"my.jpg");if(file.exists()){System.out.println("是否是文件:"+(file.isFile()));System.out.println("是否是目录:"+(file.isDirectory()));System.out.println("文件大小:"+(new BigDecimal((double)file.length()/1024/1024).divide(new BigDecimal(1),2,BigDecimal.ROUND_HALF_UP))+"M");System.out.println("上次修改的时间是:"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(file.lastModified())));}}
}

列出目录信息–listFiles

package IO;import java.io.File;public class four {public static void main(String[] args) {File file=new File("d:"+File.separator);if(file.isDirectory()){File result[]=file.listFiles();for (int i = 0; i < result.length; i++) {System.out.println(result[i]);}}}
}

利用递归列出目录结构-- print(result[i]);//递归调用

package IO;import java.io.File;public class five {public static void main(String[] args) {File file=new File("d:"+File.separator);print(file);}public static void print(File file){if (file.isDirectory()){File result[]=file.listFiles();if(result!=null){for (int i = 0; i < result.length; i++) {//                    System.out.println(result[i]);print(result[i]);//递归调用}}}System.out.println(file);}
}

字节流与字符流

流:输入流,输出流

  • 字节流(JDK 1.0):InputStream(输入字节流),OutputStream(输出字节流)
  • 字符流(JDK 1.1):Reader(输入字节流),Writer(输出字节流)

流的基本操作形式

  • 第一步:通过File类定义一个要操作文件的路径
  • 第二步:通字节流或字符流的子类对象为父类对象实例化
  • 第三步:进行数据的读(输入),写(输出)操作
  • ☆☆☆第四步:数据流属于资源操作,资源操作必须关闭
    不管何种情况,只要是资源操作(例如:网络,文件,数据库的操作都属于资源操作),必须要关闭连接

字节输出流:OutputStream

NO. 方法 类型 描述
1 public void close() throws IOException 普通 关闭字节输出流
2 public void flush() throws IOException 普通 强制刷新
3 public abstract void write(int b )throws IOException 普通 输出单个字节
4 public void write(byte[] b )throws IOException 普通 输出全部字节数组数据
5 public void write(byte[] b,int off,int len )throws IOException 普通 输出部分字节数组数据
  • Closeable 接口
    public interface Closeable extends AutoCloseable{ public void close() throws Exception }
  • Flushable 接口
    public interface Flushable { public void flush() throws Exception }
package IO;class Net implements AutoCloseable{@Overridepublic void close() throws Exception {System.out.println("*** 网络资源关闭,释放资源");}public void info() throws Exception {System.out.println("*** 欢迎访问:www.yootk.com");}
}
public class six {public static void main(String[] args) {try(Net n=new Net()) {n.info();} catch (Exception e) {e.printStackTrace();}}
}

文件内容的输出

package IO;import java.io.*;public class seven {public static void main(String[] args) throws IOException {File file=new File("d:"+File.separator+"demo"+File.separator+"mldn.txt");if(!file.getParentFile().exists()){//文件目录不存在file.getParentFile().mkdirs();//创建目录//应该使用OutputStream和其子类进行对象的实例化,此时目录存在,文件还不存在OutputStream output=new FileOutputStream(file);String str="更多资源请访问:www.baidu.com";byte[] data=str.getBytes();//将字符串变为字节数组output.write(data);//输出内容output.close();}}
}

字节输入流:InputStream

NO. 方法 类型 描述
1 public void close() throws IOException 普通 关闭字节输出流
2 public abstract int read() throws IOException 普通 读取单个字节
3 public int read(byte[] b )throws IOException 普通 将数据读取到字节数组中,同时返回读取长度
4 public int read(byte[] b,int off,int len) throws IOException 普通 将数据读取到部分字节数组中,同时返回读取的数据长度

java.Io.InputStream是一个抽象类,所以如果想要进行文件的读取,需要使用FileInputStream子类,构造方法是:

  • public FileInputStream(File file)throws FileNotFoundException
  • 所有的子类要向父类进行转型
package IO;import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;public class eight {public static void main(String[] args) throws IOException {File file=new File("d:"+File.separator+"demo"+File.separator+"mldn.txt");if(file.exists()){InputStream input=new FileInputStream(file);byte data[]=new byte[1024];int len=input.read(data);input.close();System.out.println("["+new String(data,0,len)+"]");}}
}

输入流与输出流的部分总结:

首先在main中 File file=new File,不同的是输出流的是if(!file.getParentFile().exists()),则创建目录file.getParentFile().mkdirs();而输入流则是 if(file.exists()),接着输入流和输出流别无二致,都需要进行向上转型的操作OutputStream output=new FileOutputStream(file); InputStream input=new FileInputStream(file);输出流操作是:
String str=“更多资源请访问:www.baidu.com”;
byte[] data=str.getBytes();//将字符串变为字节数组
output.write(data);//输出内容
output.close();
输入流的操作则是:
byte data[]=new byte[1024];
int len=input.read(data);
input.close();
System.out.println("["+new String(data,0,len)+"]");

Java笔记--基础篇相关推荐

  1. 01 - Java并发编程与高并发解决方案笔记-基础篇

    01 - Java并发编程与高并发解决方案笔记-基础篇 基础篇很重要!很重要!很重要!!!一定要理解和认真思考. 01 - Java并发编程与高并发解决方案笔记-基础篇 1.课程准备 2.并发编程基础 ...

  2. Google Map 开发笔记——基础篇(Javascript )

    Google Map 开发笔记--基础篇 说明: 一.使用入门: 1.在您需要显示地图的 html 页面嵌入这段 script 2.地图 DOM 元素 3.初始化地图 二.地图画点.线.面 1.标记( ...

  3. MySQL学习笔记-基础篇1

    MySQL 学习笔记–基础篇1 目录 MySQL 学习笔记--基础篇1 1. 数据库概述与MySQL安装 1.1 数据库概述 1.1.1 为什么要使用数据库 1.2 数据库与数据库管理系统 1.2.1 ...

  4. Redis学习笔记①基础篇_Redis快速入门

    若文章内容或图片失效,请留言反馈.部分素材来自网络,若不小心影响到您的利益,请联系博主删除. 资料链接:https://pan.baidu.com/s/1189u6u4icQYHg_9_7ovWmA( ...

  5. MySQL学习笔记-基础篇2

    MySQL学习笔记-基础篇2 目录 MySQL学习笔记-基础篇2 8.子查询 8.1 需求分析与问题解决 8.1.1 实际问题 8.1.2 子查询的基本使用 8.1.3 子查询的分类 8.2 单行子查 ...

  6. 7.3 TensorFlow笔记(基础篇):加载数据之从队列中读取

    前言 整体步骤 在TensorFlow中进行模型训练时,在官网给出的三种读取方式,中最好的文件读取方式就是将利用队列进行文件读取,而且步骤有两步: 1. 把样本数据写入TFRecords二进制文件 2 ...

  7. 7.1 TensorFlow笔记(基础篇):加载数据之预加载数据与填充数据

    TensorFlow加载数据 TensorFlow官方共给出三种加载数据的方式: 1. 预加载数据 2. 填充数据 预加载数据的缺点: 将数据直接嵌在数据流图中,当训练数据较大时,很消耗内存.填充的方 ...

  8. 7.2 TensorFlow笔记(基础篇): 生成TFRecords文件

    前言 在TensorFlow中进行模型训练时,在官网给出的三种读取方式,中最好的文件读取方式就是将利用队列进行文件读取,而且步骤有两步: 1. 把样本数据写入TFRecords二进制文件 2. 从队列 ...

  9. java实现linkstring,【JAVA SE基础篇】32.String类入门

    [JAVA SE基础篇]32.String类入门 1.字符串 1.String类又称作不可变字符序列 2.String位于java.lang包中,java程序默认导入java.lang包下所有的类 3 ...

最新文章

  1. 用C#实现基于TCP协议的网络通讯
  2. linux子系统gdp调试,Linux系统中GDB功能汇总
  3. 访问Mysql数据库,连接字符串配置
  4. 如何保证 Serverless 业务部署更新的一致性?
  5. window安装swagger editor
  6. bat文件设置dns服务器,.bat文件设置IP、DNS
  7. PowerDesigner15在win7-64位系统下对MySQL 进行反向工程以及建立物理模型产生SQL语句步骤图文傻瓜式详解...
  8. 【Arthas】Arthas classloader类加载器
  9. 12505 java_Java jdbc Oracle error: ORA 12505
  10. MIMO-OTFS in High-Doppler Fading Channels:Signal Detection and Channel Estimation(3)
  11. ITIL4 讲解:监控管理
  12. 原生拨号盘设置电信卡呼叫转移概率失败
  13. 解决安装office2007的各种工具时提示“安装程序找不到office.zh-cn/*”的问题
  14. 参考文献标引方式_参考文献标注及排写格式
  15. 注册微信小程序账号 APPID的获取
  16. HTML篇三——(1)
  17. ThreeJS - 直接设置Fbx模型的某个关节的位移和旋转值
  18. Linux boot 时 USB 的初始化过程分析2
  19. 漫谈测试成长之探索——测试用例评审
  20. JQuery-回到顶部

热门文章

  1. 使用poi导出excel,及合并单元格边框显示问题
  2. 人工智能原理笔记------知识表示方法
  3. c语言中正弦函数的定义,三角函数基本概念 | 玄数
  4. @ds实现多数据源切换及解决事务失效问题
  5. 高德地图WEB端软件应用
  6. Android攻城狮ScrollView
  7. Debussy VerilogVHDL ISE仿真平台搭建步骤
  8. 镜头焦距和视角大小计算
  9. 手把手教你最近很火的 微信公众号测试号推送消息
  10. The SetStack Computer UVA - 12096 集合栈计算机 set集合