Java笔记——初始化和清除

来源:互联网 发布:淘宝优惠券微信公众号 编辑:程序博客网 时间:2024/05/14 15:08

用构建器进行初始化

  • 保证每个对象都可得到正确的初始化
  • 构建器的名字与类名相同,这是必须的

方法过载

  • 让相同的方法名随不同的自变量类型而调用不同的方法
package com.demo;import java.io.PrintStream;class Tree{    int height;    Tree(){        System.out.println("planting a seeding");        height = 0;    }    Tree(int h){        System.out.println("creating a new tree "+h+" feet tall");    }}public class E4_2 {    public static void main(String[] args)    {        for(int i = 0;i < 5;i++)        {            Tree t1 = new Tree();            Tree t2 = new Tree(i);        }    }}运行结果:planting a seedingcreating a new tree 0 feet tallplanting a seedingcreating a new tree 1 feet tallplanting a seedingcreating a new tree 2 feet tallplanting a seedingcreating a new tree 3 feet tallplanting a seedingcreating a new tree 4 feet tall

区分过载方法:
每个过载的方法都有一个独一无二的自变量列表


  • 主类型过载
      -
  • 返回值过载
    • 不可行
  • 默认构建器
    • 若创建了一个没有构建器的类,则编译过程会为我们自动生成一个
    • 若存在一个已经定义的构建器,则编译过程将不再自动生成默认构建器
  • -

this关键字

class Banana{    void f(int i){    //..    }}Banana a = new Banana();Banana b = new Banana();a.f(2);b.f(1);/*    a.f(2) -- Banana.f(a,2) -- class Banana{                                    void f(self, int i)                                    {                                        this.i = ();                                    }                                }    b.f(1) -- Banana.f(b,1)*/  

但不可以这么写表达式


0 0
原创粉丝点击