Home  >  Article  >  Java  >  Java basic classes and objects, singleton pattern, inheritance

Java basic classes and objects, singleton pattern, inheritance

巴扎黑
巴扎黑Original
2017-06-26 11:29:321004browse

Java classes and objects

General classes can only be public or default. If they are public, the class name must be the same as the file name. Generally, only one class is written in a file, so this class is usually added with public.

Inner classes can also be private and protected, generally privatized (private), because only the current class is needed. This way only its outer classes can access it directly. So it doesn't matter whether the data inside is public, private or default.

public class Out {private int d = 10;public int add() {      // 外部类不能直接访问内部类的数据,除非new出内部类对象,如下  // Out.In abc = new Out().new In();a = 3; // falseb = 5; // false}  // 内部类private class In {private int a = 100;int b;public int c;public void add() {
            System.out.println(d); // true, 内部类却可以直接访问外部类的数据}
    }public static void main(String[] args) {
        Out bb = new Out();
        Out.In abc = new Out().new In();
        bb.d = 20; // 本类可以直接访问private,一般不这样,而是写个set函数,搭配get函数System.out.println(aa.a); // 100System.out.println(bb.d); // 被修改为20}
}
  • Anonymous object

new Abc().run(); // 调用一次后这个对象就销毁new Abc().run(); // 这是另外一个Abc对象了
  • About private

  • Private variables: Encapsulate data and only show methods to users. For example, the private String name cannot be modified at will, but the setName() and getName() methods can be called to realize data encapsulation, which is safer.

  • Private method: A function that does not need to be called by the user can be defined as private by completing some internal implementation details. For example, the selection sort algorithm is written as a method, which contains the process of exchanging two data and is encapsulated into a function. This function does not need to be operated by the user (the user only needs to use a sort()), and this swap() is defined as private.

Single case design pattern

can ensure the uniqueness of the object of a class in memory. When you need to use the same configuration information object for multiple programs, you need to ensure that the object Uniqueness, then single instance is needed.

In the tool class, if the object member data is not used (accessed), there is no need to create an object. To prevent object creation, the constructor can be defined as private.

How to ensure the uniqueness of objects?

  1. Do not allow other programs to create objects of this class using new, and set the constructor to private

  2. Create a unique class instance in this class

  3. Provide a method to the outside world so that other programs can obtain this unique object

Single case design steps

  1. Private the constructor of this class

  2. Put an object of this class into this class through new

  3. Define one puiblic method, returns the object created in 2

hunger mode

// 饿汉式--不管用不用得到,先new出一个再说public class SingleDemo {// private不能将这个实例暴露出去,只能通过getInstance()获取,另为何是static?private static SingleDemo s = new SingleDemo();private SingleDemo() {}// 供外界调用来获取这个对象public static SingleDemo getInstance() {return s;
    }  // 只有本类中可以new对象并调用addpublic void add() {
        System.out.println("danli");
    }public static void main(String[] args) {      // 本类可以newSingleDemo a = new SingleDemo();
        a.add();
    }
}public class Test {public static void main(String[] args) {      // fasle, 其他类中若用到这个单例,不能newSingleDemo aa = new SingleDemo();      // true  SingleDemo aa = SingleDemo.getInstance();
    }
}

lazy mode

// 另外一种单例设计模式--懒汉模式--用到了才new,延时加载public class SingleDemo {// 先设为空private static SingleDemo s;private SingleDemo() {}// 供外界调用来获取这个对象public static SingleDemo getInstance() {      if (s == null)
        s = new SingleDemo();return s;
    }

Q: Why are member variables static and methods static?

A: Because new is not allowed to create new objects in other classes, getInstance() cannot be called. If we set it to static method, we can use Single.getInstance () to obtain without new object, and the data in the static method must also be static. Therefore, this SingleDemo object must also be static.

Q: What is the difference between hungry man mode and lazy man mode?
A: Lazy mode is delayed loading, and it is new only after it is used; the uniqueness of the object cannot be guaranteed in multi-threading, and it is thread unsafe. Hungry Man Mode As the class is loaded, the object is new, whether it is used or not, it is thread-safe.

Inheritance

Java generally uses single inheritance, and cannot directly multiple inheritance --> Because multiple parent classes may have the same members, calling will cause ambiguity .

But you canMulti-level inheritance, such as A --> B -->C--> D, which can mean that A inherits from B, and B inherits from C, so And so on.

  • Use this to distinguish between members of this class and local variables

  • When members of subclasses and parent classes have the same name Use super to distinguish

  • The derived class cannot access the private members of the base class, but it is indeed inherited, but it cannot be accessed. You can call the parent class's# The ##set and get functions operate the private members of the subclass and have no effect on the parent class.

  • If the member is protected or has higher permissions, you can directly access the member without

    set or get.

  • The members of the parent class and the subclass are independent of each other. The subclass changes its own members and the parent class remains the same.

package Chap1;public class Fu {  // 父类的成员是私有的,子类继承过去了也不能直接访问
  private int age;private String name;public Fu(int age, String name) {this.age = age;this.name = name;
    }public int getAge() {return age;
    }public void setAge(int age) {this.age = age;
    }public String getName() {return name;
    }public void setName(String name) {this.name = name;
    }
}class Zi extends Fu {  // 特有的job,父不能访问private String job;Zi(int age, String name, String job) {super(age, name);this.job = job;
    }public String getJob() {return job;
    }  public static void main(String[] args) {
        Zi aa = new Zi(23, "Zi","Study");
        Fu bb = new Fu(55, "Fu");      // 改变子类不会影响父类aa.setAge(24);
        aa.setName("zi");      // zi 24 Study  // Fu 55System.out.println(aa.getName()+" "+aa.getAge() + " " + aa.getJob());
        System.out.println(bb.getName()+" "+bb.getAge());

    }
}
  • Subclasses implicitly execute super(). When new a child object, the constructor of the parent class is called first and then executed. Constructor for subclasses.

  • The default constructor is parameterless,

    the parameterized constructor will override the parameterless one . At this time, super(args) needs to be used explicitly, and it must be placed on the first line. If super is not written explicitly, the default super(), which is the parent class constructor without parameters, will be executed.

class Fu {  // 构造函数
  Fu() {
    System.out.println("father");
  }  // 带参的构造函数
   public Fu(int age, String name) {this.age = age;this.name = name;
    }
}class Zi extends Fu {  
  Zi() {private String job;// super() 会打印“father”// 无参数时是默认构造器,这句super()可以不写。父类的构造函数默认执行,先执行// 
  }  
  Zi(int age, String name, String job) {// 若不写,会默认调用无参的super()打印fathersuper(age, name);this.job = job;
    }
}
  • 类是public,构造函数也是public的。他们的修饰符是对应的。

一个对象的实例化过程

Person p = new Person();

  1. JVM读取Person.class文件,加载进内存;若有父类,会先加载父类。

  2. 在堆内存中开辟空间,分配地址。

  3. 在对象空间中,对对象的属性进行默认初始化,如int age = 0; String name = null;

  4. 显示初始化,如private int age = 9。若是子类,则会先调用父类的构造器。

  5. (子)类的 构造函数进行特定的初始化。如下程序中age变成100。

  6. 初始化后,将地址传递给引用变量。Person p <-- new Person();

package Test;// 先打印9// 再打印100public class Demo {private int age = 9;
    {
        System.out.println(age);
    }Demo(int age) {this.age = age;
    }public static void main(String[] args) {
        Demo aa = new Demo(100);
        System.out.println(aa.age);
    }
}

The above is the detailed content of Java basic classes and objects, singleton pattern, inheritance. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Java String AdvancedNext article:Java String Advanced