Java_School

Java_School

1. HelloWorld

1.1. 练习

温度转换程序:

import java.util.Scanner;
public class Temperature{
    public static void main(String [] args){
        int c;
        Scanner sc = new Scanner(System.in);
        c = sc.nextInt();

        int f = 9 * c / 5 + 32;
        System.out.println("最高温度:" + c + "C");
        System.out.println("最高温度:" + f + "F");
    }
}

天气程序:

import java.util.Scanner;
public class Temperature{
public static void main(String [] args){
double c;
String w;
Scanner sc = new Scanner(System.in);
c = sc.nextDouble();
w = sc.next();
    
    double f = 9 * c / 5 + 32;
System.out.println("最高温度:" + c + "C");
System.out.println("最高温度:" + f + "F");
System.out.println("天气:" + w);
}
    }

Java基础--数据

1.标识符:temp,grade,charPosition;一般一个或者多个英文单词;多个第二个首字母大写。

2.关键字:一些英文单词,Java语言自己用,不允许用户再定义为其他含义。

3.类型:基本类型,引用类型

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

引用类型:类、接口、数组

4.表达式:运算符把变量、常量链接起来。例如:9 * c / 5 + 32

优先级:c + 5 * d;*的优先级高于+;x + y == c * d;运算次序1)x+y;2)c * d;3)判断 ==;记不住

写成这样:(x + y) ==(c * d)

结合性:a + b + c;

5.类型转换

public class Test{
    public static void main(String [] args){
        int i = 100;
        long l = 20;

        l = i;
        i = (int)l;
    }
}

Java程序:

1程序框架:public class xxxxx{......}

框架里面是一个方法:public static void main(String [] args){......}

程序功能写到main方法中

2程序功能:

IPO三步:输入,处理,输出;

再讲一个例子:

import java.util.Scanner;
public class CircleArea{
public static void main(String [] args){
//input
double r;
Scanner sc = new Scanner(System.in);
r = sc.nextDouble();
    
    //process
double area = r * r * 3.14;
//output
System.out.println("circle area = " + area);
}
    
    

1.2. 作业

第一周作业

1 .编写一个Java程序,输入两个整数,实现两个数的交换,并输出交换后的结果。要点提示:

  1. 假设有两个整型变量a和b,设计一个临时变量temp辅助交换

  2. 交换过程如下:

    temp = a;

    a = b;

    b = temp;

2 .摄氏温度和华氏温度是两个主要的国际温度计量标准。

不同国家使用不同的温度计量方法,

例如我国使用摄氏度,而美国使用华氏度。

如果输入摄氏温度,如何转换为华氏温度呢? 编写程序,将摄氏温度转换为华氏温度。

要点提示:

  1) 定义变量C和F分别表示摄氏度和华氏度;

  2) 从键盘输入摄氏度C的值;

  3) 利用转换公式F = 9*C/5+32计算出华氏度,赋值给F;

  4) 将F变量的值输出。

3 .上题实现了由摄氏温度转换为华氏温度,

请编写程序实现华氏温度转换为摄氏温度,输入华氏温度,将转换结果输出。

要点提示:

转换公式为C = (F-32)×5/9,F表示华氏度,C表示摄氏度。

4 .编写程序,

输入球体的半径,计算球的体积,输出结果。

要点提示:

体积计算公式V= 4 / 3 * π * r * r * r,r为半径。

5 .编写程序,

输入正方形的边长,计算正方形的面积,输出结果。

要点提示:

面积计算公式S= side * side,side为边长。

6 .在购物结账时,会根据商品的单价和购买数量计算出总价。

编写程序,从键盘输入瓶装水的单价和购买数量,计算并输出金额,计算结果保留两位小数。

要点提示:保留指定位数的小数

  1) 引入DecimalFormat包:import java.text.DecimalFormat;

  2) 设定小数位数格式:DecimalFormat df = new DecimalFormat("0.00");

  3) 将result值保留指定位数小数:result = df.format(total);

7 .身体质量指数即BMI指数,是用于衡量人体胖瘦程度以及是否健康的一个标准。

BMI指数的计算公式为:BMI = 体重(kg)÷身高2(m2)。

例如,一个人身高1.75米、体重75公斤,他的BMI值为24.49。

编写程序计算自己的BMI指数,对照下表查看自己身体健康状况。

要点提示:

计算公式BMI=体重÷身高2要写成合法的Java表达式,注意运算符优先级。

8 .国内BMI值(kg/m2) 9. 分类

9 .< 18.5 11. 偏瘦

10 .18.5 ~ 24 13. 正常

11 .24 ~ 28 15. 偏胖

12 .= 28 17. 肥胖

说明:6、7选做

1.3. 作业

第二周作业

1 .有折扣矿泉水金额:

每瓶矿泉水2.2元,1

0瓶及以上9折,

24瓶及以上8折;

输入购买数量,计算金额。

2 .两个数排序。

输入两个数a,b,从小到大输出。

提示:

两种方法:

第一种方法,直接比较,输出;

第二种方法,比较,交换;

3 .三个数排序。

输入三个数a,b,c,从小到大输出

4 .设计一个猜数游戏,

程序随机产生一个1-100的整数作为目标数字,

用户输入一个整数,

如果与目标数字相同,则用户猜中,游戏结束;

否则程序提示用户其所输入的数字比目标数字是大还是小,

如果6次均没有猜中,则游戏结束。

要点提示:

  1. 产生1-100随机数语句:x=1+(int)(Math.random()*100);

  2. 生成随机数,再使用循环输入数据并进行判断,直到相等或者超过6次。

5 .输入全班学生的成绩,统计及格(成绩>=60)学生的平均分。

要点提示:

  1. 全班学生人数未知,使用while循环,输入-1表示所有成绩输入完毕。

  2. 在循环体中加入if分支语句,如果输入成绩大于60,则进行累加和计数。

6 .显示100以内所有可以同时被3和7整除的整数。

要点提示,

在循环体中判断一个整数n是否能够被3和7整除,让n的值从1到100循环;

2. 类与对象

作业问题

提交:附件格式,按要求做;

提交:按时,1-2;21;3-7;4-6;5-3.

三个数比大小:

if(a<=b && b<=c) {
    //
}
else if (a<=c && c<=b) {
    //
}

不推荐;

2.1. 类的引入

从原来的学生类中做三步:

第一步,提出属性:

第二步,提取方法,display

第三步,提出main方法,放到Test类中

看Student类:

三个属性,一个方法;

Test类:main方法。

Test:测试类,引导类;

练习:定义一个教师类:姓名、年龄、工资;设计测试类Test装入运行教师类。

总结:

定义类:包括两个部分:属性和方法;

属性:简单说就是类的变量;描述类中对象特征的;

方法:类的函数;描述类的行为;

2.2. 构造方法

构造方法:给属性赋初值。

构造方法:名字和类名一样;没有返回类型;

用途:给属性赋初值;

参数:一般构造方法参数的个数与属性个数一致;

一般写法上,参数类型和名字与属性一样;赋值:this.name= name;

this代指本类对象。

练习:参考Student类,给Teacher类增加构造方法,初始化属性;

2.3. 访问控制权限

四种访问控制权限:public、private、protected、默认;

总结:简单处理,方法,类前面加public;属性前面加private;

2.4. 对象实例化过程

例子:Student s = new Student("张三", 19, 89);

Student:类;简单理解为类型;与int,double相似;

s:对象;简单理解为一个变量;与int i 中的i类似

实例:堆中开辟的空间,称为实例。

new:在堆中开辟存储空间,空间大小又Student确定,存放对象属性值;

具体说:开辟空间包括:三个部分:name的值,age的值和grade的值;

构造方法:Student("lisi", 19, 78),给实例初始化属性值;

=的作用:空间的起始地址赋给对象s;

对象s存放是地址;对象类型是应用类型;

开辟空间,赋初值的过程,称为实例化;

2.5. this关键字

this是一个关键字,指代本类对象。

举例说明:

Student s = new Student("lisi", 19, 78);

调用 Student("lisi", 19, 78);,对应这个方法的this指针是s

构造方法中:this.name = name;本质上执行的是s.name = name

修改年龄的执行过程:

s.display(); 执行display方法对应的对象s;

display方法内,this指代就是对象s

this的用法:有两种:

this.name:本类对象;

this,指代本类构造方法;this("unknown",0, 0);

在没有歧义的情况下,this可以省略。

2.6. 作业

第三周作业

1 . 设计一个手机类MobilePhone,

属性有品牌brand和号码code,类型String;

设计一个带参数的构造方法初始化对象属性。

设计测试类,创建MobilePhone类的对象,并调用方法显示手机基本信息。

要点提示:

  1. 定义MobilePhone类的属性:品牌、号码,类型String;

  2. 定义MobilePhone类的构造方法:public MobilePhone(String brand, String code);

  3. 定义MobilePhone类的显示方法:display()。

2 . 摄氏温度类Celsius,

有一个属性temp,类型int;

增加一个构造方法Celsius(int temp);

有一个转换方法int cTof(int temp);

一个显示方法,显示对应的摄氏和华氏温度。

设计测试类,输入摄氏温度,显示对应的摄氏温度和华氏温度。

3 . 设计骰子类Dice,

有一个属性:点数,num(1--6),类型int;

有一个方法play(),掷色子;显示方法,显示点数;

增加一个构造方法Dice(),随机产生一个点数。

设计测试类,

定义骰子对象,显示点数,掷骰子,再次显示点数。

4 . 定义一个周工资类Salary,可以计算每周的工资。

有两个属性:

工作小时数hours,类型int;

每小时工资price,类型double。

一个构造方法Salary(int hours, double price)。

一个方法geMoney(),根据小时数来计算工资,如果每周小时数超过40,超出部分工资增加50%;

一个显示工资方法display()。

设计测试类,

定义工资对象,输入工作小时数和小时工资,显示周工资。

5 . 定义Door类,

有属性宽度、高度,int;颜色,String;

方法,显示门信息。增加构造方法。

设计测试类,

输入Door类对象属性值,显示对象信息。调用开门方法,再次显示门信息。

6 . 定义教室类ClassRoom,

属性:座位数,编号,朝向;

方法:显示教室信息。增加一个属性门door,类型Door。

增加构造方法初始化属性值。

设计测试类,

输入ClassRoom类对象属性值编号、座位数和朝向,

定义一个门对象,显示教室对象信息。

7 . 定义线段类LineSeg,

有四个属性:x1,y1,x2,y2;方法求线段长度,显示线段信息;

增加构造方法LineSeg(double x1, double y1,double x2, double y2)。

设计测试类,输入LineSeg类对象端点坐标值,定义LineSeg类对象ls,显示线段对象ls的长度。

8 . 在程序6基础上定义矩形类MyRectangle;

有四个属性:

起点x,y;

宽度:length,高度:height;

方法:计算面积,显示面积。

增加构造方法MyRectangle(double x, double y, double length, double height)。

设计测试类,

输入矩形的起点坐标值,长和宽,显示矩形的面积。

9 . 设计一个MyPoint类,

属性:x,y;点的坐标值;

方法有显示方法,构造方法。

设计测试类,

输入坐标值,显示点。

10 . 圆类MyCircle有属性:圆心center,类型MyPoint;半径r,类型double;

方法有:

构造方法MyCircle(MyPoint p, double r),

计算面积方法getArea(),返回类型double;

显示面积方法display(),返回类型void。

在测试类中定义圆对象,显示圆面积。

前7个比做,有面两个选做。

3. 类&对象&关键字

3.1. 类

1、类的组成:属性和方法

2、属性的定义:类型:标识符

3、方法:类似于函数。返回类型,方法名,参数,方法体

4、方法:构造方法、置取方法,普通方法

5、构造方法:名字与类名相同,用于初始化属性的值;

6、置取方法:获取方法,名字是get+属性名首字母大写,返回类型是属性类型,返回值是属性的值;

	设置方法,名字是set+属性名首字母大写,返回类型void,使用参数值修改属性值。

7、类的访问控制权限:public、private、protected、默认。类和方法用public;属性用private

3.2. 对象

1、对象的定义

2、对象的实例

3、this关键字:访问属性和方法;访问本类对象的构造方法;

4、实例化过程

3.3. 静态属性和静态方法

1、静态属性,管理类中的对象实例;

2、静态方法,只能访问静态的属性和方法;

3、静态属性和方法,可以使用类名访问,也可以使用实例名访问

3.4. 重载方法

1、要求:访问控制权限,类型,名字相同,参数不同;

2、参数i相同:两个方法的参数个数和类型一一对应,相同;其他不相同;

3、重载方法的作用是相同的名字的不同方法表示同一功能的不同实现。

public class Dice {
    // 1、属性
    private int num;
    
    // 2、空参构造器
    public Dice() {
        num = play();
    }
    
    public int play() {
        int temp = (int) ((Math.random) * 6) + 1;
        return temp;
    }
    
    // 对上面方法play()的改进
    public int play() {
        num = (int) ((Math.random) * 6) + 1;		// 直接修改属性
    }
    
}

Color,是Java基础类

自己定义颜色属性的时候,写成myColor,好像写成 color,也没有什么影响

类似的

Circle, Point是基础类

自己写成 myCircle, myPoint

赋值(修改属性值)的几种方法

1、带参构造器,参数来赋值属性

2、get, set方法

3、普通方法

使用工具,打开.class文件,有个init(),说明有默认构造器

如果自己写了构造器(空参/带参),.class文件中,就没有init()了

指针和引用的理解

指针->变量

引用->常量

允许负值,不允许计算

C语言

int* p;			// 定义
malloc();		// 申请
free();			// 释放

C语言指针

1、提前释放指针,悄悄死掉

2、不释放指针(内存泄漏),慢死

C指针,传递了很多层,到最后程序员,不是道什么时候释放了,用不用释放了

Java, GC(garge collector),垃圾回收器

GC代价

1、牺牲性能

application,需要设置标志,去检测,哪些需要回收,这个GC application,运行会占用资源

2、收集不完整

难以判断的,就不判断了

大量商用服务器,Java写

高性能,高要求服务器,C写的

3.5. static的引入

C语言

// 函数
function() {
    static int i;		// 有点类似,常驻内存了
}

// 修改i的值
i = 10;
i = 20;
i = 30;

Java

加完 staic,属性就不存到 heap中了

static静态方法中,只能使用静态属性 或 方法

1、Math.random()

静态属性、方法

1、静态attribute, method和类关联,用类名 或 实例名,来访问

2、静态属性:类属性,

类有效,则静态属性有效

public Demo() {    this("");			// 访问本类对象的构造方法    }

3.6. 作业

第四周作业

1 . 使用前面定义点MyPoint类,

增加两个距离重载方法,参数是点,或者是一对坐标值。

2 . 使用前面定义点MyPoint类,

增加两个重载设置点方法,参数是点,或者是一对坐标值。

使用设置方法修改。

提示:

先调get方法,取出x来,再set进去

3.设计一个正方形类MySquare,

有两个基本属性:左下起点,MyPoint类型;边长,double类型。

正方形类MySquare的方法有:构造方法MySquare(MyPoint start, double side);

构造内接圆方法createCircle(),类型MyCircle;

显示方法display(),显示内接圆的圆心,半径和面积。

设计测试类,

输入正方形起点和边长,构造内接圆,显示内接圆信息。

4.设计一个排课程序,

设计一个教师类Teacher,

再设计一个课程类Course,

属性有课程编号,名称,简介,类型都是字符串。

课程类Course中有一个构造方法,

一个排课方法schedule(Teacher t),参数是教师对象,返回类型void,

方法体显示教师姓名,讲授课程,

显示结果示例:“zhangsan teaching Java programming”,

其中zhangsan是教师名,Java programming是课程名。

设计测试类,

定义教师对象,课程对象,显示排课结果。

5 . 设计一个选课程序,

先设计一个课程类Course,

属性有课程编号,名称,简介,类型都是字符串。

再参考前面书中内容设计一个学生类Student,学生类设计一个选课方法select(Course c),完成选课功能,

参数是课程对象,方法体显示学生姓名,选修课程,

显示结果示例:“zhangsan selecting Java programming”,

其中zhangsan是学生姓名,Java programming是课程名。

再增加一个类似的方法,退选课程unSelect(),

方法体显示学生姓名和课程名称。

设计测试类,定义学生对象,课程对象,显示选课和退课的结果。

6 . 设计一个小猴打怪程序;

定义一个小猴类,属性:编号,名字,方法打怪;

定义一个测试类,创建小猴,打怪;

显示创建小猴的序号,打怪内容;

7 . 提高:设计一个摄氏温度类Celsius,有两个属性,温度值和标志值,标志值是C;

同样设计一个华氏温度类Fahrenheit,有两个属性,温度值和标志值,标志值是F。

给摄氏温度类增加一个温度转换方法cTof(),返回华氏温度类的对象,对象的属性温度是转换后的华氏温度值;

同样,给华氏温度增加一个转换方法fToc(),返回摄氏温度类的对象,对象的属性温度是转换后的摄氏温度值;

两个类各有一个显示温度方法display(),显示温度值和标志。

设计测试类,输入一个摄氏温度值,构造摄氏温度类对象,显示摄氏温度结果。

使用温度转换方法cTof()生成一个华氏温度对象,显示转换后的温度结果。

8 . 提高:

定义车类Car,

一辆车有四个轮子(类Wheels)和一个发动机(类Engine)。

现在要求用组合方法设计类Car、类Wheel和类Engine。

  1. 类Engine 有一个字符串属性类型,记录发动机的型号;

有构造方法,可设置发动机的型号;

有方法start()启动引擎(输出包含发动机型号和“starts”的字符串)。

  1. 类Wheel有一个字符串属性类型,记录轮胎的型号,有整数类型属性编号,记录当前轮胎位置的编号(1:front-left,2:front-right,

3:back-left,4:back-right),有构造方法,可设置轮胎的型号和编号,有方法roll()表示轮胎正在转动,输出轮胎型号、轮胎位置。

  1. 类Car有一个字符串类型的属性,记录车的型号;

有属性轮子数组wheels[]和engine,分别是Wheel类对象数组和Engine类对象;

有构造方法,参数是三个字符串,分别表示轿车的型号、轮胎型号和发动机的型号;

有方法changeWheel()可以改变指定轮胎的型号;

有方法start(),

先输出轿车型号和“firing”的字符串,

然后调用engine的start(),

再调用所有轮胎的roll(),

最后显示轿车型号和“running”。

  1. 要求编程实现类Car、类Wheel和类Engine,

定义Test类,

定义Car类对象,

执行run()方法,

显示要求信息。

9 . 提高:

使用前面定义点MyPoint类,

增加两个重载距离方法,点到点,点到线。

4. 继承、接口与泛型

子类与父类

子类的继承性

子类的子类对象的构造过程

子类的成员变量隐藏和方法的重写

子类的super关键字

子类的final类与final方法

子类的对象的上转型对象

前面讲的是 类和对象

面向对象

封装、继承、多态

1、封装

封装,设计类

2、继承

3、多态

泛化

1、正方形、矩形 不是 泛化而来,

2、特例: 可以在程序中,写 圆 继承于 点

点 是 圆的特例,圆 经过泛化后,得不到点

程序正确

1、程序实现正确

2、语义正确

Java API 改不了(过时)

最典型的过时方法,Date,以后使用 开林特

读 Java api 语言 问题、错误, 小册子

4.1. 作业

1、定义电话类Phone,

属性有电话号码code,

方法包括一个带参的构造方法,

一个普通方法display(),用于显示code属性值。

以Phone类为父类,继承得到手机类MobilePhone,

要求

新增属性品牌brand和机主身份证号ownerId,

新增普通方法public double pay(int time,double price),用于返回话费计算结果(time*price)。

设计测试类创建MobilePhone类对象,并计算话费。

要点提示:

  1. 参考程序13.1实现父类Phone;

  2. 参考程序13.2实现子类MobilePhone。

2、大学课程包括 理论课 和 实践课,

设计 理论课类ClassCourse的属性有:

编号code,类型String; 名称name,类型String; 学时hours,类型int。

设计一个 实践课类LaboratoryCourse属性有:

编号code,类型String; 名称name,类型String; 周数weeks,类型int。

两类课程都有方法display(),显示课程信息。

要求对两类课程进行 泛化 得到 课程类Course,

使用 课程类 作为基类,继承 基类 设计出 理论课 和 实践课 对应的类。

设计测试类,定义三个类的对象,实例化,显示各类课程的信息。

3、设计 学生类Student 和 它的 子类Undergraduate,

要求:

①Student类

有属性:姓名name 和 年龄age,

有一个包含两个参数的 构造方法,为 两个属性 赋初值,

一个 display() 方法 输出 Student的 属性信息;

②Undergraduate类增加一个属性:专业major,类型String。

有一个包含三个参数的构造方法,

一个display()方法输出Undergraduate的属性信息;

③在测试类中

分别创建Student对象 和 Undergraduate对象,

调用它们的 display()方法 显示 学生信息。

4、宠物猫Cat属性有:名字name,类型String, 颜色cColor,类型String, 年龄age,类型int;

方法有两个:吃eat(),叫shout()。

宠物狗Dog属性有:名字name,类型String, 种类species,类型String, 年龄age,类型int;

方法有吃eat(),叫shout(),两个方法分别显示不同的字符串。

在此基础上进行 泛化,得到宠物类Pet;

属性有:名字name,类型String, 年龄age,类型int;

方法有吃eat(),叫shout()。

设计测试类,定义三个类的对象,实例化,显示各自的信息。

5. 抽象类&接口

5.1. final

final 用在修饰下面3个东西, 前面

1, 修饰 类,则 类 不可以再被 继承,例如,不能有 extends String

2, 修饰 方法,则 方法 不可以再被 重写

3, 修饰 属性,则 属性 不可以再被 修改

public final int size = 10;   // size不可修改

5.2. 上下转型

向上转型,向下转型

动态绑定,实现了多态

同一个东西,有不同的表现,叫多态

Pet p = new Pet("huang", 2);p.eat();// 在不同的语境下,p调用不同实例的eat()Pet::eat();Cat::eat();Dog::eat();

现代程序设计工程,不用 继承 实现 代码复用 功能,

现代程序设计工程,复用 用 组合

继承 用来 做 多态 和 框架

框架的核心

先写的代码Pet p,调用后来的代码

前面的代码, 调用后面的代码

5.3. 抽象类

抽象类 和 抽象方法

上面是 抽象类,接口

下面是 具体类

抽象类,

抽象方法, 继承这个 抽象类 的时候, 必须 重写这个方法,强制重写

概念的抽象 ==> 抽象类

5.4. 接口

一个类 通过使用关键字 implements 声明 自己实现 一个 或 多个接口。

接口名字的规范写法: 动词+able

class A implements Printable, Addable;
A a = new A();

a 可以是 Printable,也可是 Addable 的对象

很多人开发项目的时候

先写接口,

写接口(实现接口的功能) 的人A小组, 写接口

用接口的人B小组, 正常用就可以了, 测试的时候,可以 先通过写 假的 接口, 等到A小组的人写完之后, 把正确的 实现接口功能的代码, 替换 测试的 假的接口,就可以了

什么叫多态?

下节课,讲 异常类

前面封装、继承、多态, 讲完了

后面再讲一些 面向对象的

再后面,讲一些 Java应用

5.5. 作业

第六周作业:

1、修改子类 宠物猫Ca t和 宠物狗Dog,重写方法 吃eat() 和 方法 叫shout()。

在前面 类Person 基础上 增加 喂养方法feed(Pet p),

给这个方法传递 不同的 子类对象实例,喂养方法调用对应宠物对象的方法 吃eat() 和 叫shout()。

设计 测试类Test,利用 宠物 对象多态,显示 不同结果。

提高:有兴趣的读者可以继续改进这个程序,设计 学生类Student 继承 Person,实现 学生 喂养 宠物。

Tips:

1、考察: 多态性

修改Cat类, Dog类

测试类中,

往里面,扔谁的实例

将来可以传递 Pet的实例,

feed方法里面 调用 写2个方法eat(), shout(),s

Test里面,调用 person.feed() 参数,可以传递 Pet的实例, Cat的实例, Dog的实例

传递不同,显示不同

2、修改MobilePhone类,对 父类 的 display()方法 进行 重写,显示 brand 和 ownerId 属性的值。

Test类 中定义 Phone类 和 MobilePhone类 的对象,并分别 调用display()方法。

要点提示,重写 MobilePhone类 的 display() 方法。

Tips:

2、

调用子类的display()方法

3、修改 宠物类Pet 为 抽象类,方法 吃eat() 和 方法 叫shout() 为抽象方法。

定义 宠物类Pet 的 子类 宠物猫Cat 和 宠物狗Dog,属性 和 方法与 实做程序14.5 相同。

设计 测试类Test,利用宠物对象 多态,显示 不同结果。

Tips:

3、考察: 抽象类,抽象方法

提示:

4、设计两个接口,

接口 Eatable 有一个方法吃eat(),接口 Shoutable 有一个方法 叫shout()。

设计 宠物猫类Cat 和 宠物狗类Dog 分别 实现 两个接口,重写 对应的接口方法。

定义 类Person,有一个 饲养宠物方法 feed(Eatable ea),一个听声音方法 hear(Shoutable sa),显示 一个字符串。

设计 测试类Test,利用宠物对象 多态,显示 饲养不同宠物 和 听到 不同宠物 的叫声。

Tips:

4、考察: 接口

显示字符串

6. 异常类&包

6.1. 异常类

try-catch

try-catch-finally

finally, 恢复现场, 常用来 释放资源

有些服务器, 不能随便重启

Error

  • VirtureMachineError

Exception

  • 运行时异常

  • i/o异常

throws

数组越界异常

6.2. 包(package)

windows 没有包

非Windows, 有包

Windows中 叫 文件夹

其他OS, 叫 目录

package, 必须放到第一行

编译 和 运行, 都是在当前目录下(package)

java test.Test

虚拟机, 装载 类

错误写法

直接进入 test目录, 执行

java test

会报错, 会去找 package下

体会 当前目录

\ DOS系统, 目录分隔符

6.3. Java总结

6.3.1 java基础知识

访问控制权限 private, public; 高阶内容

6.3.2 面向对象程序设计

this, 本类对象

this作用

1, 访问属性和方法

2, 访问本类构造方法

对象实例化

继承, 泛华, 设计获得类的结构

super, this, 对应

多态

1, 方法重写

2, 上转型

3, 多态, 面向对象的精华

框架 用的就是 多态, 框架 还有用 其他

抽象类

1, 抽象方法

接口

1, 定义方法, 只写 方法头

2, 抽象类 和 接口的异同

6.3.3 java应用

1, 字符串

2, 集合类, 泛型

Java基础类库 包含 大多数 数据结构

3, 文件结构

文件读写操作, 复制

4, 数据库

访问数据库

5, 图形界面

Java中, 图形界面不重要

Java做服务器,

图形界面优点

1, 有趣

2, 和win类似, 涉及 事件处理机制

用到 接口

有时间的话

6, 网络编程

6.4. 作业

第七次作业:

1, 定义数组ta,有size个元素,编写程序访问ta[size]元素,看看报什么异常。

修改程序捕获相应异常。

再次测试,查看结果。

2, 编写程序输入一个整数a,实际输入时输入字符,看看报什么异常。

修改程序捕获相应异常。

再次测试,查看结果。

3, 前面定义了图形类MyPoint、MySquare、MyCircle,在此基础上定义图形类包shape,将这些类放入该包中。

定义测试类,显示图形信息

7. String&包装类&集合类&Map

public boolean mkdir    public boolean mkdirs

Java应用

虽然,String使用起来, 比较方便, 但是底层实现比较复杂的

黑板图

最左边 是 运行栈, 里面存放变量 s1, s2

s1, 指向 常量池中的 "test"

s2, 申请堆内存中, 堆内存再指向 常量池

hascode

String

StringBuilder, 线程不安全, 单线程

StringBuffer, 线程安全, 多线程

现在JDK, 是使用 StringBuilder实现的 String

StringBuffer, 线程安全

StringBuilder, 轻量级的字符数组

7.1. 包装类

自动装箱, 自动拆箱

包装类, 可以直接参与运算

所有包装类, 都增加了一个null值

将 数字 转化为 字符串

1,

"" + 数字

2, 使用valueOf方法

7.2. String

public final class Stringextends Objectimplements Serializable, Comparable<String>, CharSequence

7.2.1. String中常用方法

public int compareTo(String anotherString)  public boolean endsWith(String suffix) public boolean equals(Object anObject) public int hashCode()  public int indexOf(String str) public int length()  public boolean startsWith(String prefix)  public String trim()  public 

7.3. 集合类

集合类

map

例子

list接口

arraylist

arraylist是 list的实现类

定义 list的类型的

new 实现类的

List, 泛型, java从5开始支持的

7.4. Map

Map是 高度抽象的数据结构

C数据结构没有Map, 面向对象的数据结构中才有的 Map

Map<K, V>    Student: { "姓名:", "张三"    		"年龄", "18"    		"成绩", "98"    		"DA", "可以自己设计想输入的类型"  }

集合类, 有很多东西, 只讲了list, arraylist, map, hashmap

之后Java程序连接数据库的时候, 不管用什么数据库, 就是使用

List<Map<String, String>>

了解一下 put, 是List的方法, 还是 Map的方法, 应该是 Map的, 因为代码中, 使用的 Map的对象 m, 来调用put方法的

7.5. 作业

1, 参照上课的例子, 学生

用List, ArrayList来做

教师,用Map做, 或者 单独做个教师类

第八周作业:

定义教师类:姓名、年龄、工资;构造方法、显示方法;

定义学院类,有多名教师;显示方法,排序方法,添加教师,删除教师,修改教师工资;

实现方法自己查阅List的API文档,或者百度;

参考学生类和班级类实现;

测试类Test参考例子实现。

8. 10周

包名所有字母一律小写

switch, enum不能用

'65', 字符串

float b = 12.45;错误,

正确, floab b = 12.45f;

9. IO流

数据流

重定向, 管道, Unix

BufferedReader, 支持整行读写

Java中, 一个字符 是一个 int型

字节流

一个字节, 一个字节的读, 写

9.1. FileInputStream

java.io.FileInputStream

public class FileInputStream    extends InputStream {    // 构造器    public FileInputStream(File file);    public FileInputStream(FileDescriptor fdObj);    public FileInputStream(String name);        // 常用方法    public int read();    public int read(byte[] b);    public int read(byte[] b, int off, int len);}

使用 FileInputStream 的时候, 是从硬盘中, 读入到内存中

9.2. FileOutputStream

java.io.FileOutputStream

public class FileOutputStream    extends OutputStream {    // 构造器    public FileOutputStream(File file);    public FileOutputStream(File file, boolean append);    public FileOutputStream(FileDescriptor fdObj);    public FileOutputStream(String name);    public FileOutputStream(String name, boolean append);        // 常用方法    public void write(byte[] b);    public void write(byte[] b, int off, int len);    public void write(int b);}

体会, 使用 FileOutputStream的时候, 是从内存中, 往硬盘中写文件

字符流

例子中, 添加一条学生信息, 出现乱码, 改为用 字符流

字符流, 一个字符一个字符地读, 写

9.3. FileReader

java.io.FileReader

public class FileReader    extends InputStreamReader {    // 构造器    public FileReader(File file);    public FileReader(FileDescriptor fd);    public FileReader(String fileName);}

9.4. FileWriter

java.io.FileWriter

public class FileWriter    extends OutputStreamWriter {    // 构造器    public FileWriter(File file);    public FileWriter(File file, boolean append);    public FileWriter(FileDescriptor fd);    public FileWriter(String fileName);    public FileWriter(String fileName, boolean append);}

9.5. BufferedReader

9.6. BufferedWriter

打开&关闭文件

打开文件

1, 内存中, 形成该存储 该文件信息的 数据结构

2, 内存中, 分配缓冲区, 存储 磁盘中的该文件

关闭文件

1, 内存中, 缓冲区的文件 写到磁盘上

2, 删除 内存中, 形成的存储 该文件信息的 数据结构

体会, 打开文件, 理解这个之后, 有些内容, 就会比较容易理解, 有点 原理类知识点 的意思

上课还是要静下心来听的, 不要忙着记笔记, 有些内容理解了, 知道怎么分析理解了, 很多问题就解决了, 而不是整理的很好的笔记, 深刻体会这点吧

有很多此这样的体会了, 深刻体会吧

有些原理类的知识点, 理解了, 可以说是内在逻辑, 内在过程吧, 理解了过程, 再写代码, 就会知道步骤, 会容易很多

不然, 不理解过程, 会比较麻烦

9.7. File

java.io.File

public class File    extends Object    implements Serializable, Comparable<File> {        // 属性    static String pathSeparator;    static char pathSeparatorChar;    static String separator;    static char separatorChar;        // 构造器    // Creates a new File instance from a parent abstract pathname and a child pathname string.    public File(File parent, String child);        // Creates a new File instance by converting the given pathname string into an abstract pathname.    public File(String pathname);        // Creates a new File instance from a parent pathname string and a child pathname string.    public File(String parent, String child);        // Creates a new File instance by converting the given file: URI into an abstract pathname.    public File(URI uri);            // 方法        // Tests whether the application can execute the file denoted by this abstract pathname.    public boolean canExecute();        // Tests whether the application can read the file denoted by this abstract pathname.    public bollean canRead();        // Tests whether the application can modify the file denoted by this abstract pathname.    public boolean canWrite();        // Compares two abstract pathnames lexicographically.    public int compareTo(File pathname);        // Atomically creates a new empty file named by this abstract pathname if and only if a file with this name does not yet exist.    public boolean createNewFile();        // Creates a new empty file in the specified directory, using the given prefix and suffix string s to generate its name.    public static File createTempFile(String prefix, String suffix);    public static File createTempFile(String prefix, String suffix, File directory);        // Deletes the file or directory denoted by this abstract pathname.    public boolean delete();        // Requests that the file or directory denoted by this abstract pathname be deleted when the virtual machine terminamtes.    public void deleteOnExit();        // Tests this abstract pathname for equality with the given object.    public boolean equals(Object obj);        // Tests whether the file or directory denoted by this abstract pathname exists.    public boolean exists();        // Returns the absolute form of this abstract pathname.    public File getAbsoluteFile();        // Returns the absolute pathname string of this abstract pathname.    public String getAbsolutePath();        // Returns the canonicl form of this abstract pathname.    public File getCanonicalFile();        // Returns the canonical pathname string of this abstract pathname.    public String getCanonicalPath();        // Returns the number of unallocated bytes in the partition named by this abstract pathname.    public long getFreeSpace();        // Returns the name of the file or directory denoted by this abstract pathname.    public String getName();        // Returns the pathname string of this abstract pathname's parent, or null if this pathname does not name a parent directory.    public String getParent();        // Returns the abstract pathname of this abstract pathname's parent, or null if this pathname does not name a parent directory.    public File getParentFile();        // Converts this abstract pathname into a pathname string.    public String getPath();        // Returns the size of the partition named by this abstract pathname.    public long getTotalSpace();        // Returns the number of bytes available to this virtual machine on the partition named by this abstract pathname.    public long getUsableSpace();        // Computes a hash code for this abstract pathname.    public int hashCode();        // Tests whether this abstract pathname is absolute.   	public boolean isAbsolute();        // Test whether the file denotedy by this abstract pathname is a directory.    public boolean isDirectory();        // Tests whether the file denoted by this abstract pathname is a normal file.    public boolean isFile();        // Tests whether the file named by this abstract pathname is a hidden file.    public boolean isHidden();        // Returns the time that the file denoted by this abstract pathname was last modified.    public long lastModified();        // Returns the length of the file denoted by this abstract pathname.    public long length();        // Returns an array of strings naming the files and directroies in the directory denoted by this abstract pathname.    public String[] list();        // Returans an array of strings naming the files and directories in the directory denoted by this abstract pathname that satisfy the specified filter.    public String[] list(FilenameFilter filter);        // Returns an array of abstract pathname denoting the files in the directory denoted by this abstract pathname.    public File[] listFiles();        // Returns an array of abstract pathnames denoting the files and directories in the directory denoted by this abstract pathname that satisfy the speicified filter.    public File[] listFiles(FileFilter filter);        // Returns an array of abstract pathname denoting the files and directories in the directory denoted by this abstract pathname that satisfy the specified filter.    public File[] listFiles(FilenameFilter filter);        // List the available filesystem roots.    public static File[] listRoots();        // Creates the directory named by this abstract pathname.    public boolean mkdir();        // Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories.    public boolean mkdirs();        // Renames the file denoted by this abstract pathname.    public boolean renameTo(File dest);        // Sets the owner's or everybody's execute permission for this abstract pathname.    public boolean setExecutable(boolean executable);        // Sets the owner's or everybody's execute permission for this abstract pathname.    public boolean setExecutable(boolean executable, boolean ownerOnly);        // Sets the last modified time of the file or directory named by this abstract pathname.    public boolean setLastModified(long time);        // A convenience method to set the owner's read permission for this abstract pathname.    public boolean setReadable(boolean readable);        // Sets the owner's or everybody's read permission for this abstract pathname.    public boolean setReadable(boolean readable, boolean ownerOnly);        // Marks the file or directory named by this abstract pathname so that only read operations are allowed.    public boolean setReadOnly();        // Sets the owner's or everybody's read permission for this abstract pathname.        // A convenience method to set the owner's write permission for this abstract pathname.    public boolean setWritable(boolean writable);        // Sets the owner's or everybody's write permission for this abstract pathname.    public boolean setWritable(boolean writable, boolean ownerOnly);       // Returns a java.nio.file.Path object constructed from the this abstract path.    public Path toPath();        // Returns the pathname string of this abstract pathname.    public String toString();        // Constructs a file: URI that represents this abstract pathname.    public URI toURI();        // Deprecated    public URI toURI();}

9.8. 作业

1, 给文件增加一个复制函数, 设计 测试类 实现文件复制

提高: 测试类从 命令行 读入参数, 实现文件复制(这个好像是在, 上面的那个基础上)

2, 参考学生类和班级类, 设计 教师类 和 学院类, 实现教师信息的文件操作功能, 包括将 学院教师信息 保存到 文件, 从文件 读取 教师信息

提高: 初始化学院

提高: 如果文件不存在, 或者为空, 则使用程序数据 初始化

Tips: 向尝试从文件中读, 文件中没有, 再 如果文件不存在, 或者为空, 就用原来的数据初始化

10. GUI&事件监听

图形界面

刚开始 awt

后来将第三方 swing, 加入类库

10.1. Container

java.awt.Container

public class Container extends Component {    // 构造器    public Container();        // 常用方法    add(Component comp);    add(Component comp, int index);    add(Component comp, Object constraints);    add(Component comp, Object constraints, int index);    add(String name, Component comp);    addContainerListener(ContainerListener l);}

10.2. Window

public class Window    extends Container    implements Accessible {        // 构造器    public Window(Frame owner);    public Window(Window owner);    public Window(Window owner, GraphicsConfiguration gc);        // 常用方法    public void setBackground(Color bgColor);    public void setBounds(int x, int y, int width, int height);    public void setBounds(Rectangle r);    public void setIconImage(Image image);    public void setIconImages(List<? extends Image> icons);    public void setLocation(int x, int y);    public void setLocation(Point p);    public void setSize(Dimension d);    public void setSize(int width, int height);    public void setVisible(boolean b);}

10.3. Frame

java.awt.Frame

public class Frame extends Window implements MenuContainer {    // 构造器    Frame();    Frame(GraphicsConfiguration gc);    Frame(String title);    Frame(String title, GraphicsConfiguration gc);    // 常用方法    void setBackground(Color bgColor);    void setIconImage(Image image);    void setResizable(boolean resizable);    void setTitle(String title);}

10.4. Font

java.awt.Font

public class Font extends Object implements Serializable {    // 构造器    public Font(Font font);    public Font(Map<? extends AttributedCharacterIterator.Attribute,?> attributes);    public Font(String name, int style, int size);}

10.5. Color

java.awt.Color

public class Color extends Object implements Paint, Serializable{    static Color black;    static Color BLACK;    static Color blue;    static Color BLUE;    static Color cyan;    static Color CYAN;    static Color DARY_GRAY;    static Color darkGray;    static Color gray;    static Color GRAY;    static Color green;    static Color GREEN;    static Color LIGHT_GRAY;    static Color lightGray;    static Color magenta;    static Color MAGENTA;    static Color orange;    static Color ORANGE;    static Color pink;    static Color PINK;    static Color red;    static Color RED;    static Color white;    static Color WHITE;    static Color yellow;    static Color YELLOW;    // 构造器    public Color(ColorSpace cspace, float[] components, float alpha);    public Color(float r, float g, float b);    public Color(float r, float g, float b, float a);    public Color(int rgb);    public Color(int rgba, boolean hasalpha);    public Color(int r, int g, int b);    public Color(int r, int g, int b, int a);}

10.6. 放图片

Windows中, 图片 和 图标 不一样

图片不能直接用, 需要先通过ImageIcon(), 将图片转换为图标

lb.setIcon(new ImageIcon("java.jpg"));
public class ImageIcon    extends Object    implements Icon, Serializable, Accessible {    // 构造器    public ImageIcon();    public ImageIcon(byte[] imageData);    public ImageIcon(byte[] imageData, String description);    public ImageIcon(Image image);    public ImageIcon(Image image, String description);    public ImageIcon(String filename);    public ImageIcon(String filename, String description);    public ImageIcon(URL location);    public ImageIcon(URL location, String description);}

10.7. Layout

FlowLayout, 流式布局(常用)

BorderLayout, 边界布局(常用)

CardLayout, 网格布局

GridLayout布局

null, 空布局

BoxLayout, 布局

布局自己做

不设置set, 默认 边界布局

JPanel, 不写, 默认 流失布局

1, FlowLayout

FlowLayout构造器

public class FlowLayout extends Object implements LayoutManager, Serializable {    // 构造器    public FlowLayout();    public FlowLayout(int align);    public FlowLayout(int align, int hgap, int vgap);        // 常用方法    }

2, BorderLayout

BorderLayout构造器

public class BorderLayout extends Object implements LayoutManager2, Serializable {    // 构造器    public BorderLayout();    public BorderLayout(int hgap, int vgap);}

3, null

10.8. Dimension

public class Dimension extends Dimension2D implements Serializable {    // 构造器    public Dimension();    public Dimension(Dimension d);    public Dimension(int width, int height);}

10.9. 给按钮加动作

输入框, textfile

import javax.swing.*;import java.awt.*;import java.awt.event.*;public class EventDemo implements ActionListener{	private JFrame myFrame;	private JLabel lb = new JLabel("显示标签");	private JButton input = new JButton("演示按钮");		public EventDemo(String title){		myFrame = new JFrame(title);		myFrame.setLocation(100, 100);		myFrame.setSize(300, 200);		FlowLayout flow = new FlowLayout();		flow.setAlignment(FlowLayout.LEFT);		myFrame.setLayout(flow);				input.addActionListener(this);				myFrame.add(input);		myFrame.add(lb);		myFrame.setVisible(true);		myFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);	}	public void actionPerformed(ActionEvent evt){		lb.setText(input.getText());	}}

10.10. TextArea

public class TextArea extends TextComponent {    // 常量    static int SCROLLBARS_BOTH;    static int SCROLLBARS_HORIZONTAL_ONLY;    static int SCROLLBARS_NONE;    static int SCROLLBARS_VERTICAL_ONLY;    // 构造器    TextArea();    TextArea(int rows, int columns);    TextArea(String text);    TextArea(String text, int rows, int columns);    TextArea(String text, int rows, int columns, int scrollbars);        // 常用方法    public static Component createHorizontalBox();    public void setLayout(LayoutManager l);}

10.11. Box

public class Box extends JComponent implements Accessible {    // 构造器    Box(int axis);        // 常用方法    // Creates a Box that displays its components from left to right.    public static Box createHorizontalBox();        // Creates an invisible, fixed-width component.    public static Component createHorizontalStrut(int width);    }

10.12. JFrame

Frame, 是个窗口

带J的, 是swing组件

图形界面实现机理

swing, 轻量级(Java写的),

awt, 本地写的, 依赖本地

Jpanel, 也是容器类控件

控件分2类

1, 容器

2, 普通控件

EXIT_ON_CLOSE, 是JFrame中的常量, 使用的时候, 加上 JFrame

public class JFrame extends Frame     implements WindowConstants, Accessible, RootPaneContainer {    // 属性    protected AccessibleContext accessibleContext;    static int EXIT_ON_CLOSE;    protected JRootPane rootPane;    protected boolean rootPaneCheckingEnabled;    // 构造器    public JFrame();    public JFrame(GraphicsConfiguration gc);    public JFrame(String title);    public JFrame(String title, GraphicsConfiguration gc);    // 常用方法    public void setSize(int width, int height);    public void setLocation(int x, int y);    public void setVisible();    public void setResizable(boolean b);    public void dispose();							// 撤销当前窗口, 并释放当前窗口所使用的资源    public void setExtendedState(int state);			// 设置窗口的扩展状态    /*    operation, 取JFrame中的 int型 static常量        DO_NOTHING_ON_CLOSE			// 什么也不做	HIDE_ON_CLOSE				// 隐藏当前窗口	DISPOSE_ON_CLOSE			// 隐藏当前窗口, 并释放窗体占有的其他资源	EXIT_ON_CLOSE				// 结束窗口所在的应用程序    */    public void setDefaultCloseOperation(int operation);}

state, 取JFrame中的下列常量

MAXIMIZED_HORIZ 		// 水平方向最大化MAXIMIZED_VERT 			// 垂直方向最大化MAXIMIZED_BOTH			// 水平, 垂直方向都最大化

10.13. JLabel

标签, 显示提示信息

javax.swing.JLabel

public class JLabel extends JComponent    implements SwingConstants, Accessible {    // 构造器    public JLabel();    public JLabel(Icon image);    public JLabel(Icon image, int horizontalAlignment);    public JLabel(String text);    public JLabel(String text, Icon icon, int horizontalAlignment);    public JLabel(String text, int horizontalAlignment);}

10.14. JButton

javax.swing.JButton

public class JButton extends AbstractButton    implements Accessible {        // 构造器    public JButton();    public JButton(Action a);    public JButton(Icon icon);    public JButton(String text);    public JButton(String text, Icon icon);}

10.15. JTable

javax.swing.JTable

public class JTable    extends JComponent    implements TableModelListener, Scrollable, TableColumnModelListener, ListSelectionListener, CellEditorListener, Accessible, RowSorterListener {    // 构造器    public JTable();    public JTable(int numRows, int numColumns);    public JTable(Object[][] rowData, Object[], columnNames);    public JTable(TableModel dm);    public JTable(TableModel dm, TableColumnModel cm);    public JTable(TableModel, dm, TableColumnModel cm, ListSelectionModel sm);    public JTable(Vector rowData, Vector columnNames);}

10.16. JMenu

javax.swing.JMenu

public class JMenu    extends JMenuItem    implements Accessible, MenuElement {    // 构造器    public JMenu();    public JMenu(Action a);    public JMenu(String s);    public JMenu(String s, boolean b);}

10.17. JMenuItem

javax.swing.JMenuItem

public class JMenuItem    extends AbstractButton    implements Accessible, MenuElement {    // 构造器    public JMenuItem();    public JMenuItem(Action a);    public JMenuItem(Icon icon);    public JMenuItem(String text);    public JMenuItem(String text, Icon icon);    public JMenuItem(String text, int mnemonic);	// Creates a JMenuItem with the specified text and keyboard mnemonic(助记符).}

10.18. JMenuBar

javax.swing.JMenuBar

public class JMenuBar    extends JComponent    implements Accessible, MenuElement {        // 构造器    public JMenuBar();        // 常用方法    public JMenu add(JMenu c);		// Appends the specified menu to the end of the menu bar.}

10.19. Jpanel

中间容器

先使用 Jpanne

在使用 Borderlaoyout

javax.swing.Jpanel

public class JPanel    extends JComponent    implements Accessible {    // 构造器    public JPanel();    public JPanel(boolean isDoubleBuffered);    public JPanel(LayoutManager layout);    public JPanel(LayoutManager layout, boolean isDoubleBuffered);}

10.20. 事件

ActionEvent

public class ActionEvent {        // Constructs an ActionEvent object.    public ActionEvent(Object source, int id, String command);        // Constructs an ActionEvent object with modifiler keys.    public ActionEvnet(Object source, int id, String command, int modifiers);        // Constructs an ActionEvent object with thie specified modifiler keys and timesamp.    public ActionEvent(Object source, int id, String command, long when, int modifiers);}

10.21. 作业

1, 设计一个添加学生界面, 可以录入学生的姓名, 年龄和成绩; 将输入数据保存到文件中

设计一个界面, 里面有一个TestArea控件, 读取学生信息, 显示到界面中

将上面两个界面合并到一个界面中

2, 参考上面程序设计一个登录界面, 输入用户名和密码; 登录成功显示上面界面, 否则给出提示, 显示登录页面

3, 设计一个简单图形界面程序, 界面给出一个按钮和一个标签

采用流式布局

按钮的名字: "点击我"

标签名字: "点击x次", 显示按钮的点击次数; 最初为0次

设计程序实现上述功能

11. 网络编程与多线程

网络编程

计算机前面, 有一个终端设备, 才能连接到网络, 现在这个设备变小了, 这个设备就是 网卡

有线网卡, 就是一条线

无线网卡, 内置在笔记本电脑中

物理连接(有线, 无线), 有线, 无线, 都叫物理连接

无线, 也会占用无线信道

网络编程, 一句话, 就是面向Socket编程, 客户端和服务端连接, 体会

电脑常驻运行程序

11.1. DataOutputStream

java.io.DataOutputStream

public class DataOutputSteam    extends FilterOUtputStream    implements DataOutput {    // 属性    protected int written;        // 构造器    // Creates a new data output stream to write data to the specified underlying output stream.    // 创建一个新的数据输出流, 以将数据写入指定的底层输出流    DataOutputSteam(OutputStream out);        // 方法    // Flushes this data output stream.    // 刷新此数据输出流    public void flush();        // Return the current value of the counter written, the number of bytes written to this data output stream so far.    // 返回计数器的当前值written, 到目前为止写入此数据输出流的字节数    public int size();        // Writes len bytes from the specified byte array starting at offset off to the underlying output stream.    // 写入, 从off开始, 长度为len    public void write(byte[], int off, int len);        // Writes the specified byte(the low eight bits of the argument b) to the underlying output stream.    // 将指定的字节(参数b 的低8位) 写入底层输出流    public void write(int b);        // Writes a boolean to the underlying output stream as a 1-byte-value.    // 将boolean写入底层输出流作为1字节值    public void writeBoolean(boolean v);        // Writes out a byte to the underlying output stream as a 1-byte value.    // 将byte作为1字节值写入底层输出流    public void writeByte(int v);        // Writes out the string to the underlying output stream as a sequence of bytes.    // 将字符串作为字节序列写入基础输出流    public void writeBytes(String s);        // Writes out a byte to the underlying output stream as a 1-byte value.    // 将byte作为1字节值写入底层输出流    public void writeChar(int v);        // Writes out the string to the underlying output stream as a sequence of byte.    // 将char写入底层输出流作为2字节值, 高字节优先    public void writeChars(String s);        // Converts the double arguments to a long using the doubleToLongBits method in class Double, and then writes that long value to the underlying output stream as an 8-byte quantity, high byte first.    // 使用 Double类 中的 doubleToLongBits方法, 将 double参数类型 转换到 long型, 将 long型的值,以8字节写入到输出流, 高字节优先    public void writeDouble(double v);        // Converts the float argument to an int using the floatToIntBits method in class Float, and then writes that int value to the underlying output stream as a 4-byte quantity, high byte first.    // 使用 Float类 中的 floatToIntBits方法, 将 float型 的参数转换成 int型, 然后将 int型值 以4个字节的标准, 写入到 底层输出流, 高字节优先    public void writeFloat(float v);        // Writes an int to the underlying output stream as four bytes, high byte first.    // 给4个字节, 将 int型 写入到 底层输出流    public void writeInt(int v);        // Writes a long to the underlying output stream as eight bytes, high byte first.    // 以8个字节, 将 long型 写入到 底层输出流, 高字节优先    public void writeLong(long v);        // Writes a short to the underlying output stream as two bytes, high byte first.    // 以2字节, 将 short型 写入到 底层输出流, 高字节优先    public void writeShort(int v);        // Writes a string to the underlying output stream using modified UTF-8 encoding in a machine independent manner.    // 使用UTF-8编码, 将字符串型的值, 写入到 底层输出流    public void writeUTF(Strint str);}

11.2. DataInputStream

数据输入流允许应用程序以独立于机器的方式

java.io.DataInputStream

public class DataInputStream    extends FilterINputStream    implements DataInput {        // 构造器        // Creates a DataInputStream that uses the specified underlying InputStream.    // 使用指定的 底层输入流, 创建一个 DataInputStream    DataInputStream(InputStream in);        // Reads some number of bytes from the contained input stream and stores them into the buffer array b.    // 从一些包含的input stream中, 读一些字节, 存储它们到 缓冲字符数组 b    public int read(byte[] b);        // Reads up to len bytes of data from the contained input stream into an array of bytes.    // 从包含在 input stream中, 读入长度为 len 的字节数据, 到 字节数组中    public int read(byte[] b, int off, int len);        // See the general contract of the readBoolean method of DataInput    // 去看一下 DataInput 的 readBoolean方法, 的一般说明    public boolean readBoolean();        // See the general contract of the readByte method of DataInput    // 去看一下 DataInput 的 readByte方法, 的一般说明    public byte readByte();        // See the general contract of the readChar method of DataInput    // 去看一下 DataInput 的 readChar方法    public char readChar();        // See the general contract of the readDouble method of DataInput    // 去看一下 DataInput 的 readDouble方法, 的一般说明    public double readDouble();        // See the general contract of the readFloat method of DataInput    // 去看一下 DataInput 的 readFloat方法, 的一般说明    public float readFloat();        // See the general contract of the readFully method of DataInput    // 去看一下 DataInput的 readFully方法, 的一般说明    public void readFully(byte[] b);        // See the general contract of the readFully method of DataInput    // 去看一下 DataInput的 readFully方法, 的一般说明    public void readFully(byte[] b, int off, int len);        // See the general contract of the readInt method of DataInput    // 去看一下 DataInput的 readInt方法, 的一般说明    public int readInt();        // Deprecated    public String readLine();        // See the general contarct of the readLong method of DataInput    // 去看一下 DataInput 的 readLong方法, 的一般说明    public long readLong();        // See the general contract of the readShort method of DataInput    // 去看一下 DataInput 的 readLong方法, 的一般说明    public short readShort();        // See the general contract of the readUnsignedShort method of DataInput.    // 去看一下 DataInput 的readUnsignedShort方法, 的一般说明    public int readUnsignedByte();        // See the general contract of the readUnsignedByte method of DataInput    // 去看一下 DataInput 的 readUnsignedByte方法, 的一般说明    public int readUnsignedShort();        // See the general contract of the readUTF method of DataInput    // 去看一下 DataInput 的 readUTF方法, 的一般说明    public String readUTF();        // Reads from the stream in a representations of a Unicode character string encoded in modified UTF-8 format; this string of characters is then returned as s String.    // 从一个流中读取 UTF-8格式的数据, 这个字符串类型, 返回一个 字符串    public static String readUTF(DataInput in);        // See the general contract of the skipBytes method of DataInput    // 去看一下 DataInput 的 skipBytes方法, 的一般说明    public int skipByte(int n);}

11.3. Socket

该类实现客户端套接字(也称为 "套接字"), 套接字是两台机器之间通讯的端点

套接字的实际工作由SocketImpl类的实例执行, 应用程序更改创建套接字工厂, 可以配置自己创建适合本地防火墙的套接字

java.net.Socket

public class Socket extends Object implements Closeable {    // 构造器    // 创建一个未连接的socket, 并使用系统默认类型的SocketImpl    public Socket();        // 创建流socket, 并将其连接到指定IP地址的指定端口号    public Socket(InetAddress address, int port);        // 已弃用. 使用DatagramSocket代替UDP传输    public Socket(InetAddress host, int port, boolean stream);            // 创建一个socket, 连接它到指定的远程地址的指定端口    public Socket(InetAddress address, int port, InetAddress localAddr, int localPort);        // Creates an unconnected socket, specifying the type of proxy. if any, that should be used regardless of any other settings.    // 创建一个无连接的socket, 指定代理类型, 如果有的话, 无论其他任何设置如何    public Socket(Proxy proxy);        // Creates an unconnected Socket with a user-specified SocketImpl    // 使用一个用户指定的SocketImpl, 创建一个无连接的socket    public Socket(SocketImpl impl);        // Creates a stream socket and connectes it to the specified port number on the named host    // 创建一个流socket, 连接它到指定的主机名的指定端口号上    public Socket(String host, int port);        // Deprecated. Use DatagramSocket instead for UDP transport    // 已废弃, 使用DatagramSocket代替UDP传输    public Socket(String host, int port, boolean stream);        // Creates a socket and connects it to the specified remote host on the specified remote port.    // 创建一个socket, 连接它到指定远程主机的指定端口    public Socket(String host, int port, InetAddress localAddr, int localPort);}

11.4. ServerSocket

这个类实现了服务器套接字, 服务器套接字等待通过网络进入的请求.

它根据该请求执行一些操作, 然后可能将结果返回给请求者

服务器套接字的实际工作由SocketImpl类的实例执行, 应用程序可以更改创建套接字实现的套接字工厂, 以配置自己创建适合本地防火墙的套接字

java.net.ServerSocket

构造器

public ServerSocket(int port) throws IOException;

常用方法

侦听要连接到此套接字并接受它, 该方法将阻塞直到建立连接

创建一个新的Socket s, 如果有安全管理器, 则使用 s.getInetAddress().getHostAddress()和 s.getPort()作为其参数来调用安全管理器的checkAccept()方法, 以确保允许操作, 这可能会导致 Security.Exception

public Socket accept()    throws IOException;
public class ServerSocket     extends Object     implements Closeable {    // 构造器    public ServerSocket();    public ServerSocket(int port);    public ServerSocket(int port, int backlog);    public ServerSocket(int, int backlog, InetAddress bindAddr);        // 侦听要连接到此套接字并接受它    public Socket accept();        // 将ServerSocket绑定到特定地址(IP地址和端口号)    public void bind(SocketAddress endpoint);        // 将ServerSocket绑定到特定地址(IP地址和端口号)    public void bind(SocketAddress endpoint, int backlog);        // 关闭套接字    public void close();        // 返回与此套接字相关联的唯一的ServerSocketChannel对象(如果有)    public ServerSocketChannel getChannel();        // 返回此服务器套接字的本地地址    public InetAddress getInetAddress();        // 返回此服务器正在侦听的端口号    public int getLocalport();        // 返回此服务器绑定到的端点的地址    public int getLocalSocketAddress();        // 获取此ServerSocket的SO_RCVBUF选项的值, 即将用于从该ServerSocket接受的套接字的建议缓冲区大小    public int getReceiveBufferSize();        // 测试是否启用了 SO_REUSEADDR    public boolean getReuseAddress();        // 检索 SO_TIMEOUT 的设置    public int getSoTimeout();        // ServerSocket的子类使用这个方法来覆盖 accept() 来返回自己的套接字子类    public protected void implAccept(Socket s);        // 返回ServerSocket的返回状态    public boolean isBound();        // 返回ServerSocket的关闭状态    public boolean isClosed();        }

11.5. InetAddress

java.net.InetAddress

public class InetAddress    extends Object    implements Serializable {    }

11.6. DatagramSocket

java.net.DatagramSocket

public class DatagramSocket    extends Object    implements Closeable {        public DatagramSocket();    protected DatagramSocket(DatagramSocketImpl impl);    public DatagramSocket(int port);    public DatagramSocket(int port, InetAddress laddr);    public DatagramSocket(SocketAddress bindaddr);        public void bind(SocketAddress addr);    public void close();    public void connect(InetAddress addr, int port);    public void disconnect();    public boolean getBroadcast();    public DatagramChannel getChannel();    public InetAddress getInetAddress();    public InetAddress getLocalAddress();    public int getLocalPort();    public SocketAddress getLocalSocketAddress();    public int getPort();    public int getReceiverBufferSize();    public SocketAddress getRemoteSocketAddress();    public boolean getReuseAddress();    public int getSendBufferSize();    public int getSoTimeout();    public int getTrafficClass();    public boolean isBound();    public boolean isClosed();    public boolean isConnected();    public void receive(DatagramPacket p);    public void send(DatagramPacket p);    public void setBroadcast(boolean on);    public static void setDatagramSocketImplFactory(DatagramSocketImplFactory fac);    public void setReveiveBufferSize(int size);    public void setReuseAddress(boolean on);    public void setSendBufferSize(int size);    public void setSoTimeout(int timeout);    public void setTrafficClass(int tc);       }

11.7. DatagramPacket

java.net.DatagramPacket

public final class DatagramPacket    extends Object {        public DatagramPacket(byte[] buf, int length);    public DatagramPacket(byte[] buf, int length, InetAddress address, int port);    public DatagramPacket(byte[] buf, int offset, int length);    public DatagramPacket(byte[] buf, int offset, int length, InetAddress address, int port);    public DatagramPacket(byte[] buf, int offset, int length, SocketAddress address);    pbulic DatagramPacket(byte[] buf, int length, SocketAddress address);        	public InetAddress getaddress();    public byte[] getData();    public int getLength();    public int getOffset();    public int getPort();    public SocketAddress getSocketAddress();    public void setAddress(InetAddress iaddr);    public void setData(byte[] buf);    public void setData(byte[] buf, int offset, int length);    public void setLength(int length);    public void setPort(int port);    public void setSocketAddress(SocketAddress address);    }

11.8. URL

java.net.URL

public final class URL    extends Object    implements Serializable {    // 构造器    public URL(String spec);    public URL(String protocol, String host, int port, String file);    public URL(String protocol, String host, int port, String file, URLStreamHandler handler);    public URL(String protocol, String host, String file);    public URL(URL context, String spec);    public URL(URL context, String spec, URLStreamHandler handler);}

11.9. Thread

多线程

java.lang.Thread

public class Thread    extends Object    implements Runnable {    // 构造器    public Thread();        // Allocates a new Thread object.    // 分配一个新的线程对象    public Thread(Runnable target);        // Allocate a new Thread object.    // 分配一个新的线程对象    public Thread(Runnable target, String name);        // Allocates a new Thread object.    // 分配一个新的线程对象    public Thread(String name);        // Allocates a new Thread object.    // 分配一个新的线程对象    public Thread(ThreadGroup group, Runnable target);        // Allocates a new Thread object so that it has target as its run object, has the specified name as its name, and belongs to the thread group refeered to by group.    // 分配一个新的线程对象, 以至于它有目标作为它的运行实体, 有它的名字的特定名字, 有属于线程组    public Thread(ThreadGroup group, Runnable target, String name);        // Allocates a new Thread object so that it has target as its run object, has specified name as its name, and belongs to the thread group referred to by group, and has the specified stack size    // 分配一个线程对象以至于它有目标作为它的运行实体    public Thread(ThreadGroup group, Runnable target, String name, long stackSize);        // Allocates a new Thread object    // 分配一个新的线程对象    public Thread(ThreadGroup group, String name);    // 常用方法    void run();									。     static void sleep(long millis);    static void sleep(long millis, int nanos);    // Causes(引起) this thread to begin execution; the Java Virtual Machine calls(调用) the run method of this thread.    void start();    boolean isAlive();									// Tests if this thread is alive.    void interrupt();									// Interrupts(中断) this thread.}

11.10. 作业

接口中的方法, 都是 抽象方法

实现接口, 则需要将接口中的方法重写, 但不绝对, 好像可以只重写接口中的部分方法, 跟楠哥学Java

抽象类中的方法, 不一定都是抽象方法

byte, 1个字节

int, 4个字节

静态方法运行时, 在 方法区

静态变量, 放在方法区

所有方法, 都在方法区

方法, 存在 方法区

对象, 存在 实例区

栈区, 堆中 有 实例区

Student s = new Student();

s, 在 栈区

new Studnet(), 在堆中的 实例区

栈中的s, 指向 堆中的实例区的new Studnet()

java中, 不叫 指针, 因为是 隐士引用

new Studnet(), 没有指定值得时候, 默认有初始值

汇编语言, 块填充, 快, 磁盘

.class文件中的 init方法, 就是默认的构造方法, 自己通过idea编译后的.class文件, 打开后, 没有看到

可以尝试通过Notepad++, 打开, 或者通过命令行窗口编译, 再打开试试

java, jvm对 string , 进行了很多加工

string,不是普通的类型了

posted on 2021-06-18 15:23  beyondx  阅读(219)  评论(0编辑  收藏  举报

导航