java_关于this关键字,方法及构造器

this关键字:(这个)
成员变量前系统默认提供了this.
类是对象的模板,对象是类的实例化
当形参与成员变量名称一致时,为区分两者,需要在成员变量前加this.

this指向的是将要创建的那个对象,即变量.方法()时的变量

================================================
方法:
概念:
类的共同行为,封装了一段逻辑代码,尽可能只完成一个功能(避免多个功能封装在一个方法内)
方法的使用:
方法属于对象的行为,应该使用:引用.方法,这些方法动态绑定到对象上
方法签名:
方法名+形参列表 = 方法签名
形参列表:指的是形参的类型顺序列表

如: public void sum(int a,int,b)
    方法签名:sum + int,int
public int eat(String food)
    方法签名:eat + String

方法的重载(overload):
在同一个类型中,方法名相同,参数列表不同

在方法调用时,编译器会检查类的信息中是否有此方法签名的方法
c.sum(3,5);
此时,编译器检查类中是否有c.sum(int,int)这样的方法
有,编译通过
没有,编译失败,并提示错误

内存管理机制:

方法区:jvm将字节码文件加载到此区域,用来储存类的信息
堆(heap):用来存储引用类型的对象
栈(stack):用来存储方法内的局部变量
栈帧:是栈中的空间,当程序执行到某一方法时,jvm专门为此方法开辟的一块独有空间,此方法内的局部变量都在此栈帧中,方法结束后消失

================================================
构造方法:
是特殊的方法,作用是用来给成员变量(Field)初始化
特殊在
(1)没有返回值这个位置
(2)方法名与类名相同
格式:修饰词 类名(){}

如:点;

public class Point{
    int x;
    int y;
    public Point(int x,int y){
        this.x = x;
        this.y = y;
    }
}

默认无参构造器:
如果定义类时,没有添加构造方法,系统会默认提供一个公有的没有形参的构造方法
public Point(){}

如果定义期间提供了构造器,系统不再提供无参构造器

有参构造器:
因为构造器是用来给成员变量初始化的,为了方便,所以形参名都与成员变量名一致,因此,赋值时this.不能省略

构造器的调用:
只能是new关键字来调用;
new 构造方法(有参传参);

对象的实例化:是由new完成的(对象存在,成员变量都是默认值)
对象的成员变量初始化:是由new调用的构造器进行的(成员变量第一次被赋值)

构造器的重载:
一个类中,可以有多个构造器
方法名相同,参数列表不同
================================================
练习:

public class Dog {
    String name;//名字
    int age;//年龄
    char gender;//性别
    String color;//颜色
    /*构造器的重载*/
    /**无参构造器*/
    public Dog(){}
    /**四个全参构造器*/
    public Dog(String name,int age,char gender,
            String color){
        this.name = name;
        this.age = age;
        this.gender = gender;
        this.color = color;
    }
    /**三参构造器*/
    public Dog(String name,int age,char gender){
        this.name = name;
        this.age = age;
        this.gender = gender;
        color = "黄色";
    }
    /**两个参数构造器*/
    public Dog(String name,int age){
        this.name = name;
        this.age = age;
        gender = '公';
        color = "黄色";
    }
    /*方法的重载*/
    /**
     * eat方法
     * */
    public void eat(String food){
        System.out.println(age+"岁的"+name+"喜欢吃"+food);
    }
    /**
     * eat方法n斤狗粮
     * */
    public void eat(int n){
        System.out.println(age+"岁的"+name+"吃了"+n+"斤狗粮");
    }
    /**
     * toString()
     * System.out.println(引用变量);
     * 输出时不再是对象的地址信息,
     * 而是输出toString()方法的返回值
     */
    public String toString(){
        return name+","+age+"岁,"+gender+","+color;
    }
    public static void main(String[] args) {
        Dog d = new Dog("旺财",5);
        System.out.println(d);
        d.eat("骨头");
        Dog d1 = new Dog("小花",3,'母');
        System.out.println(d1);
        d1.eat(2);
        Dog d2 = new Dog();
        System.out.println(d2);
        Dog d3 = new Dog("阿黄",4,'公',"土黄色");
        System.out.println(d3);
    }
}

输出结果:
旺财,5岁,公,黄色
5岁的旺财喜欢吃骨头
小花,3岁,母,黄色
3岁的小花吃了2斤狗粮
null,0岁, ,null
阿黄,4岁,公,土黄色

猜你喜欢

转载自blog.csdn.net/yc_hen/article/details/81289987