第八章面向对象编程
8.1封装
8.1.1成员变量的封装
public class Human{ //name sex age变量都是定义成私有变量,只能在Human这个类中被调用 private String name; private String sex; private int age; //外部类就可以使用公有的方法使用上面这些变量, public String getName(){ return name; } public void setName(String name){ this.name=name; } public String getSex(){ return sex; } public void setSex(String sex){ this.sex=sex; } public int getAge(){ return age; } public void setAge(int age){ this.age=age; } }
8.1.2成员变量的继承
public class Parent{ public String pString = "父类的public属性"//父类只有这一个公有的成员变量 } public class Child extends Parent{ public void print(){ //打印父类的成员变量 因为父类pString是public,子类继承了父类所以子类可以直接使用 System.out.println(pString); } public ststic void main(String[] args){ Child child = new Child(); child.print(); } } --输出结果: 父类的public属性
8.1.3成员变量的覆盖
父类和之类中同样声明一个变量时,子类访问该变量时是访问的子类的变量,要想访问父类的,要使用super关键字。
public class Parent{ public String pString = "父类的public属性"//父类只有这一个公有的成员变量 } public class Child extends Parent{ public String pString = "子类中的字符串" public void print(){ System.out.println(pString); //System.out.println(super.pString);强制使用父类的成员变量 } public ststic void main(String[] args){ Child child = new Child(); child.print(); } } --输出结果:调用子类的成员变量 子类中的字符串
8.2合理的使用类
合理的分解类
让类的名字和方法反映它的应用
类的名字、方法名、变量名都尽量要反映它表示的东西。比如Human类表示人类、Animal类表示动物类、Tiger类表示老虎类。方法应该尽量用动词或动词与名词的组合来表示,比如move()、 getName()等。
复用现有的类
当一些代码会经常用到的时候,最好是把它们抽离出来,其它的类来调用它,这样当有需求改变或者这个类发现有bug的时候,只需要改一个地方,所有调用它的类就都改了。Java中也已经提供了很多有用的类,我们都可以拿来用,不用自己重新写。比如String,它就提供了非常多有用的方法。
第九章异常处理
Java提供了一套完善的异常处理机制,通过这套机制,可以轻松写出容错性非常高的代码。
9.1异常的基本知识
由于硬件问题、资源耗尽、输入错误以及程序代码编写不严谨会导致程序运行时产生异常,这些异常会导致程序终端而不能正常继续运行,所以需要对异常的情况进行妥善处理。
9.2一些例子
以下介绍2种最基本的异常情况,例一 :
package exception; public class TryCatchDemo { public static void main( String[] args ) { string str = null; int strLength = 0 ; strLength = str.length(); System.out.println( strLength); } } 此时str是null,空的是无法获取长度,所以会抛出以下异常
public class TryCatchDemo{ public static void main(String[] args){ string str = null; int strLength = 0; try{ strLength = str.length(); }catch(NullPointerException e){ //这段话会抛出一个异常,不会报错,但不会接着后面执行 } System.out.println( strLength); } } --输出结果:0 ------------------------------------------------------------------------------- public class TryCatchDemo{ public static void main(String[] args){ string str = null; int strLength = 0; try{ strLength = str.length(); }catch(NullPointerException e){ e.printStackTrace(); }catch(Exception e){ e.printStackTrace();//异常catch可以有多个 }finally{ //无论这个程序是否异常这里的finally一定会执行 System.out.println("这里一定会执行"); } System.out.println(strLength); } } --运行结果如下,抛出异常后,e.printStackTrace();打印出异常,还会执行后面的语句输出0。
例二
public class ThorwsDemo{ //这个方法和以往的不一样,如果该方法有异常发生抛到方法外面 //让调用我这个方法的那个方法去处理异常,调用这个方法的方法必须要try catch public static void method() throws NullPointerException{ String str = ""; int strLength = str.length(); System.out.println(strLength); } public static void main(String[]args){ try { method(); }catch(NullPointerExceptione) { e.printStackTrace(); } } }