栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

2021-10-12 六、面向对象(上)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

2021-10-12 六、面向对象(上)

面向对象(上)
  • 1. 面向过程与面向对象
    • 1.1 面向对象:Object Oriented Programming
    • 1.2 面向过程:Procedure Oriented Programming
    • 1.3 学习面向对象内容的三条主线
  • 2. 类和对象
    • 2.1 Java 类及类的成员
    • 2.2 类与对象的创建及使用
    • 2.3 对象的创建和使用:内存解析
  • 3. 类
    • 3.1 类的成员之一:属性
    • 3.2 类的成员之二:方法
      • 3.2.1 类中方法的声明和使用
      • 3.2.2 理解“万事万物皆对象”
      • 3.2.3 对象数组的内存解析
      • 3.2.4 匿名对象的使用
      • 3.2.5 自定义数组的工具类
      • 3.2.6 方法的重载(overload)
      • 3.2.7 可变个数的形参
      • 3.3 (重点)方法参数的值传递机制
      • 3.3.1 针对基本数据类型(值传递)
      • 3.3.2 针对引用数据类型
      • 3.3.3 练习
  • 4. 面向对象特征之一:封装与隐藏
    • 4.1 封装性的引入与体现
    • 4.2 四种权限修饰符的理解与测试
  • 5. 类的结构之三:构造器(构造方法、constructor)的使用
    • 5.1 构造器的理解
    • 5.2 总结属性赋值的过程
  • 6. 关键字:this 的使用
    • 6.1 this 调用属性、方法、构造器
  • 7. 关键字:package、import 的使用
    • 7.1 关键字—package
    • 8.2 关键字—import

1. 面向过程与面向对象

何谓“面向对象”的编程思想?

  • 首先解释一下什么是“思想”。
    例如:先问你个问题:你想做个怎样的人?
    可能你会回答:我想做个好人,孝敬父母,尊重长辈,关爱亲朋…
    你看,这就是思想。这是你做人的思想,或者说,是你做人的原则。做人有做人的原则,编程也有编程的原则。这些编程的原则呢,就是编程思想。
1.1 面向对象:Object Oriented Programming

面向对象的思想概述

  1. 面向对象分析方法分析问题的思路和步骤:
  2. 根据问题需要,选择问题所针对的现实世界中的实体。
  3. 从实体中寻找解决问题相关的属性和功能,这些属性和功能就形成了概念世界中的类。
  4. 把抽象的实体用计算机语言进行描述,形成计算机世界中类的定义。即借助某种程序语言,把类构造成计算机能够识别和处理的数据结构。
  5. 将类实例化成计算机世界中的对象。对象是计算机世界中解决问题的最终工具。
// 人把大象装进冰箱的问题
// 把构成问题事务分解成各个对象,
// 建立对象的目的不是为了完成一个步骤,
// 而是为了描叙某个事物在整个解决问题的步骤中的行为。
  人{
  		打开(冰箱){
  			冰箱.开门();
  		}
  		操作(大象){
  			大象.进入(冰箱);
  		}
  		关闭(冰箱){
  			 冰箱.关门();     
  		}
  }
  
  冰箱{
  		开门(){
  		}  
  		关门(){
  		}
  }
  
  大象{
  		进入(冰箱){
  		}
  }
1.2 面向过程:Procedure Oriented Programming
// 人把大象装进冰箱的问题
// 就是分析出解决问题所需要的步骤,
// 然后用函数把这些步骤一步一步实现,使用的时候一个一个依次调用就可以了
 ① 打开冰箱
 ② 把大象装进冰箱
 ③ 把冰箱门关住 

两者的区别:友情链接
各自的优缺点:
面向过程:

  • 优点:性能比面向对象高,因为类调用时需要实例化,开销比较大,比较消耗资源;比如单片机、嵌入式开发、 Linux/Unix等一般采用面向过程开发,性能是最重要的因素。
  • 缺点:没有面向对象易维护、易复用、易扩展

面向对象:

  • 优点:易维护、易复用、易扩展,由于面向对象有封装、继承、多态性的特性,可以设计出低耦合的系统,使系统 更加灵活、更加易于维护
  • 缺点:性能比面向过程低
1.3 学习面向对象内容的三条主线
  • Java 类及类的成员:属性、方法、构造器、代码块、内部类
  • 面向对象的三大特征:封装、继承、多态性、(抽象性)
  • 其它关键字:this、super、static、final、abstract、interface、package、import 等
2. 类和对象

2.1 Java 类及类的成员

现实世界的生物体,大到鲸鱼,小到蚂蚁,都是由最基本的细胞构成的。同理,Java 代码世界是由诸多个不同功能的类构成的。

现实生物世界中的细胞又是由什么构成的呢?细胞核、细胞质、… 那么,Java 中用类 class 来描述事物也是如此。常见的类的成员有:

  • 属性:对应类中的成员变量
  • 行为:对应类中的成员方法
2.2 类与对象的创建及使用
 
//1.创建类,设计类的成员
class Person{
	
	//属性:对应类中的成员变量
	String name;
	int age = 1;
	boolean isMale;
	
	//方法:对应类中的成员方法
	public void eat(){
		System.out.println("吃饭");
	}
	
	public void sleep(){
		System.out.println("睡觉");
	}
	
	public void talk(String language){
		System.out.println("人可以说话,使用的是:" + language);
	}
}
//测试类
public class PersonTest {
	public static void main(String[] args) {
		//2.创建 Person 类的对象
		//创建对象语法:类名对象名= new 类名();
		Person p1 = new Person();
		//Scanner scan = new Scanner(System.in);
		
		//调用类的结构:属性、方法
		//调用属性:“对象.属性”
		p1.name = "Tom";
		p1.age = 25;
		p1.isMale = true;
		System.out.println(p1.name); // Tom
		
		//调用方法:“对象.方法”
		p1.eat(); // 吃饭
		p1.sleep(); // 睡觉
		p1.talk("chinese"); // 人可以说话,使用的是:chinese
		/
 class User{
	//属性(或成员变量)
	String name;	//不加 权限修饰符 即为缺省 默认值 null
	public int age; // 默认值 0
	boolean isMale; // 默认值 false
	
	public void talk(String language){// language:形参,也是局部变量
		System.out.println("我们使用" + language + "进行交流。");
	}
	
	public void eat(){
		String food = "石头饼";	// food:局部变量
		System.out.println("北方人喜欢吃:" + food);
	}
}
public class UserTest {
	public static void main(String[] args) {
		User user = new User();
		System.out.println(user.name); // null
		System.out.println(user.age); // 0
		System.out.println(user.isMale); // false
		
		user.talk("俄语"); // 我们使用俄语进行交流。
	}
}


练习1

class Student{
	String name;
	int age;
	String major;
	String interests;
	
	void say(String name, int age){
		System.out.println("这个学生是:"+name+"年龄是:"+age);	}
}
class Teacher{
	String name;
	int age;
	String teachAge;
	String course;
	
	void say(String name, int age){
		System.out.println("这个老师是:"+name+"年龄是:"+age);
	}
}
public class School {
	public static void main(String[] args) {
		Student stu = new Student();
        stu.name = "小明";
        stu.age = 16;
		
		Teacher tea = new Teacher();
		tea.name = "王老师";
        tea.age = 27;

        stu.say(stu.name,stu.age); // 这个学生是:小明年龄是:16
        tea.say(tea.name, tea.age); // 这个老师是:王老师年龄是:27
	}	
}

3.2 类的成员之二:方法 3.2.1 类中方法的声明和使用

方法:描述 类 应该具有的功能。比如:

  1. Math类:sqrt()random() …
  2. Scanner类:nextXxx() …
  3. Arrays类:sort() binarySearch() toString() equals()
  • 方法的声明规则:
权限修饰符  返回值类型  方法名(形参列表){
 	方法体
 } 			  

注意
关于权限修饰符:默认方法的权限修饰符暂时先都使用public
Java规定的4种权限修饰符:private、public、缺省、protected
static、final、abstract 来修饰的方法,后面再讲。

举例: (封装性暂时不说)
public void eat(){}
public void sleep(int hour){}
public String getName(){}
public String getNation(String nation){}
  • 返回值类型: 有返回值 vs 没有返回值
    • 如果方法有返回值,则必须在方法声明时,指定返回值的类型。同时,方法中,需要使用 return关键字来返回指定类型的变量或常量return 数据;
    • 如果方法没有返回值,则方法声明时,使用void来表示。通常,没有返回值的方法中,就不需要使用return.但是,如果使用的话,只能return ;,表示结束此方法的意思。

    return关键字的使用:
    使用范围:使用在方法体中
    注意点: return关键字后不可声明执行语句。

方法的使用中,可以调用当前类的属性或方法。特殊的:方法A中又调用了方法A(递归方法)。

示例

//客户类
class Customer{
	
	//属性
	String name;
	int age;
	boolean isMale;
	
	//方法
	// 方法名:属于标识符,遵循标识符的规则和规范,“见名知意”
	public void eat(){
		System.out.println("客户吃饭");
		return;
		//return后不可以声明表达式
//		System.out.println("hello");
	}
	
	// 形参列表:方法名可以声明0个、1个,或多个形参。
	// 格式:数据类型1 形参1,数据类型2 形参2,...如下面的int hour
	public void sleep(int hour){
		System.out.println("休息了" + hour + "个小时");
		// 方法的使用中,可以调用当前类的属性或方法。
		eat();
//		sleep(10);
	}
	
	public String getName(){
		// 方法的使用中,可以调用当前类的属性或方法。
		if(age > 18){
			return name;
			
		}else{
			return "Tom";
		}
	}
	
	public String getNation(String nation){
		String info = "我的国籍是:" + nation;
		return info;
	}
	
	//体会形参是否需要设置的问题
//	public void sort(int[] arr){
//		
//	}
//	public void sort(){
//		int[] arr = new int[]{3,4,5,2,5,63,2,5};
//		//。。。。
//	}
	
	public void info(){
		//错误的: 方法中不能定义其他方法。
//		public void swim(){
//			
//		}
		
	}
}
public class CustomerTest {
	public static void main(String[] args) {
		
		Customer cust1 = new Customer();
		
		cust1.eat();
		
		//测试形参是否需要设置的问题
//		int[] arr = new int[]{3,4,5,2,5};
//		cust1.sort();
		
		cust1.sleep(8);
		
	}
}


练习1

public class Person {
	String name;
	int age;
	
	int sex;
	
	public void study(){
		System.out.println("studying");
	}
	
	public void showAge(){
		System.out.println("age:" + age);
	}
	
	public int addAge(int i){
		age += i;
		return age;
	}
}

测试类

public class PersonTest {
	public static void main(String[] args) {
		Person p1 = new Person();
		
		p1.name = "Tom";
		p1.age = 18;
		p1.sex = 1;
		
		p1.study(); // studying
		
		p1.showAge(); // age:18
		
		int newAge = p1.addAge(2);
		System.out.println(p1.name + "的年龄为" + newAge); // Tom的年龄为20
		
		System.out.println(p1.age);	//20
		
		/
 //圆:面积=3.14*r*r
class Circle{
	//属性 半径
	double radius;
	
	//圆的面积方法
	//方法1:
//	public double findArea(){
//		double area = 3.14 * radius * radius;
//		return area;
//	}	
	//方法2:
	public void findArea(){
		double area = Math.PI * radius * radius;
		System.out.println("面积为:" + area);
	}
	//错误情况:
	public double findArea(Double r){
		double area = 3.14 * r * r; // 这里用的是外面传进来的形参,而不是这个圆实体类本身的半径
		return area;
	}
}

//测试类
public class CircleTest {
	public static void main(String[] args) {
		Circle c1 = new Circle();
		
		c1.radius = 2.1;
		
		//对应方式一:
//		double area = c1.findArea();
//		System.out.println(area); // 13.8474
		
		//对应方式二:
		c1.findArea();
		//错误的调用
		double area = c1.findArea(3.4);
		System.out.println(area);
	}
}

练习3

public class ExerTest {
		//3.1
//	public void method(){
//		for(int i = 0;i < 10;i++){
//			for(int j = 0;j < 8;j++){
//				System.out.print("* ");
//			}
//			System.out.println();
//		}
//	}
	
	//3.2
//	public int method(){
//		for(int i = 0;i < 10;i++){
//			for(int j = 0;j < 8;j++){
//				System.out.print("* ");
//			}
//			System.out.println();
//		}
//		return 10 * 8;
//	}
	
	//3.3
	public int method(int m,int n){
		for(int i = 0;i < m;i++){
			for(int j = 0;j < n;j++){
				System.out.print("* ");
			}
			System.out.println();
		}
		return m * n;
	}
	
	public static void main(String[] args) {
		
		ExerTest esr = new ExerTest();
		//3.1测试
//		esr.method();
		
		//3.2测试
		//方式一:
//		int area = esr.method();
//		System.out.println("面积为:" + area);
		
		//方式二:
//		System.out.println("面积为:" + esr.method());
		
		//3.3测试
		System.out.println("面积为:" + esr.method(6,5));
	}

}

练习4

 
class Student{
	int number;	//学号
	int state;	//年级
	int score;	//成绩
	
	//显示学生信息的方法
	public String info(){
		return "学号:" + number + ",年级:" + state + ",成绩:" + score;
	}
}
// 测试类
public class StudentTest {
	public static void main(String[] args) {
		//声明一个Student类型的数组
		Student[] stu = new Student[20];
		for(int i = 0;i stu[j+1].score){
					//如果需要换序,交换的是数组的元素,也就是整个Student对象!!!
					Student temp = stu[j];
					stu[j] = stu[j+1];
					stu[j+1] = temp;
				}
			}
		}
		
		//遍历学生数组
		for(int i = 0;i < stu.length;i++){
			System.out.println(stu[i].info());
		}
		
	}
}

练习四优化(体现面向对象的封装性)

 
class Student2{
	int number;	//学号
	int state;	//年级
	int score;	//成绩
	
	//显示学生信息的方法
	public String info(){
		return "学号:" + number + ",年级:" + state + ",成绩:" + score;
	}
}
// 测试类
public class StudentTest2 {
	public static void main(String[] args) {
		//声明一个Student类型的数组
		Student2[] stu = new Student2[20];
		
		for(int i = 0;i  stu[j + 1].score) {
                    flag = true;
                    //如果需要换序,交换的是数组的元素,Student对象!!!
                    temp = stu[j];
                    stu[j] = stu[j + 1];
                    stu[j + 1] = temp;
                }
            }
            // 如果内层循环没有交换过说明后面的已经有序了,可以结束排序
            if (!flag) {
                break;
            }
        }
    }
	}
}

3.2.2 理解“万事万物皆对象”

通过上述的学习,我们再次理解一下对象
1.在Java语言范畴中,我们都将功能、结构等封装到类中,通过类的实例化,来调用具体的功能结构。如:

  1. Scanner,String等
  2. 文件:File
  3. 网络资源:URL

2.涉及到Java语言与前端html、后端的数据库交互时,前后端的结构在Java层面交互时,都体现为类、对象。

3.2.3 对象数组的内存解析
Student[] stus = new Student[5];
stus[0] = new Student();
sysout(stus[0].state);//1
sysout(stus[1]);// null
sysout(stus[1].number);// 异常
stus[1] = new Student();
sysout(stus[1].number);// 0

class Student{
  int number;//学号
  int state = 1;//年级
  int score;//成绩
}

3.2.4 匿名对象的使用
class Phone{
	double price;	//价格
	
	public void sendEmail(){
		System.out.println("发邮件");
	}
	public void playGame(){
		System.out.println("打游戏");
	}
	public void showPrice(){
		System.out.println("手机价格为:" + price);
	}
}
class PhoneMall{
	
	public void show(Phone phone){
		phone.sendEmail();
		phone.playGame();
	}
}

 // 测试类
public class InstanceTest {
	public static void main(String[] args) {
	    // 实例对象
		Phone p = new Phone();
//		p = null;
		System.out.println(p);
		p.sendEmail();
		p.playGame();
		
		//匿名对象 在堆中生成内存地址,用完即弃
//		new Phone().sendEmail(); // 发邮件
//		new Phone().playGame(); // 打游戏
		
		new Phone().price = 1999;
		new Phone().showPrice();	//0.0
		
		/
public class ArrayUtil {
	// 求数组的最大值
	public int getMax(int[] arr) {
		int maxValue = arr[0];
		for (int i = 1; i < arr.length; i++) {
			if (maxValue < arr[i]) {
				maxValue = arr[i];
			}
		}
		return maxValue;
	}

	// 求数组的最小值
	public int getMin(int[] arr) {
		int minValue = arr[0];
		for (int i = 1; i < arr.length; i++) {
			if (minValue > arr[i]) {
				minValue = arr[i];
			}
		}
		return minValue;
	}

	// 求数组总和
	public int getSum(int[] arr) {
		int sum = 0;
		for (int i = 0; i < arr.length; i++) {
			sum += arr[i];
		}
		return sum;
	}

	// 求数组平均值
	public int getAvg(int[] arr) {
		int avgValue = getSum(arr) / arr.length;
		return avgValue;
	}

	// 反转数组
	public void reverse(int[] arr) {
		for (int i = 0; i < arr.length / 2; i++) {
			int temp = arr[i];
			arr[i] = arr[arr.length - i - 1];
			arr[arr.length - i - 1] = temp;
		}
	}

	// 复制数组
	public int[] copy(int[] arr) {
		int[] arr1 = new int[arr.length];
		for (int i = 0; i < arr1.length; i++) {
			arr1[i] = arr[i];
		}
		return null;
	}

	// 数组排序
	public void sort(int[] arr) {
		for (int i = 0; i < arr.length - 1; i++) {
			for (int j = 0; j < arr.length - 1 - i; j++) {
				if (arr[j] > arr[j + 1]) {
					int temp = arr[j];
					arr[j] = arr[j + 1];
					arr[j + 1] = temp;
				}
			}
		}
	}

	// 遍历数组
	public void print(int[] arr) {
		System.out.print("[");
		for (int i = 0; i < arr.length; i++) {
			System.out.print(arr[i] + ",");
		}
		System.out.println("]");
	}

	// 查找指定元素
	public int getIndex(int[] arr, int dest) {
		//线性查找
		for (int i = 0; i < arr.length; i++) {
			if (dest==arr[i]) {
				return i;
			}
		}
		return -1;
	}
}

测试类

public class ArrayUtilTest {
	public static void main(String[] args) {
		ArrayUtil util = new ArrayUtil();
		int[] arr = new int[]{32,5,26,74,0,96,14,-98,25};
		int max = util.getMax(arr);
		System.out.println("最大值为:" + max);
		
//		System.out.print("排序前:");
//		util.print(arr);
//		
//		util.sort(arr);
//		System.out.print("排序后:");
//		util.print(arr);
		
		System.out.println("查找:");
		int index = util.getIndex(arr, 5);
		if(index > 0){
			System.out.println("找到了,索引地址:" + index);
		}else{
			System.out.println("没找到");
		}
	}
}

3.2.6 方法的重载(overload)

重载的定义:在同一个类中,允许存在一个以上的同名方法,只要它们的参数个数或者参数类型不同即可。
!!!划重点,同一个类 相同方法名中 只要参数个数 或者 类型不一样即可 (与方法的返回值类型、权限修饰符、形参变量名、方法体都无关。)

public class OverLoadTest {
	//如下的四个方法构成了重载
	public void getSum(int i,int j){
		System.out.println("1");
	}
	// 形参类型不同
	public void getSum(double d1,double d2){
		System.out.println("2");
	}
	// 形参类型不同
	public void getSum(String s,int i){
		System.out.println("3");
	}
	
	// 形参类型不同
	public void getSum(int i,String s){
		
	}
	//以下3个是错误的重载 
	// 形参类型相同、个数相同
//	public int getSum(int i,int j){
//		return 0;
//	}
	// 形参类型相同、个数相同
//	public void getSum(int m,int n){
//		
//	}
	// 形参类型相同、个数相同
//	private void getSum(int i,int j){
//		
//	}
	public static void main(String[] args) {
		OverLoadTest test = new OverLoadTest();
		//在通过对象调用方法时,通过判断参数列表指定重载方法
		test.getSum(1, 2);	//调用的第一个,输出1
	}


}

练习1

判断:在同一个类下,与void show(int a,char b,double c){} 构成重载的有:
a)void show(int x,char y,double z){} // no 形参类型相同、个数相同
b)int show(int a,double c,char b){} // yes // 形参类型不同(顺序不一样也是不同)
c) void show(int a,double c,char b){} // yes // 形参类型不同
d) boolean show(int c,char b){} // yes // 形参个数不一样
e) void show(double c){} // yes  // 形参个数不一样
f) double show(int x,char y,double z){} // no 形参类型相同、个数相同
g) void shows(){double c} // no // 方法名不一样,构不成重构

练习2

public class OverLoadever {
	//1.如下三个方法构成重载
	public void mOL(int i){
		System.out.println(i*i);
	}
	public void mOL(int i,int j){
		System.out.println(i*j);
	}
	public void mOL(String s){
		System.out.println(s);
	}
	
	//2.如下三个方法构成重载
	public int max(int i,int j){
		return (i > j) ? i : j;
	}
	public double max(double i,double j){
		return (i > j) ? i : j;
	}
	public double max(double d1,double d2,double d3){
		double max = (d1 > d2) ? d1 : d2;
		return (max > d3) ? max : d3;
	}
	public static void main(String[] args) {
		OverLoadever test = new OverLoadever();
		//1.调用3个方法
		test.mOL(5);
		test.mOL(6, 4);
		test.mOL("fg");
		
		//2.调用3个方法
		int num1 = test.max(18, 452);
		System.out.println(num1);
		double num2 = test.max(5.6, -78.6);
		System.out.println(num2);
		double num3 = test.max(15, 52, 42);
		System.out.println(num3);
	}

	
}

3.2.7 可变个数的形参

JavaSE 5.0 中提供了Varargs(variable number of arguments)机制,允许直接定义能和多个实参相匹配的形参。从而,可以用一种更简单的方式,来传递个数可变的实参。
可变个数形参的格式:数据类型 ... 变量名 例如:int ... a

  • 当调用可变个数形参的方法时,传入的参数的个数可以是:0个,1个,2个…
  • 可变个数形参的方法与本类中方法名相同,形参不同的方法之间构成重载。
  • 可变个数形参的方法与本类中方法名相同,与类型相同的数组之间不构成重载。即二者不可共存。(因为可变个数形参相当于一个数组了)
  • 可变个数形参在方法中的形参中,必须声明在末尾。
  • 可变个数形参在方法中的形参中,最多只能声明一个可变形参。
public class MethodArgs {
	public void show(int i) {

	}
	// public void show(String s){ 重载
	// System.out.println("show(String)");
	// }
	
	// 可变个数形参示例
	public void show(String... strs) {
		System.out.println("show(String ...strs)");
		for (int i = 0; i < strs.length; i++) {
			System.out.println(strs[i]);
		}
	}
	// 此方法与上一方法不可共存
	// public void show(String[] strs){
	//
	// }
	
	public void show(int i, String... strs) {

	}

	//可变个数形参必须放在最后,所以这个方法是错的
//	public void show(String... strs,int i,) {
//
//	}
	public static void main(String[] args) {
		MethodArgs test = new MethodArgs();
		test.show(12);
		// test.show("hell0");
		// test.show("hello","world");
		// test.show();
		test.show(new String[] { "AA", "BB", "CC" });
	}


}

3.3 (重点)方法参数的值传递机制
  • 关于变量的赋值
    如果变量是基本数据类型,此时赋值的是变量所保存的数据值。
    如果变量是引用数据类型,此时赋值的是变量所保存的数据的地址值。
class Order{
	int orderId;
}
public class ValueTransferTest {

	public static void main(String[] args) {
		
		System.out.println("**********基本数据类型:***********");
		int m = 10;
		int n = m;
		System.out.println("m = " + m + ", n = " + n); // m = 10, n = 10
		n = 20;
		System.out.println("m = " + m + ", n = " + n); // m = 10, n = 20
		System.out.println("***********引用数据类型:********");
		Order o1 = new Order();
		o1.orderId = 1001;
		Order o2 = o1;	//赋值后,o1和o2的地址值相同,都指向了堆空间中同一个对象实体
		System.out.println("o1.orderId = " + o1.orderId + ",o2.orderId = " + o2.orderId); // o1.orderId = 1001,o2.orderId = 1001
		
		o2.orderId = 1002;
		System.out.println("o1.orderId = " + o1.orderId + ",o2.orderId = " + o2.orderId);// o1.orderId = 1002,o2.orderId = 1002
	}
}

3.3.1 针对基本数据类型(值传递)

形参:方法定义时,声明的小括号内的参数
实参:方法调用时,实际传递给形参的数据

值传递机制: 如果参数是基本数据类型,此时实参赋值给形参的是实参真是存储的数据值。

public class ValueTransferTest1 {

	public void swap(int m,int n){
		int temp = m;
		m = n;
		n = temp;
	}
	
	public static void main(String[] args) {
		int m = 10;
		int n = 20;
		System.out.println("m = " + m + ", n = " + n);// m = 10, n = 20
		//交换两个变量的值的操作 
//		int temp = m; 
//		m = n;
//		n = temp; // m = 20, n = 10
		// 注释掉上面的交换,m = 10, n = 20
		ValueTransferTest1 test = new ValueTransferTest1();
		test.swap(m, n); // 这里的交换和外面的n、m无关
		
		System.out.println("m = " + m + ", n = " + n); // m = 10, n = 20
		
	}
}

3.3.2 针对引用数据类型

值传递机制: 如果参数是引用数据类型,此时实参赋值给形参的是实参存储数据的地址值。

class Data{
	
	int m;
	int n;
}
public class ValueTransferTest2 {

	public void swap(Data data){
		int temp = data.m;
		data.m = data.n;
		data.n = temp;
	}
	public static void main(String[] args) {
		Data data = new Data();
		data.m = 10;
		data.n = 20;
		System.out.println("m = " + data.m + ", n = " + data.n);// m = 10, n = 20

		//交换m和n的值
//		int temp = data.m;
//		data.m = data.n;
//		data.n = temp; // m = 20, n = 10

		// 注释掉上面的交换,m = 10, n = 20
		ValueTransferTest2 test = new ValueTransferTest2();
		test.swap(data); // 传进去之后,swap用的也是同一个地址的变量,所以外面会改变
		System.out.println("m = " + data.m + ", n = " + data.n);// m = 20, n = 10

	}
}

3.3.3 练习

练习1

class Value {
	int i= 15;
} 
public class TransferTest3{
	public void first(){
		int i = 5;
		Value v = new Value(); // v.i = 15
		v.i = 25; // v.i 从 15 变成了 25
		second(v,i); // 传入 
		System.out.println(v.i); // 20
	}
	
	public void second(Value v,int i){ // 接收地址和值
		i = 0;
		v.i = 20; // v.i 从25 变成了 20
		Value val = new Value(); // 新开辟一个地址 v.i = 15
		v = val; // v 指向新的地址,与外部first()中的v断联系了 v.i = 15
		System.out.println(v.i+" "+i); // 15 0
		
	}
	public static void main(String args[]){
		TransferTest3 test=new TransferTest3();
		test.first();
	}
	
	
}

根据这个图再解释一遍
main方法中,创建main方法的栈帧

  1. TransferTest3 test=new TransferTest3(); 在main方法的栈帧中压入test对象,并且指向堆中地址
  2. test.first(); 调用first

first方法中,创建first方法的栈帧

  1. int i = 5; // 在first方法的栈帧中压入 i = 5
  2. Value v = new Value(); // 在first方法的栈帧中压入v(0x5566) 堆中v.i = 15
  3. v.i = 25; // 堆中v.i 从 15 变成了 25
  4. second(v,i); // 传入 v(0x5566)和i = 5
  5. System.out.println(v.i); // 20 执行到这之前,second方法的栈帧已经弹出 ,second方法的栈帧中的变量被回收

second方法中,创建second方法的栈帧

  1. i = 0; // 在second方法的栈帧中把传入 i 从 5 改成 0
  2. v.i = 20; // 在second方法的栈帧中的 v(0x5566)的 v.i 从 25 变成了 20
  3. Value val = new Value(); // 在堆中新开辟一个地址 v(0x8899) v.i = 15
  4. v = val; // 在second方法的栈帧中 v 指向val的地址,与外部first()中的v断联系了 v.i = 15
  5. System.out.println(v.i+" "+i); // 15 0

练习2

public static void method(int a,int b){
	a = a * 10;
	b = b * 20;
	System.out.println("a=" + a);
	System.out.println("b=" + b);
	System.exit(0); //这个方法是用来结束当前正在运行中的java虚拟机 
	// 参数0表示正常退出;非零参数,表示是非正常退出。
}

练习3

 
//错误写法
for(int i= 0;i < arr.length;i++){
	arr[i] = arr[i] / arr[0]; // 首位数元素除了之后就变成1了,会出问题
}

//正确写法1
for(int i = arr.length –1;i >= 0;i--){
	arr[i] = arr[i] / arr[0];
}

//正确写法2
int temp = arr[0]; // 定义一个临时变量来放首位置元素
for(int i= 0;i < arr.length;i++){
	arr[i] = arr[i] / temp;
}

练习4

public class ArrayPrint {

	public static void main(String[] args) {
		int[] arr = new int[]{1,2,3};
        //传进去的是一个Object的对象
		System.out.println(arr);//地址值
		
		char[] arr1 = new char[]{'a','b','c'};
        //传进去的是一个数组,里面遍历数据了
		System.out.println(arr1);//abc
		// 出现上述现象可以查看System.out.println源码,因为两个数组调用的println方法不一样
	}
}

练习5

class Circle {
	double radius;	//半径
	
	//返回圆的面积
	public double findArea(){
		return radius * radius * Math.PI;
	}
}
// 测试类
public class PassObject {
	public static void main(String[] args) {
		PassObject test = new PassObject();
		Circle c = new Circle();
		test.printAreas(c, 5);
		System.out.println("now radius is:" + c.radius); // 6
	}
	
	public void printAreas(Circle c,int time){
		System.out.println("Radius Areas");
		//设置圆的半径
		for(int i = 1;i <= time ;i++){
			c.radius = i;
			System.out.println(c.radius + "tt" + c.findArea());
		}
		//重新赋值
		c.radius = time + 1;
	}
}


4. 面向对象特征之一:封装与隐藏

回顾一下面向对象的特征:封装、多态、继承、(抽象)

4.1 封装性的引入与体现

为什么需要封装?封装的作用和含义?
我要用洗衣机,只需要按一下开关和洗涤模式就可以了。有必要了解洗衣机内部的结构吗?有必要碰电动机吗?
我要开车,…
2. 我们程序设计追求“高内聚,低耦合”。
高内聚:类的内部数据操作细节自己完成,不允许外部干涉;
低耦合:仅对外暴露少量的方法用于使用。
3. 隐藏对象内部的复杂性,只对外公开简单的接口。

简单地说:便于外界调用,从而提高系统的可扩展性、可维护性。通俗的说,把该隐藏的隐藏起来,该暴露的暴露出来。这就是封装性的设计思想。

 class Animal{
	
	String name;
	private int age;
	private int legs; //腿的个数
	
	//对于属性的设置
	public void setLegs(int l){
		if(l >= 0 && l % 2 == 0){
			legs = l;
		}else{
			legs = 0;
		}
	}
	
	//对于属性的获取
	public int getLegs(){
		return legs;
	}
	
	public void eat(){
		System.out.println("动物进食");
	}
	
	public void show(){
		System.out.println("name = " + name + ",age = " + age + ",legs = " + legs);
	}
	
	//提供关于属性 age 的 get 和 set 方法
	public int getAge(){
		return age;
	}
	
	public void setAge(int a){
		age = a;
	}
}
public class AnimalTest {

	public static void main(String[] args) {
		Animal a = new Animal();
		a.name = "大黄";
//		a.age = 1; // 私有属性没办法直接复制
//		a.legs = 4;// The field Animal.legs is not visible
		
		a.show(); // name = 大黄,age = 0,legs = 0
		
		a.setLegs(-6); // 注意看方法
		
		a.show();// name = 大黄,age = 0,legs = 0
		
		a.setLegs(6);
		a.show();// name = 大黄,age = 0,legs = 6
		
		System.out.println(a.name); // 大黄
		System.out.println(a.getLegs()); // 6
	}
}


4.2 四种权限修饰符的理解与测试

Java 权限修饰符public、protected、default(缺省)、private 置于类的成员定义前,用来限定对象对该类成员的访问权限。

对于 class 的权限修饰只可以用 public 和 default(缺省)。

  • public 类可以在任意地方被访问。
  • default(friendly) 类只可以被同一个包内部的类访问。

protected 方法、属性 可以在本包和子类内部访问 (子类只能在自己的作用范围内访问自己继承的那个父类protected域,而无法到访问别的子类(同父类的亲兄弟)所继承的protected域)
private 方法、属性 只能在当前类内部访问

4 种权限都可以用来修饰类的内部结构:属性、方法、构造器、内部类

示例

package com.entity;

public class Order {
	private int orderPrivate;
	int orderDefault;
    protected int orderProtected;
	public int orderPublic;
	
    private void methodPrivate() {
        orderPrivate = 1;
        orderDefault = 2;
        orderProtected = 3;
        orderPublic = 4;
    }

    void methodDefault() {
        orderPrivate = 1;
        orderDefault = 2;
        orderProtected = 3;
        orderPublic = 4;
    }

    protected void methodProtected() {
        orderPrivate = 1;
        orderDefault = 2;
        orderProtected = 3;
        orderPublic = 4;
    }

    public void methodPublic() {
        orderPrivate = 1;
        orderDefault = 2;
        orderProtected = 3;
        orderPublic = 4;
    }
}

package com.entity;

public class OrderTest {

	public static void main(String[] args) {
		Order order = new Order();
		order.orderDefault = 1; // 同一个包下和当前类可以访问
		order.orderProtected = 1; // 同一个包下和当前类可以访问
		order.orderPublic = 2; // 同个工程下都能访问
		//出了 Order 类之后,私有的结构就不可调用了
//		order.orderPrivate = 3; //The field Order.orderPrivate is not visible
		order.methodDefault(); // 同一个包下和当前类可以访问
		order.methodProtected(); // 同一个包下和当前类可以访问
		order.methodPublic(); // 同个工程下都能访问
		//出了 Order 类之后,私有的结构就不可调用了
//		order.methodPrivate();//The method methodPrivate() from the type Order is not visible
	}
}

package com.test; 

import com.entity.Order;
// 注意这里不是同一个包下
public class OrderTest {

	public static void main(String[] args) {
		Order order = new Order();
		// 同个工程下都能访问
		order.orderPublic = 2;
		// 不同包下非子类,不能调用
		// order.orderProtected = 1; 
		//不在同一个包下之后,缺省的声明结构就不可调用了
//		order.orderDefault = 1;
		//出了 Order 类之后,私有的结构就不可调用了
//		order.orderPrivate = 3;//The field Order.orderPrivate is not visible
		// 同个工程下都能访问
		order.methodPublic();
		// 不同包下非子类,不能调用
		// order.methodProtected(); 
		//不在同一个包下之后,缺省的声明结构就不可调用了
//		order.methodDefault();
		//出了 Order 类之后,私有的结构就不可调用了
//		order.methodPrivate();//The method methodPrivate() from the type Order is not visible
	}
}

package com.test; 

import com.entity.Order;
// 注意这里不是同一个包下
public class OrderChild extends Order {

	public static void main(String[] args) {
		Order order = new Order();
		// 同个工程下都能访问
		order.orderPublic = 2;
		// 虽然是不同包下子类内,但是new出来的是Order实例,不能调用
		// order.orderProtected = 1; 
		//不在同一个包下之后,缺省的声明结构就不可调用了
//		order.orderDefault = 1;
		//出了 Order 类之后,私有的结构就不可调用了
//		order.orderPrivate = 3;//The field Order.orderPrivate is not visible
		// 同个工程下都能访问
		order.methodPublic();
		// 虽然是不同包下子类内,但是new出来的是Order实例,不能调用
		// order.methodProtected(); 
		//不在同一个包下之后,缺省的声明结构就不可调用了
//		order.methodDefault();
		//出了 Order 类之后,私有的结构就不可调用了
//		order.methodPrivate();//The method methodPrivate() from the type Order is not visible
		OrderChild orderChild = new OrderChild();
		// 不同包下子类内,是自己的实例,可以调用
		orderChild.orderProtected = 1; 
		orderProtected = 1;
		order.methodProtected(); 
		methodProtected();
	}
}
}

练习1

public class Person {
	private int age;
	public void setAge(int a){
		if(a < 0 || a > 130){
//			throw new RuntimeException("传入的数据据非法"); // 抛出运行时异常
			System.out.println("传入的数据据非法");
			return;
		}
		age = a;
	}
	public int getAge(){
		return age;
	}
	
	//绝对不能这样写!!!
	public int doAge(int a){
		age = a;
		return age;
	}
}

 // 测试类
public class PersonTest {

	public static void main(String[] args) {
		Person p1 = new Person();
//		p1.age = 1;	//编译不通过 
		
		p1.setAge(12);
		
		System.out.println("年龄为:" + p1.getAge());
	}
}


5. 类的结构之三:构造器(构造方法、constructor)的使用 5.1 构造器的理解

一、构造器的作用:

  1. 创建对象
  2. 初始化对象的属性

二、说明

  1. 如果没有显示的定义类的构造器的话,则系统默认提供一个空参的构造器。
  2. 定义构造器的格式:
    权限修饰符 类名(形参列表) { }
  3. 一个类中定义的多个构造器,彼此构成重载。
  4. 一旦显示的定义了类的构造器之后,系统不再提供默认的空参构造器。
  5. 一个类中,至少会有一个构造器。
class Person{
	//属性
	String name;
	int age;
	//构造器
	public Person(){
		System.out.println("Person()......");
	}
	
	public Person(String n){
		name = n;
	}
	
	public Person(String n,int a){
		name = n;
		age = a;
	}
	
	//方法
	public void eat(){
		System.out.println("人吃饭");
	}
	
	public void study(){
		System.out.println("人学习");
	}
}

public class PersonTest {

	public static void main(String[] args) {
		//创建类的对象:new + 构造器
		Person p = new Person();	//Person()这就是构造器 控制台会输出Person()......
		
		p.eat(); // 人吃饭
		
		Person p1 = new Person("Tom");
		System.out.println(p1.name); // Tom
	}
}

练习 1

public class Person {

	private int age;
	
	public Person(){
		age = 18;
	}
}

public class PersonTest {

	public static void main(String[] args) {
		Person p1 = new Person();

		System.out.println("年龄为:" + p1.getAge()); // 年龄为:18
	}
}

练习2

public class Person {

	private int age;
	private String name;
	
	public Person(){
		age = 18;
	}
	
	public Person(String n,int a){
		name = n;
		age = a;
	}
	
	public void setName(String n){
		name = n;
	}
	
	public String getName(){
		return name;
	}
	
	public void setAge(int a){
		if(a < 0 || a > 130){
//			throw new RuntimeException("传入的数据据非法");
			System.out.println("传入的数据据非法");
			return;
		}
		
		age = a;
		
	}
	
	public int getAge(){
		return age;
	}
}

public class PersonTest {

	public static void main(String[] args) {
		
		Person p2 = new Person("Tom",21);
		
		System.out.println("name = " + p2.getName() + ",age = " + p2.getAge());
	}
}

5.2 总结属性赋值的过程
class User{
	String name; // 默认初始化值
	int age = 1; // 显式初始化
	
	public User(){
		
	}
	
	public User(int a){
		age = a; // 构造器中赋值
	}
	
	public void setAge(int a){
		age = a;
	}
}
public class UserTest {

	public static void main(String[] args) {
		User u = new User();
		
		System.out.println(u.age);
		
		User u1 = new User(2);
		
		u1.setAge(3); // 通过"对象.方法" 或 “对象.属性”的方式,赋值
		
		System.out.println(u1.age);
	}
}

知识拓展:UML类图

+ 表示 public 类型, - 表示 private 类型, # 表示 protected 类型
方法的写法: 方法的类型(+、-)  方法名(参数名:参数类型) : 返回值类型
示例:+ getBalance() : double

6. 关键字:this 的使用 6.1 this 调用属性、方法、构造器

this 关键字的使用

  • this 可以用来修饰、调用:属性、方法、构造器

this 修饰属性和方法:this 理解为当前对象,或当前正在创建的对象。

  • 在类的方法中,我们可以使用this.属性或this.方法的方式,调用当前对象属性和方法。
  • 通常情况下,我们都选择省略this.。特殊情况下,如果方法的形参和类的属性同名,我们必须显式的使用this.变量的方式,表明此变量是属性,而非形参。
    例如:
	public void setName(String name){
		this.name = name;
	}

在类的构造器中,我们可以使用this.属性或this.方法的方式,调用正在创建的对象属性和方法。

  • 但是,通常情况下,我们都选择省略this.。特殊情况下,如果构造器的形参和类的属性同名,我们必须显式的使用this.变量的方式,表明此变量是属性,而非形参。
    例如:
	public Person(int age){
   	this.age = age;
   	this.eat();
   }

this 调用构造器
① 我们可以在类的构造器中,显式的使用this(形参列表)的方式,调用本类中重载的其他的构造器!
② 构造器中不能通过this(形参列表)的方式调用自己。
③ 如果一个类中声明了n个构造器,则最多有n -1个构造器中使用了this(形参列表)。(因为② )
④ this(形参列表)必须声明在类的构造器的首行!
⑤ 在类的一个构造器中,最多只能声明一个this(形参列表)。
例如:

	public Person(String name,int age){
		this(age);	//调用构造器的一种方式
	}
 class Person{
	
	private String name;
	private int age;
	
	public Person(){
		this.eat();
		String info = "Person 初始化时,需要考虑如下的 1,2,3,4...(共 40 行代码)";
		System.out.println(info);
	}
	
	public Person(String name){
		this();
		this.name = name;
	}
	
	public Person(int age){
		this();
		this.age = age;
	}
	
	public Person(String name,int age){
		this(age);	//调用构造器的一种方式
		this.name = name;
//		this.age = age;
	}
	
	public void setName(String name){
		this.name = name;
	}
	
	public String getName(){
		return this.name;
	}
	
	public void setAge(int age){
		this.age = age;
	}
	
	public int getAge(){
		return this.age;
	}
	
	public void eat(){
		System.out.println("人吃饭");
		this.study();
	}
	
	public void study(){
		System.out.println("学习");
	}
}
public class PersonTest {

	public static void main(String[] args) {
		Person p1 = new Person();
		
		p1.setAge(1);
		System.out.println(p1.getAge());
		
		p1.eat();
		System.out.println();
		
		Person p2 = new Person("jerry" ,20);
		System.out.println(p2.getAge());
	}
}


练习1 添加必要的构造器,综合运用this关键字和重载

public class Boy {

	private String name;
	private int age;
	
	public void setName(String name){
		this.name = name;
	}
	
	public String getName(){
		return name;
	}
	
	public void setAge(int ahe){
		this.age = age;
	}
	
	public int getAge(){
		return age;
	}
	
	public Boy(String name, int age) {
		this.name = name;
		this.age = age;
	}


	public void marry(Girl girl){
		System.out.println("我想娶" + girl.getName());
	}
	
	public void shout(){
		if(this.age >= 22){
			System.out.println("可以考虑结婚");
		}else{
			System.out.println("好好学习");
		}
	}
}

public class Girl {

	private String name;
	private int age;
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	
	public Girl(){
		
	}
	public Girl(String name, int age) {
		this.name = name;
		this.age = age;
	}
	
	public void marry(Boy boy){
		System.out.println("我想嫁给" + boy.getName());
	}
	
	public int compare(Girl girl){
//		if(this.age >girl.age){
//			return 1;
//		}else if(this.age < girl.age){
//			return -1;
//		}else{
//			return 0;
//		}
		
		return this.age - girl.age;
	}
	
}

public class BoyGirlTest {

	public static void main(String[] args) {
		
		Boy boy = new Boy("罗密欧",21);
		boy.shout();
		
		Girl girl = new Girl("朱丽叶", 18);
		girl.marry(boy);
		
		Girl girl1 = new Girl("祝英台", 19);
		int compare = girl.compare(girl1);
		if(compare > 0){
			System.out.println(girl.getName() + "大");
		}else if(compare < 0){
			System.out.println(girl1.getName() + "大");
		}else{
			System.out.println("一样的");
		}
	}
}

练习2

public class Account {

	private int id; // 账号
	private double balance; // 余额
	private double annualInterestRate; // 年利率

	public void setId(int id) {

	}

	public double getBalance() {
		return balance;
	}

	public void setBalance(double balance) {
		this.balance = balance;
	}

	public double getAnnualInterestRate() {
		return annualInterestRate;
	}

	public void setAnnualInterestRate(double annualInterestRate) {
		this.annualInterestRate = annualInterestRate;
	}

	public int getId() {
		return id;
	}

	public void withdraw(double amount) { // 取钱
		if(balance < amount){
			System.out.println("余额不足,取款失败");
			return;
		}
		balance -= amount;
		System.out.println("成功取出" + amount);
	}

	public void deposit(double amount) { // 存钱
		if(amount > 0){
			balance += amount;
			System.out.println("成功存入" + amount);
		}
	}

	public Account(int id, double balance, double annualInterestRate) {
		this.id = id;
		this.balance = balance;
		this.annualInterestRate = annualInterestRate;
	}
	
	
}

public class Customer {

	private String firstName;
	private String lastName;
	private Account account;

	public Customer(String f, String l) {
		this.firstName = f;
		this.lastName = l;
	}

	public String getFirstName() {
		return firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public Account getAccount() {
		return account;
	}

	public void setAccount(Account account) {
		this.account = account;
	}
	
}

public class CustomerTest {

	public static void main(String[] args) {
		Customer cust = new Customer("Jane" , "Smith");
		
		Account acct = new Account(1000,2000,0.0123);
		
		cust.setAccount(acct);
		
		cust.getAccount().deposit(100); //存入 100 成功存入:100.0
		cust.getAccount().withdraw(960); //取钱 960 成功取出:960.0
		cust.getAccount().withdraw(2000); //取钱 2000 余额不足,取款失败
		// Customer  [Smith,  Jane]  has  a  account:  id  is 1000, annualInterestRate  is 1.23%,  balance  is 1140.0
		System.out.println("Customer[" + cust.getLastName() + cust.getFirstName() + "]  has  a  account:  id  is "
				+ cust.getAccount().getId() + ",annualInterestRate  is " + cust.getAccount().getAnnualInterestRate() * 100 + "%,  balance  is "
				+ cust.getAccount().getBalance());
	}
}

练习3

public class Account {

	private double balance;

	public double getBalance() {
		return balance;
	}

	public Account(double initBalance){
		this.balance = initBalance;
	}
	
	//存钱操作
	public void deposit(double amt){
		if(amt > 0){
			balance += amt;
			System.out.println("存钱成功");
		}
	}
	
	//取钱操作
	public void withdraw(double amt){
		if(balance >= amt){
			balance -= amt;
			System.out.println("取钱成功");
		}else{
			System.out.println("余额不足");
		}
	}
}

public class Customer {

	private String firstName;
	private String lastName;
	private Account account;
	
	public String getFirstName() {
		return firstName;
	}
	public String getLastName() {
		return lastName;
	}
	public Account getAccount() {
		return account;
	}
	public void setAccount(Account account) {
		this.account = account;
	}
	public Customer(String f, String l) {
		this.firstName = f;
		this.lastName = l;
	}	
}

public class Bank {

	private int numberOfCustomers;	//记录客户的个数
	private Customer[] customers;	//存放多个客户的数组
	
	public Bank(){
		customers = new Customer[10];
	}
	
	//添加客户
	public void addCustomer(String f,String l){
		Customer cust = new Customer(f,l);
//		customers[numberOfCustomers] = cust;
//		numberOfCustomers++;
		customers[numberOfCustomers++] = cust;
	}

	//获取客户的个数
	public int getNumberOfCustomers() {
		return numberOfCustomers;
	}

	//获取指定位置上的客户
	public Customer getCustomers(int index) {
//		return customers;	//可能报异常
		if(index >= 0 && index < numberOfCustomers){
			return customers[index];
		}
		
		return null;
	}	
	
}

public class BankTest {

	public static void main(String[] args) {
		
		Bank bank = new Bank();
		
		bank.addCustomer("Jane", "Smith");	
		
		bank.getCustomers(0).setAccount(new Account(2000));
		
		bank.getCustomers(0).getAccount().withdraw(500);
		
		double balance = bank.getCustomers(0).getAccount().getBalance();
		
		System.out.println("客户: " + bank.getCustomers(0).getFirstName() + "的账户余额为:" + balance);
		
		System.out.println("***************************");
		bank.addCustomer("万里", "杨");
		
		System.out.println("银行客户的个数为: " + bank.getNumberOfCustomers());
		
	}
}

7. 关键字:package、import 的使用 7.1 关键字—package

一、package 关键字的使用

  1. 为了更好的实现项目中类的管理,提供包的概念
  2. 使用 package 声明类或接口所属的包,声明在源文件的首行
  3. 包(package)属于标识符,遵循标识符的命名规则、规范"见名知意"
  4. 每“.”一次,就代表一层文件目录。例如 package java.io;
public class PackageimportTest {

}

JDK中主要包的介绍

1.java.lang----包含一些 Java 语言的核心类,如 String、Math、Integer、System 和 Thread,提供常用功能
2.java.net----包含执行与网络相关的操作的类和接口。
3.java.io----包含能提供多种输入/输出功能的类。
4.java.util----包含一些实用工具类,如定义系统特性、接口的集合框架类、使用与日期日历相关的函数。
5.java.text----包含了一些 java 格式化相关的类
6.java.sql----包含了 java 进行 JDBC 数据库编程的相关类/接口
7.java.awt----包含了构成抽象窗口工具集(abstractwindowtoolkits)的多个类,这些类被用来构建和管理应用程序的图形用户界面(GUI)。B/S  C/S

8.2 关键字—import

二、import:导入

  • 1.在源文件中显式的使用import结构导入指定包下的类、接口
  • 2.声明在包的声明和类的声明之间
  • 3.如果需要导入多个结构,则并列写出即可
  • 4.可以使用xxx.*的方式,表示可以导入xxx包下的所有结构。
  • 5.如果导入的类或接口是java.lang包下的,或者是当前包下的,则可以省略此import语句。
  • 6.如果在代码中使用不同包下的同名的类。那么就需要使用类的全类名的方式指明调用的是哪个类。
  • 7.如果已经导入java.a包下的类。那么如果需要使用a包的子包下的类的话,仍然需要导入。
  • 8.import static组合的使用:调用指定类或接口下的静态的属性或方法.
import java.util.*;

import account2.Bank;

public class PackageimportTest {

	public static void main(String[] args) {
		String info = Arrays.toString(new int[]{1,2,3});
		
		Bank bank = new Bank();
		
		ArrayList list = new ArrayList();
		HashMap map = new HashMap();
		
		Scanner s = null;	
		
		System.out.println("hello");
		
		UserTest us = new UserTest();
		
	}
}

上一篇总目录下一篇
五、数组Java基础总目录未完待续
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/322370.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号