Java学习笔记

JAVA面向对象,万物皆对象(我就是没找到)

使用的IDE:IDEA IDE

Tips:

ctrl + / //Quickly add comment to selected line

三大特性:封装,继承,多态

关键字:class

什么叫类的实例化:

  1. (C++用法)使用new关键字创建对象
  2. 使用Class类的newInstance方法(反射机制)

例:

Student student = Student.class.newInstance();
  1. 使用Constructor类的newInstance方法(反射机制)
Constructor<Student> constructor = Student.class
.getConstructor(Integer.class);
Student stu3 = constructor.newInstance(123);

全例:

public class Person{
	String name;
	int age;
	public void speak(){
		System.out.println(Fuck You!);
	}
	public static void main(String[] args){
		//定义一个Person类的对象张三
		Person zhangsan;
		//实例化对象(相当于开辟了一块新的空间)
		zhangsan = new Person();
	}
}

注意:主函数

public static void main(String[] args)

必须传递命令行参数,否则无法编译运行

方法

不固定参数

*int speak(String name, int age, String ...hobbies){    
	//Parameter    
	System.out.println("I am "+name+",Age: "+age);    
	for(String hobby:hobbies){        
		System.out.println(hobby+" ");    
	}    
	int totalHobbies = hobbies.length;    
	return totalHobbies;
}*

方法的值传递和引用传递

方法的重载:类似于类的重载,体现了java的多态性

static静态方法和普通方法

调用方式:

  1. 类名.方法名(这个是静态方法调用)
  2. 对象.方法名(这个能普通方法或静态方式,调用静态方法会警告)

java与C++数据类型不同之处:long类型(对应C/C++中的long int),boolen类型(对应C/C++中的bool)

Java中的package和import语句

为便于管理大型软件系统中数目众多的类,解决类名的冲突问题,Java引入package机制,提供类的多重类命名空间。(类似于C++中的命名空间)

package作为Java源文件的第一条语句,指明该文件中定义的类所在的包

Java从键盘中读入数据(两种方法):

方法一:

int value;
value = SimpleInput.readInt();

方法二:

Scanner in =new Scanner(System.*in*);
int a=in.nextInt();

内部类

内部类定义:在类的内部定义类

内部类可以使用外部类属性

Outer.Inner inner = outer.new Inner();

外部类的类名.内部类的类名

外部类对象.内部类对象

(相当于都加了一个前缀)

匿名类:无返回值的类

//定义:
public Demo2(){    
	System.*out*.println("Structure method1");
}
//调用:
new Demo2();        
//Initialize a object, Anonymous class

代码块

普通代码类,构造块,静态构造块

代码运行的时候一定要先进入通用构造块,再进入构造块

执行顺序:静态 -> 通用 -> 方法

静态构造块(运行后,只执行一次)

static {    
	System.*out*.println("Static structure blocks");
}

通用构造块(类似于C++的默认构造函数)

{    
	System.*out*.println("General structure blocks");
}

构造方法块

public Demo2() {    
	System.*out*.println("Structure method1");
}

”==“比较的是引用,”equal“比较的是具体内容

String name1 = "zhangsan";
String name2 = new String("zhangsan");
String name3 = name2;

则name2和name3是同一个,跟name1不同

直接赋值的方式,若字符串完全一致,则采用共享内存的方式,而new的方式则单独开辟空间

字符串特性:不能改变字符串内容,只能通过指向一个新的内存地址

多态

String类常用方法及基本使用

char charAt(int index)  //返回指定索引处的char值
//indexOf返回在此字符串中第一次出现的索引
String substring(int beginIndex, int endIndex);  //该字符串从beginIndex开始到字符串末尾
String toUpperCase()  //将string中的所有字符都转换成大写
str.trim()  //去掉空格

继承类

Java类的继承(类似于C++类的继承),只支持单继承(只能继承一个父类)

继承关键字:extends

例:

class B extends A{}  //B继承与A(前面继承与后面)

私有的东西不能被继承

final关键字

使用final(终结)声明的类不能被继承,使用final声明的类不能被子类覆盖,使用final声明的静态常量不能被修改(类似于C++的const修饰符)

抽象类

含有抽象方法(abstract)的类称为抽象类,不能生成对象(实例化),只能被继承

理解成模板,具体实现留给子类

抽象类和抽象方法都要用abstract关键字声明

接口

一种特殊的抽象类,关键字interface

由全局常量(static final)和公共方法组成,实现(implement)由类来实现

写法:

public class A implements B{}

类似与C++的头文件和实现文件,区别是头文件中可以定义变量,而接口只能定义全局常量

若继承和实现都有,则先继承(extends)后实现(implements)

写法:

public class A extends C implements D,E{}

对象多态性

父类引用指向子类的具体实现

例:

Animal animal = new Dog();  //Animal是父类,Dog是子类
animal.say();
animal = new Cat();    //更换指向
animal.say();
Dog dog = (Dog)animal;
dog.say();      //向下转型,父类对象转化成子类对象

对象的转型:向上转型:子类对象转化成父类对象

向下转型:父类对象转化成子类对象(不安全)

Object类

object是所有类的父类

打开一个类的所有方法和属性:ctrl+o

打印一个对象默认调用toString()方法

instanceof类:返回boolen类型,

A instance B   //A对象是否属于B类

为确保对象一定属于某个类,可以用if(A instanceof B)

String与String Buffer

匿名内部类

*//Anonymous internal class*
t.test(new A(){    
	public void A(){        
		System.*out*.println("Anonymous internal class, use only once");    
}});

把匿名内部类的返回值作为参数传入到函数中

包装类(一切皆为对象)

装箱和拆箱:类型之间可以转换

手动装箱

public static void main(String[] args){    
	int a = 1;    
	Integer i = new Integer(a);     *//Load package*    
	int b = i.intValue();           *//Unload package*    
	System.*out*.println(a+b+i);
}

自动装箱:自动把基本数据转换成对象

自动拆箱:过程相反

Integer i = 1;      *//Auto load box*
int i2 = i;         *//Auto unload box*

包装类作用:

例:若输入的是字符串,转化成int类型进行计算

String a = "1";
int m = Integer.*parseInt*(a);       *//Convert to int type*

设计模式

单例模式

单例对象能保证在一个JVM中,该对象只有一个实例存在

饿汉式,懒汉式

饿汉式

*/** * Hungry-man single realization */*
private static final Singleton1 *single1* = new Singleton1();
*/** * Static factory method */*
public static Singleton1 getInstance(){    
	return *single1*;
}

调用

Singleton1 single1 = Singleton1.*getInstance*();

懒汉式

*/** * Lazy-man single realization */*
private static Singleton2 *single*;
*/** * Factory */*
public synchronized static Singleton2 getInstance(){    
	if(*single* == null){        
		*//Instantiate when called first        
		single* = new Singleton2();    
	}    
	return *single;*
}

调用

Singleton2 single2 = Singleton2.*getInstance*();

懒汉式:只会实例化一次

饿汉式:会实例化多次

Java异常处理

捕获和处理异常,使用try{…}catch(){…}finally{},例

String str = "123a";
try {    
	int a = Integer.*parseInt*(str);
}
catch (NumberFormatException e){    
	e.printStackTrace();    //打印出错误类型    
	System.*out*.println("exception found");
}
finally {    
	System.*out*.println("finally");
}

throw表示直接抛出异常,交给方法的调用处理

Exception和RuntimeException

Exception是检查型异常,必须使用try…catch处理

RuntimeException是非检查型异常,由JVM虚拟机处理

以上两种异常最好通过虚拟机处理

** Exception while running, will be checked while compiling, must use try...catch... structure * **@throws** Exception */*
public static void testException()throws Exception{    
	throw new Exception("Exception caught");
}

*/** * Exception while running, won't be checked while compiling, needn't use try...catch... structure * **@throws** RuntimeException */*
public static void testRuntimeException()throws RuntimeException{    
	throw new RuntimeException("Exception caught while running program!");
}

自定义异常

自定义异常继承于Exception异常类,例

public class CustomException extends Exception{    
	public CustomException(String message){        
		super(message);    
	}
}

复习

getInstance()作用:在单例模式的类中常见,用来生成唯一的实例,往往是static的。

特征:不需要自己定义,用后不需要delete,引用的方式(类似于C++的引用参数)

如下两种方式等价:

Calendar calendar = Calendar.*getInstance*();
Calendar calendar = new Calendar();

Java常用类

日期类:Calendar

例:

Calendar calendar = Calendar.*getInstance*();
System.*out*.println(calendar.get(Calendar.*YEAR*));
System.*out*.println(calendar.get(Calendar.*MONTH*)+1);

注意:月份从0开始,所以需要+1

日期格式类:SimpleDateFormat

SimpleDateFormat sdf = new SimpleDateFormat();
System.*out*.println(sdf.format(date));

日期转化为指定格式:

public static String formatDate(Date date, String format){    
	String result = "";    
	SimpleDateFormat sdf = new SimpleDateFormat(format);    
	if(date != null){        
		result = sdf.format(date);    
	}    
	return result;
}

调用:

String prt = *formatDate*(date, "yyyy-MM-dd HH:mm:ss");

StringBuffer, Math, Arrays

String VS StringBuffer

对String类型对象的操作,等于重新生成一个对象,然后 将引用指向它;

对StringBuffer类型对象的操作,操作的始终是用一个对象

泛型

一.泛型的引入

public class Generic {    
	private Integer a;    
	public Generic(Integer a){        
		super();        
		this.a = a;    
	}    
	public Integer getA(){        
		return a;    
	}    
	public void setA(){        
		this.a = a;    
	}    
	*/**     * Print the type of a     */*    
	public void print(){        
		System.*out*.println("The type of 'a' is: "+a.getClass().getName());    
	}
}

可以使用多态

public class GenericObject {    
	private Object object;    
	public Object getObject(){        
		return object;    
	}    
	public void setObject(Object object){        
		this.object = object;    
	}    
	public GenericObject(Object object){        
		super();        
		this.object = object;    
	}    
	public void print(){        
		System.*out*.println("The type of 'a' is: "+object.getClass().getName());    
	}
}

注意set…和get…

向下转型(Object类强制转化成Integer类)

int a = (Integer) test.getObject();

泛型能表示任何类型(类似于C++的模板类)

泛型类定义:例:

public class GenericClass<T> {    
	private T ob;    
	public GenericClass(T ob){        
		super();        
		this.ob = ob;    
	}    
	public GenericClass() { }    
	public T getOb(){        
		return ob;    
	}    
	public void setOb(T ob){        
		this.ob = ob;    
	}    
	public void print(){        
		System.*out*.println("The realistic type of 'T' is: "+ob.getClass().getName());    
	}
}
  • 限制泛型

只能某个子类,其他类不能引入

public class Demo <T extends Animal>

模板调用的时候数据类型只能是Animal及其子类

  • 通配符泛型

在<>中加上?表示通配符泛型

public static void take(Demo<?> a)

  • 泛型方法

定义:

public static <T> void f(T t) {    
	System.*out*.println("The type of T is: "+t.getClass().getName());
}

调用:

*f*(1);

集合

List集合是Collection接口的子接口,也是最常用的接口。

List集合里面的元素可以重复

Student student[] = new Student[3];
Student s1 = new Student("zhangsan", 1);'
Student s2 = new Student("zhangsan2", 2);
Student s3 = new Student("zhangsan3", 3);
LinkedList<Student> list = new LinkedList<Student>();
list.add(s1);
list.add(s2);
list.add(s3);
ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add("zhangsan");
arrayList.add("lisi");
*printArrayList*(arrayList);
arrayList.add(1, "smallzhangsan");
arrayList.set(2, "xiaolisi");
System.*out*.println(list.indexOf("zhangsan"));
for(int i = 0; i < list.size(); i++){    
	Student s = list.get(i);    
	System.*out*.println(s.getName()+":"+s.getAge());
}

集合的遍历

Iterator

*Iterator*<Student> it = list.iterator();        *//Return an iterator*
while (it.hasNext()) {    
	Student s = it.next();    
	System.*out*.println("Name: "+s.getName()+" Age: "+s.getAge());
}

foreach

*/** * Use foreach to traverse set */*
for(Student a:list) {    
	System.*out*.println("Name: "+a.getName()+" Age: "+a.getAge());
}

遍历哈希表

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值