美文网首页
Java基础:对象

Java基础:对象

作者: 远方的橄榄树 | 来源:发表于2019-11-20 15:48 被阅读0次

    1、类与对象概念

    • 类:类是对具有某一共同特性的事物的的集合,是一种抽象化的概念。
    • 对象:对象是对类这一概念的具体实现,是真实世界的实体。比如,我们将看做类的话,那么“我”、“小明”、“小龙”等就是一个个具体的对象。

    2. 对象与引用

    public class Person {
        public static void main(String[] args) {
            Person p = new Person();
        }
    }
    

    对于Person p = new Person();,很多人都会认为p是对象,这种理解其实是错误的。p是引用变量,它存储在栈中,new Person()会创建一个新的person对象存储在堆中,然后将存储地址传递给引用变量p

    2、this关键字

    • this关键字表示“这个对象”或“当前对象”,而且它本身表示对当前对象的引用。
    • this关键字只能在方法(不包括静态方法)内部使用。
    public class Banana {
        
        private String name;
        
        private String color;
        
        public Banana() {}
        
        public Banana(String name) {
            this.name = name; // this.name表示这个对象的属性name
        }
        
        public Banana(String name, String color) {
            this(name); // 调用构造器
            this.color = color;
        }
        
        public static void f1() {
    //        this.name;  // error
        }
    }
    

    3、 static关键字

    • static方法的内部不能调用非静态方法
    • 无论创建多少对象,静态数据都只占用一份存储区域,static关键字不能作用在于局部变量,因为它只能作用于域。
    public class Test {
        public static void main(String[] args) {
            System.out.println("水果1...");
            Fruit fruit1 = new Fruit();
            System.out.println("水果2...");
            Fruit fruit2 = new Fruit();
        }
    }
    
    class Apple {
        Apple() {
            System.out.println("苹果真好吃");
        }
    }
    
    class Fruit {
        static Apple apple = new Apple();
        
        static {
            System.out.println("静态代码块...");
        }
        Fruit() {
            System.out.println("Fruit init...");
        }
        public void f() {
    //        static int i = 1; // error
        }
    }
    
    水果1...
    苹果真好吃
    静态代码块...
    Fruit init...
    水果2...
    Fruit init...
    

    由结果可知,静态初始化会先执行,而且只在第一次加载Fruit.class的时候执行,然后再调用构造器生成对象。
    dui

    访问权限

    权限 类内 同包 不同包子类 不同包非子类
    private × × ×
    default × ×
    protected ×
    public

    相关文章

      网友评论

          本文标题:Java基础:对象

          本文链接:https://www.haomeiwen.com/subject/nguoictx.html