面向对象Java期末总结

请简述try,catch,finally的块的执行流程

1)如果在try块中发生异常那么控制会立刻被传递(跳过try块中的剩下的其他语句)到catch中去。一旦catch块执行完成之后finally块和其后的程序执行

2)如果在代码中没有异常发生,try块中的代码会被完全执行,然后执行控制被传递到(跳过catch块)finally块中

3)如果在catch或者try块中有return语句,在这种情况下,finally也会执行,控制流是:先执行finally然后回到return语句。


try语句块、catch语句块、finly语句块各有什么作用?

try语句是代码执行块,用于对代码块的异常捕获,在try中运行的代码中的异常会被捕获。

catch语句是异常处理块 是非必须执行语句 紧跟在try语句后,其中有一个参数指明异常的类型,

当捕获到此类异常的时候执行catch中的代码对其进行处理

finally语句块中的代码是一些必须执行的语句,这里的代码无论try中是否发生异常都会被执行


把main方法中所有语句都放到一个try语句块好不好?为什么?

不好

try...catch的目的是捕获不同类型的异常并针对不同的异常情况设置不同的解决方案。如果用try包含main方法的所有代码,就无法针对不同异常进行不同解决方案的处理


哪些情况应该抛出异常,哪些情况应该捕获异常?

抛出异常:无法通过参数检查  将可能导致以后的相关功能出错

捕获异常:通常在运行之前java不报错,但是运行后可能会出现某些未知的错误,但是还不想直接抛出到上一级,那么就需要通过”try{}catch“的形式进行异常捕获,之后根据不同的异常情况来进行相应的处理。有能力处理就捕获异常,不能处理就抛出


基本数据类型和引用数据类型有哪些,区别是什么?

基本数据类型:

byte:即1个字节、short:短整型、int:整型、long:长整型、float:浮点型、double:双精度浮点型、char:字符型、boolean:布尔类型

引用数据类型:

类、接口类型、数组类型、枚举类型。

区别:基本数据类型在被创建时,在栈上给其划分一块内存,将数值直接存储在栈上。

引用数据类型在被创建时,首先要在栈上给其引用(句柄)分配一块内存,而对象的具体信息都存储在堆内存上,然后由栈上面的引用指向堆中对象的地址。


简述抽象类和接口类的意义

抽象类:抽象类内允许有普通变量和普通方法;必须有abstract关键字;可以没有抽象方法,但不能实例化;有抽象方法的一定是抽象类;不能被实例化,但是有构造方法(派生类可以扩展)。

接口:接口只声明,没有方法体,如:public abstract void func();定义的变量都默认是public static final ,必须被显示初始化;没有构造方法,不能实例化;实现接口的类要实现所有的抽象方法,否则该类就必须声明为抽象类,加上 abstract关键字;接口不可以实现接口,所有接口都是抽象方法,但是接口支持多继承。


简述泛型的含义,说明使用通配符extends和super的使用场景

1)所谓泛型,即通过参数化类型来实现在同一份代码上操作多种数据类型。泛型编程是一种编程范式,它利用“参数化类型”将类型抽象化,从而实现更为灵活的复用。泛型赋予了代码更强的类型安全,更好的复用,更高的效率,更清晰的约束。

2)<? extends T>只能用于方法返回,告诉编译器此返参的类型的最小继承边界为T,T和T的父类都能接收,但是入参类型无法确定,只能接受null的传入

<? super T> 只能用于限定方法入参,告诉编译器入参只能是T或其子类型,而返参只能用Object类接收

? 既不能用于入参也不能用于返参


简述静态属性和静态方法的含义

静态方法和属性是属于类的,调用的时候直接通过类名.方法名完成的,不需继承机制就可以调用如果子类里面定义了静态方法和属性,那么这时候父类的静态方法 或属性称之为“隐藏”,如果想要调用父类的静态方法和属性,直接通过父类名.方法名或变量名完成.


请简述String和StringBuffer的区别及使用场景

1. String对象是常量字符串。String对象的值一经赋值,其值不可变指的是所指向的内存值不可修改,但可以改变指向

StringBuffer对象的值可以修改主要用于对字符串做大量修改的操作时

举例:

String name= new String(“lipeilun”);

StringBuffer stringBuffer = new StringBuffer(“Hello”);

2. String 类适用于字符常量较多,且对字符常量修改较少或不修改的情况

StringBuffer 类适用于需要对字符串进行多次修改扩充的情况


小例题:已知Number是Integer的基类,某类中定义了一个print方法,参数类型是List<Number>类型,当调用该方法时传入List<Integer>类型的参数,会出现什么结果?如果导致程序出错,那应该如何修改print方法让程序能正确执行,至少说出三种修改方法,并说明修改后能正常执行的原因。

public void print(List<Number> nums) {

    for(Number num : nums) {

      System.out.println(num);

    }

}

答:会出现编译错误。

修改1:将方法的参数类型改为List<?> nums

修改2:将方法的参数类型改为List<? extends Number> nums

修改3:将方法的参数类型改为List<Integer> 类型

import java.util.ArrayList;
import java.util.List;

public class Test {

	public static void main(String[] args) {
		List<Integer> list = new ArrayList<Integer>();

		print1(list);
		print2(list);
		print3(list);
		print4(list);
	}

	public static void print(List<Number> nums) {

	    for(Number num : nums) {

	      System.out.println(num);

	    }
	}
	public static void print1(List<Integer> nums) {

	    for(Number num : nums) {

	      System.out.println(num);

	    }
	}
	public static void print2(List<? extends Number> nums) {

	    for(Number num : nums) {

	      System.out.println(num);

	    }
	}
	public static void print3(List<?> nums) {

	    for(Object num : nums) {

	      System.out.println(num);

	    }
	}
	public static void print4(List<? super Integer> nums) {

	    for(Object num : nums) {

	      System.out.println(num);

	    }
	}

}

请定义学生类。属性:姓名,年龄,薪水,定义对应的get,set方法,及至少三个构造方法,equals方法,toString方法。

public class Student {
	private String studentNo;
	private String name;
	private Double enlishScore;
	public String getStudentNo() {
		return studentNo;
		}
	public void setStudentNo(String studentNo) {
		this.studentNo = studentNo;}
	public String getName() {
		return name;
		}
	public void setName(String name) {
		this.name = name;
		}
	public Double getEnlishScore() {
		return enlishScore;
		}
	public void setEnlishScore(Double enlishScore) {
		this.enlishScore = enlishScore;
		}
	class English{
		private String name;
		private String sysInfo;
		public Person(String name) {
			this.name = name;
			}
		public Person(String name, int age, double salary) {
			this.name = name;
			this.age = age;
			this.salary = salary;
			}
		public String toString(){
			return "姓名:"+name+";年龄:"+age+";薪水:"+salary;}
		public boolean equals(Object obj){
			if(obj == null){return false;}
			if(this == obj){
				return true;
				}
			if(!(obj instanceof Person)){
				return false;
				}
			Person per=(Person) obj;
			return this.age==per.age&& this.name.equals(per.name)&& this.salary==per.salary ;        
			}
		}
	private String name;
	private String sysInfo;
	public String getName() {
		return name;
		}
	public void setName(String name) {
		this.name = name;
		}
	public String getSysInfo() {
		return sysInfo;
		}
	public void setSysInfo(String sysInfo) {
		this.sysInfo = sysInfo;
		}
	}

请定义形状类,属性:颜色,面积。定义其子类,圆类,方类。在形状类定义抽象计算面积方法,派生类进行各自实现

public class Ten {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		TenCricle c = new TenCricle();
		TenSquare s = new TenSquare();
		c.setR(2);
		c.setArea(c.getR());
		System.out.println(c.area);
		s.setX(6);
		s.setArea(s.getX());
		System.out.println(s.area);
		}
	}
public abstract class TenShape {
	protected String color;
	protected double area;
	public abstract void setArea(double a);
	}
public class TenSquare extends TenShape{
	private double x;
	public void setX(double x){
		this.x=x;
		}
	public double getX(){
		return this.x;
		}
	public void setArea(double x){
		this.area = x*x;
		}
	}
public class TenCricle extends TenShape{
	private double r;
	public void setR(double r){
		this.r=r;
		}
	public double getR(){
		return this.r;
		}
	public void setArea(double a){
		this.area = 3.14 * a * a;
		}
	}

请读取studentDB.txt文件,格式如下,其内容为三列,中间用\t隔开,第一列代表姓名,第二列代表数学成绩,第三列代表语文成绩,前两行示例如下:

zhangsan   80  90

lisi       80  90

请读取文件,将学生信息读入List,分别统计数学和语文课程不及格的学生人数是。

public class Eleven {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		File open = new File("D:/demo.txt");
		List<String>mS=newArrayList<String>();
		List<String>cS= new ArrayList<String>();
		try {
			Reader open1 = new FileReader(open); BufferedReader open11 = new BufferedReader(open1); String str;
			while((str=open11.readLine())!=null){
				String[] message = str.split("\t");
				String name = message[0];
				int mScore = Integer.parseInt(message[1]);
				int cScore = Integer.parseInt(message[2]);
				if(mScore<60)
					mS.add(name);
				if(cScore<60)
					cS.add(name);
				}
			open1.close();
			open11.close();
			}
		catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace(); 
			}
		catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace(); 
			}
		System.out.println(mS);
		System.out.println(cS); 
		} 
	}

为什么下面这个方法可以用类名.方法名调用?

public static LocalDate now() {
	return now(Clock.systemDefaultZone());
	}

LocalDate now()属于静态方法,公有的静态方法在类外的一种访问方式:通过类名.公有静态方法名([参数]),类方法可在不实例化对象的前提下直接调用,一般类的静态方法前用static关键字修饰。


“+”运算符

int n = 10;

System.out.println(n++);

System.out.println(++n);

System.out.println((n++)+1);

System.out.println(n);

10 12 13 13


计算任意给定的两个数之间的所有数之和

public class Calculator{
	int sum(int begin, int end) {
		int sum = 0;
		for(int i = begin;i <= end;i++ ) {
			sum += i ;
			}
		return sum ;
		}
	public static void main(String[] args) {
		Calculator cal = new Calculator() ;
		int sum = cal.sum( 1, 100 ) ;
		System.out.println( "1~100的和是:" + sum ) ;
		}
	}

 已知 1×2+2×3+3×4+…+n×(n+1)<1000求n的最大值

public class Calculator{
	int computeN(int totalNum) {
		int s = 0 ;
		int n = 1 ;
		while(s<totalNum){
			s+=n*(n+1);
			n=n+1;
			}
		return n–2;
		}
	public static void main(String[] args){
		Calculator cal=new Calculator() ;
		int n=cal.computeN(1000) ;
		System.out.println(“n的最大值是:” + n); 
		} 
	}

class 派生类名称 extends 基类名称

内部类:(inner class)是定义在另一个类中的类,也称内置类或嵌套类。

成员内部类:作为外部类的一个成员存在,与外部类的属性、方法并列。内部类和外部类的实例变量可以共存。

局部内部类:在方法中定义的内部类称为局部内部类,类似局部变量。

匿名内部类:将局部内部类的使用再深入一步。假如只创建这个类的一个对象,就不必对内部类命名了。这种类被称为匿名内部类

静态内部类:定义在类中,在任何方法之外,用static定义。


取本月第1天:

LocalDate firstDayOfThisMonth = today.with(TemporalAdjusters.firstDayOfMonth()); // 2014-12-01

取本月第2天:

LocalDate secondDayOfThisMonth = today.withDayOfMonth(2); // 2014-12-02

取本月最后一天,再也不用计算是28,29,30还是31:

LocalDate lastDayOfThisMonth = today.with(TemporalAdjusters.lastDayOfMonth()); // 2014-12-31

取下一天:

LocalDate firstDayOf2015 = lastDayOfThisMonth.plusDays(1); // 变成了2015-01-01

取2015年1月第一个周一

LocalDate firstMondayOf2015 = LocalDate.parse("2015-01-01").with(TemporalAdjusters.firstInMonth(DayOfWeek.MONDAY)); // 2015-01-05

解析日期:

String dateStr= "2016年10月25日";

DateTimeFormatter formatter=DateTimeFormatter.ofPattern("yyyy年MM月dd日");

LocalDate date= LocalDate.parse(dateStr, formatter);

日期转换为字符串

LocalDateTime now = LocalDateTime.now();

DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy年MM月dd日 hh:mm a");

String nowStr = now .format(format);

实例化:

LocalDateTime now = LocalDateTime.now();

LocalDateTime dateTime1 = LocalDateTime.of(1990, 1, 1, 12, 3);

LocalDateTime dateTime2 = LocalDateTime.of(2000, 2, 4, 8, 4, 20);


输出时间

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

SimpleDateFormat sdf2=new SimpleDateFormat("yyyy年MM月dd日 hh点");

try {

    Date date = sdf.parse("2008-12-23 12:23:45");

    System.out.println(sdf2.format(date));  //输出2008年12月23日 12点

} catch (ParseException e) {

    e.printStackTrace();

}


文件

File file = new File("d:/帐户信息.txt");

FileReader fr = new FileReader(file);

BufferedReader br = new BufferedReader(fr);

//使用BufferedReader包装FileReader

File file_copy = new File("d:/帐户信息-copy.txt");

FileWriter fw = new FileWriter(file_copy);

BufferedWriter bw = new BufferedWriter(fw);

//使用BufferedWriter包装FileWriter

String str = br.readLine();

while (str != null) {

         bw.write(str);

         str = br.readLine();

}

bw.flush();

bw.close();

fw.close();

br.close();

fr.close();


为什么要继承,什么情况下能继承

1、如果类被final修饰,那么此类不可以被继承。

2、如果类中只有private的构造方法,那么此类不可以被继承。

发布了46 篇原创文章 · 获赞 39 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/weixin_42128813/article/details/86660354