zoukankan      html  css  js  c++  java
  • java动手动脑 2

        类的初始化

    public class InitializeBlockClass {

    {

    field=200;

    }

    public int field=100;

    public InitializeBlockClass(int value)

    {

    this.field=value;

    }

    public InitializeBlockClass()

    {

    }

    public static void main(String[] args) {

    InitializeBlockClass obj=new InitializeBlockClass();

    System.out.println(obj.field);

    obj=new InitializeBlockClass(300);

    System .out .println(obj.field);

    }

    // TODO Auto-generated method stub

    }

    输出结果;

     

    初始化第一次是用了类的初始化块,第二次用了publicint初始化,所以第二次覆盖了第一次,输出了100,在main函数中给类InitializeBlockClass赋初值300,所以覆盖100,输出300, 所以类的初始化有类的初始化块,还可以直接在类中赋值,还可以用一个函数为类的属性赋值,还可以构造函数。

     

     

    当多个类之间有继承关系时,创建子类对象会导致父类初始化块的执行

    例如

    package fatherandson;

    public class fatherandson {

    public static void main(String[] args){

    Son a=new Son();

    a.show();

    }

    }

    class Father{

    String name;

    {

    name="father";

    }

    }

    class Son extends Father{

    int age=30;

    void show()

    {

    System.out.println("name"+name);

    System.out.println("age"+age);

    }

    }

    最后输出  nameFather

                 age 30

    静态方法中只允许访问静态数据,也可以在静态方法中访问类的实例成员

    public class StaticTest {

         public static void main(String args [])

        {

           test b=new test();   b.print();  

       }

    }

    class test {  

       int i=1;   

      static void print()    

      {       

           test a=new test();  

           System.out.println(a.i);  

       }

    }

    最后输出   1

    使用类的静态字段和构造函数,我们可以跟踪某个类所创建对象的个数。请写一个类,在任何时候都可以向它查询“你已经创建了多少个对象”

    package jishu;

    public class jishu{ 

    public static void main(String[] args){

    Information a = new Information();

    a.OutputInformation(); 

    Information b = new Information();

    b.OutputInformation();

    } }

    class Information{ 

    static int num=0;

    Information()

    { num++;

    }

    public void OutputInformation()

     { 

    System.out.println("你已经创建了"+num+"个对象!");

    }

     

  • 相关阅读:
    C++中break语句、continue语句和goto语句区别
    面试题 01.03:URL化(C++)
    面试题 01.02: 判定是否互为字符重排(C++)
    面试题 01.01: 判定字符是否唯一(C++)
    探索one
    面试题32
    面试题32
    面试题32
    面试题33: 二叉搜索树的后序遍历序列(C++)
    用命令行执行php脚本输出乱码
  • 原文地址:https://www.cnblogs.com/1336303471-tengxianliang/p/4887740.html
Copyright © 2011-2022 走看看