构造方法

构造方法

// 构造方法,用于在内存中创建对象 
public Phone(){
            System.out.println("我被构造了");
        }
        //构造方法
        public Phone(double kuan,double gao,int zhong, String yanse){
            width = kuan;
            high = gao;
            weight = zhong;
            color = yanse;
        }

作用:帮助开辟内存空间,创建对象

特征:

1 . 没有返回值 ;

2 . 名字要求和类名完全一致,区分大小写;

3 . 分为有参构造方法和无参构造方法

3 . 1 无参构造方法不不管是否书写,都会存在

3 . 2 有参构造方法学要手动编写,参数个数都可以自定义

方法的重载

上面的三个构造方法 == 》方法的重载

  1. 在同一个类中

  2. 方法的名字相同

  3. 参数不同

  3.1 参数的个数不同

  3.2 参数的类型不同

  3.3 参数类型的顺序不同

toString

 public String toString(){
           return "{"+this.weight+""+this.high+""+this.weight+""+this.color+"}";
        }

作用:把对象按照人能够理解的方式重写

this

表示当前对象(谁调用当前方法,this带是的就是谁)

public Phone(double width,double high,int weight, String color) {
            this.width = width;
            this.high = high;
            this.weight = weight;
            this.color = color;
        }

Object类

所有类的父类,但凡有其他的类被创建,Object一定被创建、

Object类中有一些固有的方法,即使没写,其他所有的类中都会有这些方法

equals()原生的:比较的是两个对象的地址是不是相同,一般场景

public boolean equals(Object obj) {
        return (this == obj);
    }

本列中以Phone为案列

public boolean equals(Object object){
            if (this==object){
                return true;
            }
            if (object instanceof Phone){
                Phone temp = (Phone) object;
                if (temp.width == this.width && temp.high == this.high && temp.weight == this.weight && temp.color == this.color){
                    return true;
                }else {
                return true;
            }
            return true;
            }

toString()原生的:返回的是对象的内存地址

   public String toString() {
        return getClass().getName() + "@" + Integer.toHexString(hashCode());
    }

**static ** 静态的

可以修饰成员属性,还可以修饰方法

被修饰的成员,类一旦创建,便分配了内存空间,可以直接通过类名.方法()调用

不需要对象即可是用,但通过对象也可调用,但不推荐

没有被修饰的成员:必须等待对象被创建,才拥有的独立的内存空间,之可以通过对象名.方法()调用

final 最终的

被final修饰的成员,值一旦被写定,不能被轻易修改

类成员的执行顺序

public class Demo01 {
    //2 普通的属性或者代码块其次执行,从上往下执行
    int size = 1;
    {
        size = 10;
    }
    //1 被static最先执行,被修饰的从上往下执行
    static int count = 30;
    static {
        count = 3;
    }
    //3 最后执行构造方法
    public Demo01(){
        System.out.println(size);
        System.out.println(count);
    }
}

内部类

和普通的成员一样,拥有对应的使用方式

public class Demo02 {
    String name;
    int age;

    public void fun(){
        System.out.println("普通的成员方法");
    }
    class Inner{
        int sex;
        double high;

        public void fun01(){
            System.out.println("内部类中的普通方法");
        }
    }
}

权限管理

public default protected private

修饰符 同一类 同一个包 子类 所有类
private √
default √ √
protected √ √ √
public √ √ √ √
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容