学习java第12天

1.对象构造与初始化

*构造方法

调用本类或父类的构造方法

    this调用本类的其他构造方法,super调用直接父类的构造方法。注:this或super要放在第一条语句,且只能够有一条

class ConstructCallThisAndSuper
{
 public static void main(String[] args){
  Person p = new Graduate();
 }
}
class Person
{
 String name;
 int age;
 Person(){}
 Person( String name, int age ){
  this.name=name; this.age=age;
  System.out.println("In Person(String,int)");
 }
}
class Student extends Person
{
 String school;
 Student(){
  this( null, 0, null );
  System.out.println("In Student()");
 }
 Student( String name, int age, String school ){
  super( name, age );
  this.school = school;
  System.out.println("In Student(String,int,String)");
 }
}
class Graduate extends Student
{
 String teacher="";
 Graduate(){
  //super();
  System.out.println("In Graduate()");
 }
}
*实例初始化与静态初始化
静态初始化   static语句  {语句......},在第一次使用这个类时要执行
其执行的时机总是先于实例的初始化
class InitialTest
{
 public static void main(String[] args)
 {
  new InitialTest2(6);
 }
 int n=10;  //step2
 {
  n++;
  System.out.println("InitialTest..."+n);
 }
 
 static int x;
 static
 {
  x++;
  System.out.println("static..." +x);
 }
 
}
class InitialTest2 extends InitialTest{
 InitialTest2(int a){
  this.a=a;
  System.out.println("this.a=" + a );
 }
 int a;
 {
  System.out.println("InitialTest2..."+this.a);
 }
 static
 {
  x++;
  System.out.println("static2..." +x);
 }
}
*构造方法执行过程
先父类构造,再本类成员赋值,最后执行构造方法中的语句
class JavaPConstructor
{
 int a=2000;
 JavaPConstructor(){
  this.a=3000;
 }
}
2.对象清除与垃圾回收
*对象清除
 
对象是自动清除的,由java虚拟机的垃圾回收线程来完成的
任何对象都有一个引用计时器,其值为0时,说明可以回收
*System.gc()方法
是System类的static方法,可以要求系统进行垃圾回收,但仅仅是建议(suggest)
*finalize()方法
系统在回收时自动调用对象的finalize()方法  protected void finalize() throws Throwable{}
*try-with-resources
try ( Scanner scanner = new Scanner(...) ) {
    ......
}
 
明天学习内容:
内部类与匿名类,Lambda表达式(*)
 
原文地址:https://www.cnblogs.com/SirNie/p/13332546.html