javase personal garbage review notes 13 Java package, Java enumeration (enum) and package (package), as well as interface

Java packaging
advantages of packaging

  1. Good packaging can reduce coupling.

  2. The internal structure of the class can be modified freely.

  3. You can control member variables more precisely.

  4. Hide information and implement details.
    Steps to achieve Java encapsulation

  5. Modify the visibility of the attribute to restrict access to the attribute (generally restricted to private), for example:

public class Person {
    
    
    private String name;
    private int age;
}

In this code, the name and age attributes are set to private, which can only be accessed by this class, and cannot be accessed by other classes, so the information is hidden.
2. Provide external public method access to each value attribute, that is, create a pair of assignment methods for access to private attributes, for example:

public class Person{
    
    
    private String name;
    private int age;public int getAge(){
    
    
      return age;
    }public String getName(){
    
    
      return name;
    }public void setAge(int age){
    
    
      this.age = age;
    }public void setName(String name){
    
    
      this.name = name;
    }
}/*采用 this 关键字是为了解决实例变量(private String name)和局部变量(setName(String name)中的name变量)之间发生的同名的冲突

Let us look at an example of a java package class:

/* 文件名: EncapTest.java */
public class EncapTest{
    
    
 
   private String name;
   private String idNum;
   private int age;
 
   public int getAge(){
    
    
      return age;
   }
 
   public String getName(){
    
    
      return name;
   }
 
   public String getIdNum(){
    
    
      return idNum;
   }
 
   public void setAge( int newAge){
    
    
      age = newAge;
   }
 
   public void setName(String newName){
    
    
      name = newName;
   }
 
   public void setIdNum( String newId){
    
    
      idNum = newId;
   }
}
/* F文件名 : RunEncap.java */
public class RunEncap{
    
    
   public static void main(String args[]){
    
    
      EncapTest encap = new EncapTest();
      encap.setName("James");
      encap.setAge(20);
      encap.setIdNum("12343ms");
 
      System.out.print("Name : " + encap.getName()+ 
                             " Age : "+ encap.getAge());
    }
}
/*
以上代码编译运行结果如下:

Name : James Age : 20

//It's pretty simple, no problem.

Java enumeration (enum)
Java enumeration is a special class, which generally represents a set of constants, such as 4 seasons of a year, 12 months of a year, 7 days of a week, and the directions are southeast, northwest, etc.
Java enumeration classes are defined using the enum keyword, and each constant is separated by a comma.
For example, define a color enumeration class.

enum Color
{
    
    
    RED, GREEN, BLUE;
}
 
public class Test
{
    
    
    // 执行输出结果
    public static void main(String[] args)
    {
    
    
        Color c1 = Color.RED;
        System.out.println(c1);
    }
}/*
执行以上代码输出结果为:

RED

Enumeration classes can also be declared in inner classes:

public class Test
{
    
    
    enum Color//每个枚举都是通过 Class 在内部实现的,且所有的枚举值都是 public static final 的。
    {
    
    
        RED, GREEN, BLUE;
    }
 
    // 执行输出结果
    public static void main(String[] args)
    {
    
    
        Color c1 = Color.RED;
        System.out.println(c1);
    }
}
/*执行以上代码输出结果为:
RED*/
//相当于:
class Color
{
    
    
     public static final Color RED = new Color();
     public static final Color BLUE = new Color();
     public static final Color GREEN = new Color();
}

Iterating enumeration elements
You can use the for statement to iterate enumeration elements:

enum Color
{
    
    
    RED, GREEN, BLUE;
}
public class MyClass {
    
    
  public static void main(String[] args) {
    
    
    for (Color myVar : Color.values()) {
    
    
      System.out.println(myVar);
    }
  }
}
/*执行以上代码输出结果为:
RED
GREEN
BLUE

Use enumeration classes in switch Enumeration classes
are often used in switch statements:

enum Color
{
    
    
    RED, GREEN, BLUE;
}
public class MyClass {
    
    
  public static void main(String[] args) {
    
    
    Color myVar = Color.BLUE;

    switch(myVar) {
    
    
      case RED:
        System.out.println("红色");
        break;
      case GREEN:
         System.out.println("绿色");
        break;
      case BLUE:
        System.out.println("蓝色");
        break;
    }
  }
}
/*执行以上代码输出结果为:
蓝色


The enumeration class defined by the values(), ordinal() and valueOf() methods enum inherits the java.lang.Enum class by default, and implements the java.lang.Seriablizable and java.lang.Comparable interfaces.

The values(), ordinal() and valueOf() methods are located in the java.lang.Enum class:
values() returns all the values ​​in the enumeration class.
The ordinal() method can find the index of each enum constant, just like an array index.
The valueOf() method returns the enum constant of the specified string value.

enum Color
{
    
    
    RED, GREEN, BLUE;
}
 
public class Test
{
    
    
    public static void main(String[] args)
    {
    
    
        // 调用 values()
        Color arr[] = Color.values();
 
        // 迭代枚举
        for (Color col : arr)
        {
    
    
            // 查看索引
            System.out.println(col + " at index " + col.ordinal());
        }
 
        // 使用 valueOf() 返回枚举常量,不存在的会报错 IllegalArgumentException
        System.out.println(Color.valueOf("RED"));
        // System.out.println(Color.valueOf("WHITE"));
    }
}
/*执行以上代码输出结果为:

RED at index 0
GREEN at index 1
BLUE at index 2
RED

Enumeration class members
Enumeration can use its own variables, methods and constructors just like ordinary classes. The constructor can only use the private access modifier, so it cannot be called from outside.

enum Color
{
    
    
    RED, GREEN, BLUE;
 
    // 构造函数
    private Color()
    {
    
    
        System.out.println("Constructor called for : " + this.toString());
    }
 
    public void colorInfo()
    {
    
    
        System.out.println("Universal Color");
    }
}
 
public class Test
{
    
        
    // 输出
    public static void main(String[] args)
    {
    
    
        Color c1 = Color.RED;
        System.out.println(c1);
        c1.colorInfo();
    }
}
/*执行以上代码输出结果为:

Constructor called for : RED
Constructor called for : GREEN
Constructor called for : BLUE
RED
Universal Color

Java package (package)
acting package
1, in the same package, and easy to find similar or related functions like class or interface tissue.

2. Like folders, packages also use a tree-shaped directory storage method. The names of classes in the same package are different, and the names of classes in different packages can be the same. When calling classes with the same class name in two different packages at the same time, the package name should be added to distinguish. Therefore, the package can avoid name conflicts.

3. The package also has limited access rights, and only classes with package access rights can access classes in a package.

Import keyword
In order to be able to use a member of a package, we need to explicitly import the package in the Java program. Use the "import" statement to complete this function.

import package1[.package2…].(classname|*);

Example
The following payroll package already contains the Employee class. Next, add a Boss class to the payroll package. The payroll prefix can be omitted when the Boss class refers to the Employee class. Examples of the Boss class are as follows.

package payroll;
 
public class Boss
{
    
    
   public void payEmployee(Employee e)
   {
    
    
      e.mailCheck();
   }
}

What if the Boss class is not in the payroll package? The Boss class must use one of the following methods to reference classes in other packages.

Use the full name of the class to describe, for example:

payroll.Employee
is introduced with the import keyword, using wildcard "*"

import payroll.*;
Use the import keyword to import the Employee class:

import payroll.Employee;
注意:

Any number of import statements can be included in the class file. The import statement must be after the package statement and before the class statement.

//I like package management the most.

Java interface

Interface (English: Interface), in the JAVA programming language, is an abstract type and a collection of abstract methods. Interfaces are usually declared as interface. A class inherits the abstract methods of the interface by inheriting the interface.

Interfaces are not classes. The way to write interfaces is similar to classes, but they belong to different concepts. The class describes the properties and methods of the object. The interface contains the methods to be implemented by the class.

Unless the class implementing the interface is an abstract class, the class must define all methods in the interface.

The interface cannot be instantiated, but it can be implemented. A class that implements an interface must implement all the methods described in the interface, otherwise it must be declared as an abstract class. In addition, in Java, interface types can be used to declare a variable, they can become a null pointer, or be bound to an object implemented by this interface.

Interfaces are similar to classes:
an interface can have multiple methods.
The interface file is saved in a file ending in .java, and the file name uses the interface name.
The bytecode file of the interface is saved in a file ending in .class.
The bytecode file corresponding to the interface must be in the directory structure that matches the package name.

The difference between interfaces and classes:
interfaces cannot be used to instantiate objects.
The interface has no constructor.
All methods in the interface must be abstract methods.
The interface cannot contain member variables, except for static and final variables.
The interface is not inherited by the class, but to be implemented by the class.
The interface supports multiple inheritance.

The interface has the following characteristics: The
interface is implicitly abstract. When declaring an interface, you don't need to use the abstract keyword.
Every method in the interface is also implicitly abstract, and the abstract keyword is also not required in the declaration.
The methods in the interface are all public.

Interface implements
the time when the class implements the interface, the interface classes to implement all of the methods. Otherwise, the class must be declared as an abstract class.
The class uses the implements keyword to implement the interface. In the class declaration, the Implements keyword is placed after the class declaration.
To implement the syntax of an interface, you can use this formula:

...implements 接口名称[, 其他接口名称, 其他接口名称..., ...] ...

example:

interface Animal {
    
    
   public void eat();
   public void travel();
}
public class MammalInt implements Animal{
    
    
 
   public void eat(){
    
    
      System.out.println("Mammal eats");
   }
 
   public void travel(){
    
    
      System.out.println("Mammal travels");
   } 
 
   public int noOfLegs(){
    
    
      return 0;
   }
 
   public static void main(String args[]){
    
    
      MammalInt m = new MammalInt();
      m.eat();
      m.travel();
   }
}
/*以上实例编译运行结果如下:

Mammal eats
Mammal travels

When rewriting methods declared in an interface, you need to pay attention to the following rules:

When a class implements an interface method, it cannot throw a mandatory exception. It can only be thrown in the interface or an abstract class that inherits the interface.
The class should keep the same method name when rewriting the method, and should keep the same or compatible return value type.
If the class implementing the interface is an abstract class, then there is no need to implement the methods of the interface.
When implementing the interface, also pay attention to some rules:

A class can implement multiple interfaces at the same time.
A class can only inherit one class, but it can implement multiple interfaces.
One interface can inherit another interface, which is similar to inheritance between classes.

Interface inheritance
One interface can inherit another interface, which is similar to the way of inheritance between classes. The inheritance of the interface uses the extends keyword, and the child interface inherits the method of the parent interface.

The following Sports interface is inherited by Hockey and Football interface:

public interface Sports
{
    
    
   public void setHomeTeam(String name);
   public void setVisitingTeam(String name);
}
 public interface Hockey extends Sports
{
    
    
   public void homeGoalScored();
   public void visitingGoalScored();
   public void endOfPeriod(int period);
   public void overtimePeriod(int ot);
}
 //Hockey接口自己声明了四个方法,从Sports接口继承了两个方法,这样,实现Hockey接口的类需要实现六个方法。

Guess you like

Origin blog.csdn.net/qq_45864370/article/details/108608854