常用类学习
内部类
在一个类的内部再定义一个完整的类
-
编译之后可以生成独立的字节码文件
-
内部类可以直接访问外部类的私有成员,而不破坏封装性
-
可为外部类提供必要的内部功能组件
package com.classplus;public class Demo01 { private String name;class Header{//内部类可以直接访问外部类的私有成员public void show(){System.out.println(name);}} }
成员内部类
在类的内部定义,与实例变量、实例方法同级别的类
是外部类的一个实力部分,创建内部类对象时,必须依赖外部类对象
Outer out=new Outer();
Inner in=out.new Inner();
当外部类、内部类存在重名属性施,会优先访问内部类的属性
成员内部类不能定义静态成员(但是可以包含静态常量static final)
package com.classplus;//外部类
public class Outer {//实例变量private String name="张三";private int age=20;//内部类,前面可以加访问修饰符class Inner{private String address="北京";private String phone="110";//同名优先访问内部类private String name="李四";//方法public void show(){//打印外部类的属性,相同是要想访问外部需要Outer.this.System.out.println(Outer.this.name);System.out.println(age);//打印内部类的属性System.out.println(address);System.out.println(phone);}}
}
package com.classplus;public class Test {public static void main(String[] args) {//创建一个外部类对象// Outer outer = new Outer();//创建内部类对象// Outer.Inner inner = outer.new Inner();//一步到位Outer.Inner inner = new Outer().new Inner();inner.show();}
}
静态内部类
不依赖外部类对象,可直接创建或通过类名访问,可声明静态成员
只能直接访问外部类的静态成员(实例成员需要实例化外部类对象)
Outer.Inner inner = new Outer.Inner();
inner.show();
package com.classplus.Demo02;//外部类
public class Outer {private String name="xxx";private int age=18;//静态内部类,它的级别和外部类相同static class Inner{private String address="上海";private String phone="111";//静态成员private static int count=1000;public void show(){//调用外部类的属性//创建外部类对象Outer outer = new Outer();//调用外部类对象的属性System.out.println(outer.name);System.out.println(outer.age);//调用静态内部类属性System.out.println(address);System.out.println(phone);//调用静态内部类的静态属性System.out.println(Inner.count);}}
}
package com.classplus.Demo02;public class Test {public static void main(String[] args) {Outer.Inner inner = new Outer.Inner();inner.show();}
}
局部内部类
定义在外部类方法中,作用范围和创建对象范围仅限于当前方法
局部内部类访问外部类当前方法中的局部变量时,因无法保障变量的生命周期与自身相同,变量必须修饰为final
限制类的使用范围
package com.classplus.Demo03;//外部类
public class Outer {private String name="刘德华";private String age="20";public void show(){//定义局部变量String address="深圳";//局部内部类:不能加任何访问修饰符class Inner{//局部内部类的属性private String phone="213128318";private String email="123456@qq.com";//private static final int count=1000;private void show2(){//访问外部类的属性,直接访问,这里Outer.this.可省略System.out.println(Outer.this.name);System.out.println(Outer.this.age);//访问内部类的属性,this.可省略System.out.println(this.phone);System.out.println(this.email);//访问局部变量,jdk1.7要求,变量必须是常量final,jdk1.8自动添加finalSystem.out.println(address);}}//创建局部内部类对象Inner inner = new Inner();inner.show2();}
}
package com.classplus.Demo03;public class Test {public static void main(String[] args) {Outer outer = new Outer();outer.show();}
}
匿名内部类
没有类名的局部内部类(一切特征都与局部内部类相同)
必须继承一个父类或者实现一个接口
定义类、实现类、创建对象的语法合并,只能创建一个该类的对象
减少代码量
可读性较差
package com.classplus.Demo04;public interface Usb {//定义了一个服务方法void service();
}
package com.classplus.Demo04;public class Mouse implements Usb {@Overridepublic void service() {System.out.println("链接电脑成功,鼠标开始工作");}
}
package com.classplus.Demo04;public class Test {public static void main(String[] args) {//创建一个接口类的变量// Usb usb = new Mouse();// usb.service();//局部内部类
// class Fan implements Usb{
//
// @Override
// public void service() {
// System.out.println("连接电脑成功,风扇开始工作");
// }
// }//使用局部内部类创建对象
// Usb usb = new Fan();
// usb.service();//匿名内部类来优化(相当于创建了一个局部内部类)Usb usb = new Usb(){@Overridepublic void service() {System.out.println("连接电脑成功,风扇开始工作");}};usb.service();}
}
Object类
超类、基类,所有类的直接或者间接父类,位于继承树的最顶层
getClass()方法
返回引用中储存的实际对象类型
通常用于判断两个引用中实际存储对象类型是否一致
package com.classplus.Demo05;public class Student {private String name;private int age;public Student(String name, int age) {this.name = name;this.age = age;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}
}
package com.classplus.Demo05;public class Test {public static void main(String[] args) {Student s1 = new Student("aaa",20);Student s2 = new Student("bbb",22);//判断s1和s2是不是同一个类型Class class1=s1.getClass();Class class2=s2.getClass();if (class1==class2){System.out.println("s1,s2属于同一个类型");}else {System.out.println("s1,s2不属于同一个类型");}}
}
hashCode()方法
返回该对象的哈希码值
//hashCode方法
System.out.println(s1.hashCode());
System.out.println(s2.hashCode());
toString()方法
返回该对象的字符串标识
package com.classplus.Demo05;public class Student {private String name;private int age;public Student(String name, int age) {this.name = name;this.age = age;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}
//重写方法@Overridepublic String toString() {return "name='" + name + '\'' + ", age=" + age;}
}
//toString方法
System.out.println(s1.toString());
System.out.println(s2.toString());
equals()方法
比较两个对象地址是否相等
equals()方法覆盖步骤
-
比较两个引用是否指向同一个对象
-
判断obj是否为null
-
判断两个引用指向的实际对象类型是否一致
-
强制类型转换
-
依次比较各个属性值是否相同
@Overridepublic boolean equals(Object obj) {//1判断两个对象是否是同一个if(this==obj){return true;}//2判断obj是否为nullif (obj==null){return false;}//3判断是否是同一类型 // if (this.getClass()==obj.getClass()){ // // }//instanceof判断对象是否是某种类型if (obj instanceof Student){//4强制类型转换Student s=(Student) obj;//5比较属性if (this.name.equals(s.getName())&&this.age==((Student) obj).age){return true;}}return false;}
//equals方法,判断两个对象是否相等
System.out.println(s1.equals(s2));Student s3 = new Student("小明",17);
Student s4 = new Student("小明",17);
System.out.println(s3.equals(s4));
finalize()方法(回收)
@Overrideprotected void finalize() throws Throwable {System.out.println(this.name+"对象被回收了");}
}
public class Test2 {public static void main(String[] args) {Student s1 = new Student("aaa",20);Student s2 = new Student("bbb",20);Student s3 = new Student("ccc",20);Student s4 = new Student("ddd",20);Student s5 = new Student("eee",20);new Student("aaa",20);new Student("bbb",20);new Student("ccc",20);new Student("ddd",20);new Student("eee",20);//回收垃圾System.gc();System.out.println("回收垃圾");}
}
包装类
基本数据类型所对应的引用数据类型
Object可统一所有数据,包装类的默认值是null
基本类型 包装类型
byte Byte
short Short
int Integer
long Long
float Float
double Double
boolean Boolean
char Character
类型转换与装箱拆箱
.valueof()静态方法
package com.classplus.Demo06;public class 包装类 {public static void main(String[] args){int num =10;//类型转换:装箱,基本数据类型转成引用数据类型//基本数据类型int num1=18;//使用Integer类型创建对象Integer integer1 = new Integer(num1);Integer integer2 = Integer.valueOf(num1);System.out.println("装箱");System.out.println(integer1);System.out.println(integer2);//类型转换:拆箱,引用数据类型转成基本数据类型Integer integer3 = new Integer(100);int num2=integer3.intValue();System.out.println("拆箱");System.out.println(num2);//jdk1.5之后,提供自动装箱和拆箱int age=30;//自动装箱Integer integer4=age;System.out.println("自动装箱");System.out.println(integer4);//自动c拆箱int age2=integer4;System.out.println("自动拆箱");System.out.println(age2);}}
字符串和基本类型的转换
.parseXXX()静态方法
//基本类型转换成字符串
int n1=15;
//1使用+号
String s1=n1+"";
//2使用Integer中的toString()方法
String s2=Integer.toString(n1,16);//radix标识转换的禁止
System.out.println(s1);
System.out.println(s2);//字符串转换成基本类型
String str="150";
//使用Integer。parseXXX()
int n2=Integer.parseInt(str);
System.out.println(n2);//boolean字符串形式转成基本类型,“true”-->true 非“true”-->false
String str2="true";
boolean b1=Boolean.parseBoolean(str2);
System.out.println(b1);
Integer缓冲区
Java预先创建了256个常用的整数包装类型对象,-128到127之间,如果不在这个范围之间会new Integer(i)
package com.classplus.Demo06;public class 缓冲区 {public static void main(String[] args) {//面试题Integer integer1 = new Integer(100);Integer integer2 = new Integer(100);System.out.println(integer1==integer2);//falseInteger integer3=Integer.valueOf(100);//自动装箱Integer.valueOfInteger integer4=100;System.out.println(integer3==integer4);//trueInteger integer5=200;//自动装箱Integer integer6=200;System.out.println(integer5==integer6);//false}
}
String类
字符串是常量,创建之后不可改变
字符串字面值储存在字符串池中,可以共享
String s="Hello".产生一个对象,字符串池中存储
String s=new String("Hello").产生两个对象,堆,池中各存储一个
package com.classplus.Demo06;public class StringClass {public static void main(String[] args) {String name="hello";//"hell"常量存储在字符串中name="张三";//张三赋值给name,给字符串赋值时,并没有修改数据,而是重新开辟一个空间String name2="张三";//字符串的另一个创建方式,new String()String str=new String("java是最好的编程语言");String str2=new String("java是最好的编程语言");System.out.println(str==str2);//false存放地址不一样System.out.println(str.equals(str2));//true}
}
常用方法
public int length();返回字符串的长度
public char charAt(int index):根据下标获取字符
public boolean contains(String str):判断当前字符串中是否包含str
//字符串方法的使用
//length()返回字符串的长度
//charAt(int index);返回某个位置的字符
//contains(String str):判断当前字符串中是否包含str
String content="java是世界上最好的编程语言";
System.out.println(content.length());
System.out.println(content.charAt(content.length()-1));//最后一个的字符
System.out.println(content.contains("java"));
public char[] toCharArray():将字符串转换为数组
public int indexOf (String str):查找str首次出现的下标,存在,则返回改下标,不存在,则返回-1
public int lastIndexOf (String str)查找字符串在当前字符串中最后一次出现的下标索引
//toCharArray():将字符串转换为数组
//indexOf (String str)查找str首次出现的下标,存在,则返回改下标,不存在,则返回-1
//lastIndexOf (String str)查找字符串在当前字符串中最后一次出现的下标索引
System.out.println(Arrays.toString(content.toCharArray()));
System.out.println(content.indexOf("java"));
System.out.println(content.indexOf("java",4));
System.out.println(content.lastIndexOf("java"));
public String trim :去掉字符串前后的空格
public String toUpperCase():将小写转换成大写
public boolean endWith(String str):判断字符串是否以str结尾
//trim :去掉字符串前后的空格
//toUpperCase():将小写转换成大写,toLowerCase()大写到小写
//endWith(String str):判断字符串是否以str结尾,startWith(String str)判断开头
String content2=" Hello World ";
System.out.println(content2.trim());
System.out.println(content2.toUpperCase());
String filename="hello.java";
System.out.println(filename.endsWith("java"));
System.out.println(filename.startsWith("hello"));
public String replace(char oldChar,char newChar):将旧字符串替换成新字符串
public String[] split(String str):根据str做拆分
//replace(char oldChar,char newChar):用新字符或字符串替换旧的字符或字符串
//split(String str):根据str做拆分
System.out.println(content.replace("java", "php"));
String say="java is the best programing language,java xiang";String[] arr=say.split("[ ,]");//空格和逗号
System.out.println(arr.length);
for (String string:arr){System.out.println(string);//遍历数组
}
补充
//补充两个方法equals、compareTo();比较大小
String s1="hello";
String s2="HELLO";
System.out.println(s1.equals(s2));
System.out.println(s1.equalsIgnoreCase(s2));//忽略大小写的比较String s3="abc";//a97
String s4="xyz";//x120
System.out.println(s3.compareTo(s4));//-23String s5="abc";
String s6="abcxyz";
System.out.println(s5.compareTo(s6));//比较长度,-3
案例
String str=“this is a text”
- 将str中的单词单独获取出来
- 将text替换为practice
- 在text前面插入一个easy
- 将每个单词首字母改为大写
package com.classplus.Demo06;public class String案例 {/*String str=“this is a text”1. 将str中的单词单独获取出来
2. 将text替换为practice
3. 在text前面插入一个easy
4. 将每个单词首字母改为大写*/public static void main(String[] args) {String str="this is a text";//1String[] arr=str.split(" ");System.out.println("1. 将str中的单词单独获取出来");for (String string:arr){System.out.println(string);//遍历数组}//2System.out.println("2. 将text替换为practice");System.out.println(str.replace("text","practice"));//3System.out.println("3. 在text前面插入一个easy");System.out.println(str.replace("text","easy text"));//4System.out.println("4. 将每个单词首字母改为大写");for (int i = 0; i < arr.length; i++) {char first= arr[i].charAt(0);//把第一个字符转成大写char upperfirst=Character.toUpperCase(first);String news=upperfirst+arr[i].substring(1);//从下标第1个开始取值System.out.println(news);}}
}
可变字符串
StringBuffer:可变长字符串,jdk1.0提供,运行效率慢,线程安全
StringBuilder:可变长字符串,jdk5.0提供,运行效率快慢,线程不安全
package com.classplus.Demo06;
//StringBuffer和StringBuilder
public class 可变字符串 {public static void main(String[] args) {StringBuffer stringBuffer = new StringBuffer();//1.append(),追加stringBuffer.append("java是世界第一");System.out.println(stringBuffer.toString());stringBuffer.append("java真香");System.out.println(stringBuffer.toString());//2.insert()添加stringBuffer.insert(0,"我在最前面");System.out.println(stringBuffer.toString());//3.replace();替换stringBuffer.replace(0,5,"hello");System.out.println(stringBuffer.toString());//4.delete();删除stringBuffer.delete(0,5);System.out.println(stringBuffer.toString());//清空stringBuffer.delete(0,stringBuffer.length());System.out.println(stringBuffer.toString());}
}
BigDecimal
double是近似值储存,需要精确运算时,需要借助BigDecimal
package com.classplus.Demo06;import javafx.util.converter.BigDecimalStringConverter;import java.math.BigDecimal;public class 精确运算 {public static void main(String[] args) {double d1=1.0;double d2=0.9;System.out.println(d1-d2);//0.09999999999//BigDecimal,大的浮点数精确计算BigDecimal bd=new BigDecimal(1.0);BigDecimal bd2=new BigDecimal(0.9);//减法subtractBigDecimal r1=bd.subtract(bd2);System.out.println(r1);//加法。add//乘法。multiply//除法divideBigDecimal r2=new BigDecimal(10).divide(new BigDecimal(3),2,BigDecimal.ROUND_HALF_UP);//保留两位小数,四舍五入System.out.println(r2);}
}
Date
表示特定的瞬间
{public static void main(String[] args) {//创建Date对象//现在Date date1 = new Date();System.out.println(date1.toString());System.out.println(date1.toLocaleString());//昨天Date date2 = new Date(date1.getTime()-60*60*24*1000);//减去一天的毫秒数System.out.println(date2);//after,beforeSystem.out.println(date1.after(date2));System.out.println(date1.before(date2));//比较compareTo();System.out.println(date1.compareTo(date2));//date1-date2//比较是否相等equals()System.out.println(date1.equals(date2));}
}
Calendar
构造方法
protected Calendar()
package com.classplus.Demo06;import java.util.Calendar;public class 新时间 {public static void main(String[] args) {//1创建Calendar对象Calendar calendar=Calendar.getInstance();System.out.println(calendar.getTime().toLocaleString());System.out.println(calendar.getTimeInMillis());//获取毫秒值//2获取时间信息//获取年,月,日,时,分,秒,月是从0-11月的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);//HOUR:12小时,HOUR_OF_DAY:24小时int minute=calendar.get(calendar.MINUTE);int second=calendar.get(calendar.SECOND);System.out.println(year+"年"+month+"月"+day+"日"+hour+"时"+minute+"分"+second+"秒");//3修改时间Calendar calendar2=Calendar.getInstance();calendar2.set(Calendar.DAY_OF_MONTH,5);System.out.println(calendar2.getTime().toLocaleString());//4add方法修改calendar2.add(Calendar.HOUR,1);System.out.println(calendar2.getTime().toLocaleString());//5补充方法int max=calendar2.getActualMaximum(Calendar.DAY_OF_MONTH);//最大天数int min=calendar2.getActualMinimum(Calendar.DAY_OF_MONTH);//最小天数System.out.println(max);System.out.println(min);}}
SimpleDateFormat
package com.classplus.Demo06;import java.text.SimpleDateFormat;
import java.util.Date;public class 格式化时间 {public static void main(String[] args)throws Exception {//1.创建SimpleDateFormat对象 y年 M月SimpleDateFormat sdf=new SimpleDateFormat("yyyy年MM月dd日HH:mm:ss");//2.创建一个DateDate date=new Date();//格式化date,把日期转成字符串String str=sdf.format(date);System.out.println(str);//解析,把字符串转换成日期Date date2=sdf.parse("1990年05月01日:05:18:30");//有异常,先抛出System.out.println(date2);}
}
System类
用于获取系统的属性数据和其他操作,构造方法是私有的
arraycopy():数组复制
currentTimeMillis():获取当前系统时间,返回的是毫秒值
gc():建议jvm赶快启动垃圾回收器回收垃圾
exit():退出jvm,如果参数是0表示正常退出jvm,非0表示异常退出jvm
package com.classplus.Demo06;public class System类 {public static void main(String[] args) {//1.arraycopy():数组复制//src,源数组//srcPos:从那个位置开始复制 0//dest:目标数组//destPos:目标数组的位置//length:复制个数int[] arr={1,2,3,4,5,6,7,8,9};int[] dest=new int[9];System.arraycopy(arr,0,dest,0,9);for (int i = 0; i < dest.length;i++) {System.out.println(dest[i]);}//2。currentTimeMillis():获取当前系统时间,返回的是毫秒值System.out.println(System.currentTimeMillis());long start=System.currentTimeMillis();//开始时间for (int i = 0; i < 999; i++) {for (int j = 0; j < 999; j++) {int result=i+j;}}long end=System.currentTimeMillis();//结束时间System.out.println("用时"+(end-start));new Student("aaa",19);new Student("bbb",19);new Student("ccc",19);//3.gc():建议jvm赶快启动垃圾回收器回收垃圾System.gc();//告诉垃圾回收器回收//4.exit():退出jvm,如果参数是0表示正常退出jvm,非0表示异常退出jvmSystem.exit(0);//结束了System.out.println("程序结束了");//没有执行}}