Day11_常用类

一. 内部类

内部类包含:

成员内部类、静态内部类、局部内部类、匿名内部类

什么是内部类?

概念:在一个类的内部再定义一个完整的类。

特点

  • 编译之后可生成独立的字节码文件
  • 内部类可直接访问外部类的私有成员,而不破坏封装。
  • 可为外部类提供必要的内部功能组件
class Outer {
    class Inner {
        
    }
}

↓ 编译后

📄 Outer$Inner.class

📄 Outer.class

成员内部类
  • 在类的内部定义,与实例变量、实例方法同级别的类。

  • 外部类的一个实例部分,创建内部类对象时,必须依赖外部类对象

    • Outer outer = new Outer();
      Outer.Inner in = outer.new Inner();
      
  • 当外部类、内部类存在重名属性时,会优先访问内部类属性

  • 成员内部类不能定义静态成员

public class Outer {
	public static void main(String[] args) {
        //====================================
		Inner inner = new Outer().new Inner(); 
        //====== 也可 Outer.Inner inner = new Outer().new Inner();
		inner.show();
	}
	
	String userName = "外部类";
	
	class Inner {
		String userName = "成员内部类";
		public void show() {
			System.out.println(userName);
			System.out.println(Outer.this.userName);
		}
	}
}

运行结果:

成员内部类
外部类

静态内部类
  • 不依赖外部类对象,可直接创建或通过类名访问可声明静态成员

  • 只能直接访问外部类的静态成员 (实例成员需实例化外部类对象)。

    • Outer.Inner inner = new Outer.Inner();
      Outer.Inner.show();
      
public class Outer2 {
	public static void main(String[] args) {
        //====================================
		Inner inner = new Inner();
        //====== 也可 Outer2.Inner inner = new Outer2.Inner();
		inner.show();
        //====== 也可 Outer2.Inner.show();
		System.out.println(Inner.age);
	}
	
	String userName = "外部类";
	
	static class Inner {
		public static int age = 10;
		String userName = "静态内部类";
		public void show() {
			System.out.println(userName);
			Outer2 outer2 = new Outer2();
			System.out.println(outer2.userName);
		}
	}
}

运行结果:

静态内部类
外部类
10

局部内部类
  • 定义在外部类方法中,作用范围和创建对象范围仅限于当前方法
  • 局部内部类访问外部类当前方法中的局部变量时,因无法保障变量的生命周期与自身相同,变量必须修饰为final
  • 限制类的使用范围。
public class Outer3 {
	public static void main(String[] args) {
		Outer3 outer3 = new Outer3();
		outer3.show();
	}
	
	String userName = "外部类";
	
	public void show() {
        //====== 作用范围和创建对象范围【仅限于当前方法】======
		class Inner {
			public void show() {
				System.out.println("局部内部类");
				System.out.println(Outer3.this.userName);
			}
		}
		Inner inner = new Inner();
		inner.show();
	}
}

运行结果:

局部内部类
外部类

匿名内部类
  • 没有类名的局部内部类(一切特征都与局部内部类相同)
  • 必须继承一个父类或者实现一个接口。
  • 定义类、实现类、创建对象的语法合并,只能创建一个该类的对象。

优点:减少代码量

缺点:可读性较差

public class Outer4 {
	public static void main(String[] args) {
		Outer4 outer4 = new Outer4();
		outer4.show();
	}
	
	String userName = "2";
	public void show() {
		System.out.println("一一一一一一一一一一");
		InnerInterface innerInterface = new InnerInterface() {
			
			@Override
			public void test() {
				System.out.println("匿名内部类-接口");
			}
		};
		innerInterface.test();
		System.out.println("一一一一一一一一一一");
		
		InnerTest innertest = new InnerTest() {
			
			@Override
			public void test() {
				System.out.println("匿名内部类-抽象");
			}
		};
		innertest.test();
	}	
}
public interface InnerInterface {
	void test();
}
public abstract class InnerTest {
	void test() {
	}
}

运行结果:

一一一一一一一一一一
匿名内部类-接口
一一一一一一一一一一
匿名内部类-抽象

二. Object类

  • 超类、基类。所有类的直接或间接父类,位于继承树的最顶层
  • 任何类,如没有书写extends显式继承某个类,都默认直接继承Object类,否则为间接继承。
  • Object类中所定义的方法,是所有对象都具备的方法
  • Object类型可以存储任何对象
    • 作为参数,可接受任何对象。
    • 作为返回值,可返回任何对象。
getClass()方法
public final native Class<?> getClass();
  • 返回引用中存储的实际对象类型。
  • 应用:通常用于判断两个引用中实际存储对象类型是否一致。
hashCode()方法
public native int hashCode();
  • 返回该对象的十进制的哈希码值。
  • 哈希算法根据对象的地址字符串数字计算出来int类型的数值。
  • 哈希码并不唯一,可保证相同对象返回相同哈希码,尽量保证不同对象返回不同哈希码。
toString()方法
public String toString() {
//  return getClass().getName() + "@" + Integer.toHexString(hashCode());
    }
  • 返回该对象的字符串表示 (表现形式)。
  • 应用:可以根据程序需求覆盖该方法,如:展示对象各个属性值。
equals()方法
public boolean equals(Object obj) {
//  return (this == obj);
    }
  • 默认实现为(this == obj),比较两个对象地址是否相同。

  • 应用:可进行覆盖,比较两个对象的内容是否相同。

  • equals()方法覆盖步骤
    • 比较两个引用是否指向同一个对象
    • 判断obj是否为null
    • 判断两个引用指向的实际对象类型是否一致
    • 强制类型转换
    • 依次比较各个属性值是否相同
finalize()方法
  • 当对象被判定为垃圾对象时,由JVM自动调用此方法,用以标记垃圾对象,进入回收队列。
  • 垃圾对象:没有有效引用指向此对象时,为垃圾对象。
  • 垃圾回收:由GC销毁垃圾对象,释放数据存储空间。
  • 自动回收机制:JVM的内存耗尽,一次性回收所有垃圾对象。
  • 手动回收机制:使用 System.gc(); 通知JVM执行垃圾回收。
【例】:
public class GCTest {

	public static void main(String[] args) {
		new Test();	// 1
		new Test();	// 2
		new Test();	// 3
		new Test();	// 4
		new Test();	// 5
		Test nTest = new Test();	// JVM认为接下来的程序有可能使用该引用变量,暂不回收
		
		System.out.println("辣鸡回收");
		System.gc();
	}
	
	@Override
	protected void finalize() throws Throwable {
		System.out.println(this + "被回收了");
	}

}

运行结果:

辣鸡回收
com.gc.Test@1cc2ea3f被回收了
com.gc.Test@1034bb5被回收了
com.gc.Test@7f5f5897被回收了
com.gc.Test@11cfb549被回收了
com.gc.Test@5b86d4c1被回收了

三. 包装类

什么是包装类?
  • 基本数据类型所对应的引用数据类型。
  • Object可统一所有数据,包装类的默认值是null。
包装类对应
基本数据类型包装类型
byteByte
shortShort
intInteger
longLong
floatFloat
doubleDouble
booleanBoolean
charCharacter
类型转换与装箱、拆箱
  • 8种包装类提供不同类型间的转方式:
    • Number父类中提供6个共性方法。
    • parseXXX()静态方法 (除了Character)。
    • valueOf()静态方法。

【注】:需保证类型兼容,否则抛出NumberFormatException异常。

【注】:JDK 5.0之后,自动装箱、拆箱。基本数据类型和包装类自动转换。

整数缓冲区
  • Java预先创建了256个常用的整数包装类型对象。(-128~127)
  • 在实际应用当中,对已创建的对象进行复用。.
【例】:
public class IntegerTest {

	public static void main(String[] args) {
		Integer integer1 = new Integer(1);
		Integer integer2 = new Integer(2);
		System.out.println(integer1 == integer2);
		Integer integer3 = 100;
		Integer integer4 = Integer.valueOf(100);
		System.out.println(integer3 == integer4);
		Integer integer5 = 128;
		Integer integer6 = Integer.valueOf(128);
		System.out.println(integer5 == integer6); // 引用类型==比较地址,超过缓冲区后不能用==比较,应该用.equals()方法比较。
        System.out.println(integer5.equals(integer6));
		
	}
}

运行结果:

false
true
false
true

四. String类

  • Java程序中的所有字符串文本(例如“abc”)都是此类的实例。

  • 字符串字面值是常量创建之后不可改变

  • 常用创建方式:

    • String str1 = "Hello";
      String str2 = new String("World");
      
常用方法
public char charAt(int index); // 根据下标获取字符。
public boolean contains(String str); // 判断当前字符串中是否包含str。
public char[] toCharArray(); // 将字符串转换成数组。
public int indexOf(String str); // 查找str首次出现的下标:存在,则返回改下标;不存在,则返回-1.
public int length(); // 返回字符串的长度。
public String trim(); // 去掉字符串前后的空格。
public String toUpperCase(); // 将小写转成大写。
public boolean endWith(String str); // 判断字符串是否以str结尾。
public String replace(char oldChar, char newChar); // 将旧字符串替换成新字符串。
public String[] split(String str); // 根据str做拆分。
public String substring(int beginIndex, int endIndex); // 在字符串中截取一个子字符串。
【例】:

需求:

已知 String str = “this is a text”;

  • 将str中的单词单独获取出来
  • 将str中的text替换为practice
  • 在text前面插入一个easy
  • 将每个单词的首字母改为大写
public class StrTest {
	public static void main(String[] args) {
		String str = "this is a text";	
		System.out.println("== 01 =========");
		for (String e : str.split(" ")) {
			System.out.println(e);
		}
		System.out.println("== 02 =========");
		System.out.println(str.replace("text", "practice"));
		System.out.println("== 03 =========");
		System.out.println(str.replace("text", "easy text"));
		System.out.println("== 04 =========");
		String[] temp = str.split(" ");
		String result = "";
		for (String e : temp) {
			result += e.substring(0, 1).toUpperCase();
			result += e.substring(1);
			result += " ";
		}
		System.out.println(result);
	}
}

运行结果:

== 01 =========
this
is
a
text
== 02 =========
this is a practice
== 03 =========
this is a easy text
== 04 =========
This Is A Text

可变字符串

概念:可在内存中创建可变的缓冲空间,存储频繁改变的字符串。

常用方法
public StringBuilder append(String str)
StringBuilder:

可变长字符串,JDK5.0提供,运行效率快,线程不安全。

StringBuffer:

可变长字符串,JDK1.0提供,运行效率慢,线程安全。

【注】:

存储频繁改变字符串时,StringBuilder的速度原快于String。

public class StingDemo {
	public static void main(String[] args) {
		long start = System.currentTimeMillis();
		String tempString = new String();	//=============
		for (int i = 0; i < 99999; i++) {
			tempString += i;	//=============
		}
		long end = System.currentTimeMillis();
		System.out.println(end - start);
	}
}

运行结果:

23820

public class StingBuilderDemo {
	public static void main(String[] args) {
		long start = System.currentTimeMillis();
		StringBuilder tempString = new StringBuilder(); //=============
		for (int i = 0; i < 99999; i++) {
			tempString.append(i);	//=============
		}
		long end = System.currentTimeMillis();
		System.out.println(end - start);
	}
}

运行结果:

13

五. BigDecimal类

public class TestBigDecimal {
    public static void main(String[] args) {
        double d1 = 1.0;
        double d2 = 0.9;
        System.out.println(d1 - d2);
    }
}

运行结果:

0.09999999999999998

很多实际应用中需要精确运算,而double是近似值存储,不符合要求。需要借助 BigDecimal

位置:java.math包中。

作用:精确计算浮点数。

创建方式

BigDecimal bd = new BigDecimal("1.0");

方法

BigDecimal add(BigDecimal bd); // 加
BigDecimal subtract(BigDecimal bd); // 减
BigDecimal multiply(BigDecimal bd); // 乘
BigDecimal divide(BigDecimal bd); // 除
【例】:
public class TestBigDecimal {
    public static void main(String[] args) {
        BigDecimal bd1 = new BigDecimal("1.0");
        BigDecimal bd2 = new BigDecimal("0.9");
        
        BigDecimal result1 = bd1.add(bd2);
        System.out.println("d1+d2="+result1);
        BigDecimal result2 = bd1.subtract(bd2);
        System.out.println("d1-d2="+result2);
        BigDecimal result3 = bd1.multiply(bd2);
        System.out.println("d1*d2="+result3);
        BigDecimal result4 = bd1.divide(bd2);
        System.out.println("d1/d2="+result4); // 抛出异常
    }
}

运行结果

d1+d2=1.9
d1-d2=0.1
d1*d2=0.90
Exception in thread “main” java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.

【注】:进行除法运算时,如果不能准确的计算除结果时需要指定保留的位数和取舍方式。

除法:
BigDecimal divide(BigDecimal bd, int scale, RoundingMode mode); // 除

参数scale:指定精确到小数点后几位。

参数mode

  • 指定小数部分的取舍模式,通常采用四舍五入的模式。
  • 取值为BigDecimal.ROUND_HALF_UP。

六. 时间相关类

Date
  • Date表示特定的瞬间,精确到毫秒。
  • Date类中的大部分方法都已经被Calendar类中的方法所取代。

【注】

​ 1秒 = 1000毫秒

​ 1毫秒 = 1000微秒

​ 1微秒 = 1000纳秒

Calendar
  • Calendar提供了获取或设置各种日历字段的方法。
  • protected Calendar() 构造方法为protected修饰,无法直接创建该对象。
  • 其他方法
static Calendar getInstance();// 使用默认时区和区域获取日历
void set(int year, int month, int date,int hourofday, int minute,int secong); // 设置日历的年、月、日、时、分、秒
int get(int field); // 返回给定日历字段的值。字段比如年、月、日等
void setTime(Date date); // 用给定的Date设置此日历的时间。Date—Calendar
Date getTime(); // 返回一个Date表示此日历的时间。Calendar—Date
void add(int field, int amount); // 按照日历的规则,给指定字段添加或减少时间量
long getTimeInMillies(); // 毫秒为单位返回该日历的时间值
【例】:
import java.util.Calendar;

public class CalendarTest {
	public static void main(String[] args) {
		Calendar calendar = Calendar.getInstance();
		int year = calendar.get(Calendar.YEAR);
		int month = calendar.get(Calendar.MONTH);
		int day = calendar.get(Calendar.DAY_OF_MONTH);
		int hour = calendar.get(Calendar.HOUR_OF_DAY);
		int minute = calendar.get(Calendar.MINUTE);
		int second = calendar.get(Calendar.SECOND);
		
		System.out.printf("%d年 %d月 %d日,%d:%d:%d" 
				,year ,month+1 ,day ,hour ,minute ,second);
	}
}

运行结果:

2020年 8月 11日,19:47:55
在这里插入图片描述

SimpleDateFormat
  • SimpleDateFormat是以语言环境有关的方式来格式化和解析日期的类。
  • 进行格式化(日期->文本)、解析(文本->日期)。
  • 常用的时间模式字母
字母日期或时间示例
y2019
M年中月份08
d月中天数10
H1天中小时数(0-23)22
m分钟16
s59
S毫秒367
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class CalendarDemo {
	public static void main(String[] args) throws ParseException {
		System.out.println(new SimpleDateFormat("yy-MM-dd HH:mm:ss").format(new Date()));
		System.out.println(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));
	
		Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2021-08-11 19:59:59");
		System.out.println(date);
			
	}
}

运行结果:

20-08-11 20:00:28
2020-08-11 08:00:28
Wed Aug 11 19:59:59 CST 2021

System

System系统类,主要用于获取系统的属性数据和其他操作。

static void arraycopy(...); // 复制数组
static long currentTimeMillis(); // 获取当前系统时间,返回的是毫秒值
static void gc(); // 建议JVM赶快启动垃圾回收器回收垃圾
static void exit(int status); // 退出JVM,如果参数是0表示正常退出JVM;非0表示异常退出JVM

总结

  • 内部类
    • 在一个类的内部再定义一个完整的类。包含:成员内部类、静态内部类、局部内部类、匿名内部类。
  • Object类
    • 所有类的直接或间接父类,可存储任何对象。
  • 包装类
    • 基本数据类型所对应的引用数据类型,可以使Object统一所有数据。
  • String类
    • Java程序中的所有字符串文本(例如:”abc“) 都是此类的实例。字符串字面值是常量,创建之后不可改变。
  • BigDecimal
    • 可精确计算浮点数
  • 时间相关类
    • Date、Calendar、SimpleDateFormat、System
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值