Rookie learning java objects and classes

1. Type variables

  • Local variables: Variables defined in methods, constructors, or statement blocks are called local variables. Variable declaration and initialization are in the method, after the method ends, the variable will be automatically destroyed.

  • Member variables: Member variables are variables defined in the class, outside the method body. This variable is instantiated when the object is created. Member variables can be accessed by methods in the class, constructors, and statement blocks of specific classes.

  • Class variables: Class variables are also declared in the class, outside the method body, but must be declared as static type.
    A class can have multiple methods, in the above example: eat(), run(), sleep() and name() are all methods of the Dog class.

2. Create objects

Objects are created from classes. In Java, use the keyword new to create a new object. Creating an object requires three steps:

  • Declaration: Declare an object, including the object name and object type.
  • Instantiation: Use the keyword new to create an object.
  • Initialization: When using new to create an object, the constructor is called to initialize the object.

Here is an example of creating an object:

public class Puppy{
    
    
   public Puppy(String name){
    
    
      //这个构造器仅有一个参数:name
      System.out.println("小狗的名字是 : " + name ); 
   }
   public static void main(String[] args){
    
    
      // 下面的语句将创建一个Puppy对象
      Puppy myPuppy = new Puppy( "tommy" );
   }
}

output

小狗的名字是 : tommy

3. Access instance variables and methods

Access member variables and member methods through the created object, as follows:

/* 实例化对象 */
Object referenceVariable = new Constructor();
/* 访问类中的变量 */
referenceVariable.variableName;
/* 访问类中的方法 */
referenceVariable.methodName();

example

The following example shows how to access instance variables and call member methods:

public class Puppy{
    
    
   int puppyAge;
   public Puppy(String name){
    
    
      // 这个构造器仅有一个参数:name
      System.out.println("小狗的名字是 : " + name ); 
   }
 
   public void setAge( int age ){
    
    
       puppyAge = age;
   }
 
   public int getAge( ){
    
    
       System.out.println("小狗的年龄为 : " + puppyAge ); 
       return puppyAge;
   }
 
   public static void main(String[] args){
    
    
      /* 创建对象 */
      Puppy myPuppy = new Puppy( "tommy" );
      /* 通过方法来设定age */
      myPuppy.setAge( 2 );
      /* 调用另一个方法获取age */
      myPuppy.getAge( );
      /*你也可以像下面这样访问成员变量 */
      System.out.println("变量值 : " + myPuppy.puppyAge ); 
   }
}

output

小狗的名字是 : tommy
小狗的年龄为 : 2
变量值 : 2

4. Source file declaration rules

Pay special attention to these rules when defining multiple classes in a single source file, and there are also import statements and package statements.

  • There can only be one public class in a source file
  • A source file can have multiple non-public classes
  • The name of the source file should be consistent with the class name of the public class. For example: the class name of the public class in the source file is Employee, then the source file should be named Employee.java.
  • If a class is defined in a package, then the package statement should be the first line of the source file.
  • If the source file contains import statements, they should be placed between the package statement and the class definition. If there is no package statement, then the import statement should come first in the source file.
  • The import statement and package statement are valid for all classes defined in the source file. In the same source file, different package declarations cannot be given to different classes.
  • Classes have several access levels, and classes are also divided into different types: abstract classes, final classes, and so on.
  • In addition to the types mentioned above, Java also has some special classes, such as: inner class, anonymous class.

Why can there only be one Public class in a JAVA file?

The java program is executed from the main function of a public class (actually the main thread), just like the C program is executed from the main() function. There can only be one public class for the convenience of the class loader. A public class can only be defined in a file named after its class.

Each compilation unit (file) has exactly one public class. Because each compilation unit can only have one public interface, represented by a public class. This interface can contain as many classes as required to support package access. If there is more than one public class, the compiler will report an error. And the name of the public class must be the same as the file name (strictly case sensitive). Of course, there can be no public class in a compilation unit.

The difference between member variables and class variables

A variable modified by static is called a static variable, which is essentially a global variable. If a certain content is shared by all objects, then the content should be decorated with static; the content that is not statically decorated is actually a special description of the object.

The instance variables of different objects will be allocated different memory spaces. If the member variables in the class have class variables, then the class variables of all objects are allocated to the same memory. Changing the class variable of one of the objects will affect This class variable of other objects, that is to say, objects share class variables.

5. The difference between member variables and class variables

  • Class variable: defined in the class, outside the method body, but must have static to declare the variable type. Static members belong to the entire class and can be called by object name or class name.
public class  ClassName{
    
    
    static int a;
    public void printNumber(){
    
    
        // 其他代码
    }
}
  • Member variables: defined in the class, outside the method body. Variables are instantiated when the object is created. Member variables can be accessed by methods, constructors, and class-specific statement blocks in the class.
public class  ClassName{
    
    
    int a;
    public void printNumber(){
    
    
        // 其他代码
    }
}
  • Local variables: Variables defined in methods, constructors, and statement blocks. Its declaration and initialization are implemented in the method and are automatically destroyed after the method ends
public class  ClassName{
    
    
    public void printNumber(){
    
    
        int a;
    }
    // 其他代码
}

In detail:

1. The life cycle of the two variables is different

  成员变量随着对象的创建而存在,随着对象的回收而释放。

  静态变量随着类的加载而存在,随着类的消失而消失。

2. Different calling methods

  成员变量只能被对象调用。

  静态变量可以被对象调用,还可以被类名调用。

3. Different aliases

  成员变量也称为实例变量。

  静态变量也称为类变量。

4. Different data storage locations

  成员变量存储在堆内存的对象中,所以也叫对象的特有数据。

  静态变量数据存储在方法区(共享数据区)的静态区,所以也叫对象的共享数据。

The static keyword is a modifier used to modify members (member variables and member functions).

Features:

1. Want to achieve object sharing of common data in objects. This data can be statically modified.

2. Members that are statically modified can be directly called by the class name. In other words, static members have one more calling method. ClassName.Static method.

3、静态随着类的加载而加载。而且优先于对象存在。

Disadvantages:

1. Some data is object-specific data and cannot be statically modified. Because in that case, the specific data will become the shared data of the object. There is a problem with the description of things in this way. Therefore, when defining static, it must be clear whether this data is shared by objects.

2. Static methods can only access static members, not non-static members.

  因为静态方法加载时,优先于对象存在,所以没有办法访问对象中的成员。

3. The this and super keywords cannot be used in static methods.

  因为this代表对象,而静态在时,有可能没有对象,所以this无法使用。

When to define static members? In other words: When defining members, do they need to be statically modified?

There are two types of members:

1. Member variables. (Static during data sharing)

  该成员变量的数据是否是所有对象都一样:

  如果是,那么该变量需要被静态修饰,因为是共享的数据。 

  如果不是,那么就说这是对象的特有数据,要存储到对象中。 

2. Member functions. (When no specific data is called in the method, it is defined as static)

  如果判断成员函数是否需要被静态修饰呢?

  只要参考,该函数内是否访问了对象中的特有数据:

  如果有访问特有数据,那方法不能被静态修饰。

  如果没有访问过特有数据,那么这个方法需要被静态修饰。

The difference between member variables and static variables:

1. The member variable belongs to the object. So it is also called instance variable.

  静态变量所属于类。所以也称为类变量。

2. Member variables exist in heap memory.

  静态变量存在于方法区中。

3. Member variables exist with object creation. Gone when the object is recycled.

  静态变量随着类的加载而存在。随着类的消失而消失。

4. Member variables can only be called by objects.

  静态变量可以被对象调用,也可以被类名调用。

Therefore, member variables can be called the unique data of the object, and static variables are called the shared data of the object.

6. The role of the new keyword

1. Allocate memory space for the object.

2. Causes the call of the object construction method.

3. Return a reference to the object.

When instantiating an object using a java class, if its constructor is not explicitly declared in the class, a default constructor will be used to initialize the object.

Example:

//一个没有显式声明构造函数的类
Public class People{
    
    
    int age = 23;
    Public void getAge(){
    
    
        System.out.print("the age is "+age);
    }
}

//用这个类来实例化一个对象
People xiaoMing = new People(); // People() 是People类的默认构造函数,它什么也不干
xiaoMing.getAge();//打印年龄

It is also possible to explicitly declare a constructor when declaring a class:

//一个带显式构造函数的类
Public class People{
    
    
    int age = 23;
        Public void getAge(){
    
    
        System.out.print("the age is "+ age);
    }
    // 显式声明一个带参数的构造函数,用于初始化年龄
    Public People(int a){
    
    
        this.age = a; 
    }
}

//用这个类来实例化一个对象
People xiaoMing = new People(20); // 使用带参数的构造函数来实例化对象
xiaoMing.getAge(); // 打印出来的年龄变为20
  • this is a pointer to the object itself, and the members of the form have the same name, and this is used to distinguish them.
    This excellent tutorial : https://blog.csdn.net/benxiangsj/article/details/124282800

  • super A pointer to the super (parent) class object.
    Super's excellent tutorial : https://blog.csdn.net/qq_46096136/article/details/126171232

7. Advantages and disadvantages of inner classes

  • Pros: Access to external class private properties (heart access to body's blood, not external pumping).
  • Disadvantages: destroy the program structure of the original class (properties, constructors, ordinary methods, inner classes).
//外部类
class Out {
    
    
    private int age = 12;
     
    //内部类
    class In {
    
    
        public void print() {
    
    
            System.out.println(age);
        }
    }
}
 
public class Demo {
    
    
    public static void main(String[] args) {
    
    
        Out.In in = new Out().new In();
        in.print();
        //或者采用下种方式访问
        /*
        Out out = new Out();
        Out.In in = out.new In();
        in.print();
        */
    }
}
运行结果:12

It is not difficult to see from the above examples that inner classes actually seriously damage the good code structure, but why use inner classes?

Because the inner class can freely use the member variables of the outer class (including private) without generating objects of the outer class, this is the only advantage of the inner class.

Just like the heart can directly access the body's blood instead of having a doctor pump it.

After the program is compiled, two .class files will be generated, namely Out.class and Out$In.class.

Where $ represents the one in Out.In in the above program.

Out.In in = new Out().new In()

It can be used to generate objects of internal classes. There are two small knowledge points that need to be noted in this method:

  1. The Out at the beginning is to indicate which outer class the inner class object to be generated belongs to.

  2. An object of the outer class must be present before an object of the inner class can be generated, because the function of the inner class is to access the member variables in the outer class.

Guess you like

Origin blog.csdn.net/AdamCY888/article/details/131394550