Java learning - static members, application, inheritance, abstract classes, interfaces and enumerations of objects

Static member

Static static modifier that modifies members in a class. Members modified by static are called static members (class members), and members not modified by static are called instance members.

1. Instance members

Instance members are owned by individual objects and cannot be shared with each other

2. Static variables

A static variable is a public storage unit. Any object of a class can access the same value. When any object of a class modifies it, it is also operating on the same memory unit
Static variables can be used without instantiation, or instance objects can be used to access static variables
Usage format: class name. Static variable name; Object name. Static variable name;
If a class contains static variables, they must be independent of methods

class Cylinder
{
    private static int num=0;
    private double radius;
    private int height;
    private static double pi=3.14;
    String color;
    public Cylinder(double r,int h,String str)
    {
        radius=r;
        height=h;
        color=str;
        num++;
    }
    public void show()
    {
        System.out.println("Radius of cylinder bottom:"+radius);
        System.out.println("high:"+height);
        System.out.println("colour:"+color);
        System.out.println("Created"+num+"Objects");
    }
    double area()
    {
        return pi*radius*radius;
    }
    double volume()
    {
        return area()*height;
    }
}
public class Test
{
    public static void main(String[] args)
    {
        Cylinder volu1=new Cylinder( 2.5,5,"gules");
        System.out.println("Cylinder bottom area="+volu1.area());
        System.out.println("Cylindrical volume="+volu1.volume());
        volu1.show();
        Cylinder volu2=new Cylinder( 1.0,2,"blue");
        System.out.println("Cylinder bottom area="+volu2.area());
        System.out.println("Cylindrical volume="+volu2.volume());
        volu2.show();
    }
}

3. Static method

Static methods are essentially methods belonging to the whole class, which are shared by all objects and cannot directly access instance variables and instance methods
When calling static methods, you can directly use the class name or a specific object name
Format: class name. Static variable name (); Object name. Static variable name ();
When calling a static method through an object name, you must first create an object

class Cylinder
{
    private static int num=0;
    private double radius;
    private int height;
    private static double pi=3.14;
    String color;
    public Cylinder(double r,int h,String str)
    {
        radius=r;
        height=h;
        color=str;
        num++;
    }
    public static void show()
    {
        System.out.println("Created"+num+"Objects");
    }
    double area()
    {
        return pi*radius*radius;
    }
    double volume()
    {
        return area()*height;
    }
}
public class Test
{
    public static void main(String[] args)
    {
        Cylinder.show();
        Cylinder volu1=new Cylinder( 2.5,5,"gules");
        System.out.println("Cylinder bottom area="+volu1.area());
        System.out.println("Cylindrical volume="+volu1.volume());
        volu1.show();
        Cylinder volu2=new Cylinder( 1.0,2,"blue");
        System.out.println("Cylinder bottom area="+volu2.area());
        System.out.println("Cylindrical volume="+volu2.volume());
        volu2.show();

    }
}


Application of object

In some cases, you can use objects like basic type variables

1. Assignment and comparison of objects

assignment

When using objects, you usually create objects with new first, and then operate on them. However, sometimes you can assign values without creating new objects.
Example: create Cylinder class Cylinder and assign values to the objects created by this class

class Cylinder
{
    private double radius;
    private int height;
    private static double pi=3.14;
    public Cylinder(double r,int h)
    {
        radius=r;
        height=h;
    }
    public void setCylinder(double r,int h)
    {
        radius=r;
        height=h;
    }
    double area()
    {
        return pi*radius*radius;
    }
    double volume()
    {
        return area()*height;
    }
}
public class Test
{
    public static void main(String[] args)
    {
        Cylinder volu1,volu2;
        volu1=new Cylinder( 2.5,5);//Create object volu1
        System.out.println("Bottom area of cylinder 1="+volu1.area());
        System.out.println("Cylinder 1 volume="+volu1.volume());
        volu2=volu1;//Assign volu1 to volu2
        volu2.setCylinder( 1.0,2);//Reset parameters
        System.out.println("Bottom area of cylinder 2="+volu2.area());
        System.out.println("Cylinder 2 Volume="+volu2.volume());

    }
}


compare

After the object is assigned, the addresses stored in the two reference variables are equal (when the parameter is a basic data type, it is a value passing method call; when the parameter is a reference variable, it is a value passing method call)
Use the following example to illustrate the comparison of objects

class Cylinder
{
    private double radius;
    private int height;
    private static double pi=3.14;
    public Cylinder(double r,int h)
    {
        radius=r;
        height=h;
    }
    public void compare(Cylinder volu)
    {
       if (this==volu)
           System.out.println("The two objects are equal");
       else
           System.out.println("The two objects are not equal");
    }
    double area()
    {
        return pi*radius*radius;
    }
    double volume()
    {
        return area()*height;
    }
}
public class Test
{
    public static void main(String[] args)
    {
        Cylinder volu1=new Cylinder( 2.5,5);
        Cylinder volu2=new Cylinder( 2.5,5);//create new object
        Cylinder volu3=volu1;//assignment
        volu1.compare(volu2);
        volu1.compare(volu3);
    }
}


2. Reference the variable as the return value of the method

Reference variables can be passed not only as parameters, but also as the return value of methods
Create a human Person and define a compare() method with the object as the return value in this class

class Person{      //Create a human
    private String name;
    private int age;
    public Person(String name,int age){
        this.name=name;
        this.age=age;
    }
    public Person compare(Person p){   //Defines a method with an object as the return value, and the return value type is an object
        if (this.age>p.age)
           return this;//Returns the object that calls the method, in this case per1
        else
            return p;//Returns a parameter object, in this case per2
    }
}
public class Test1 {
    public static void main(String[] args) {
        Person per1=new Person("Zhang San",22);
        Person per2=new Person("Li Si",21);
        Person per3;
        per3=per1.compare(per2);
        if (per3==per1)
            System.out.println("Zhang San is old");
        else
            System.out.println("Li Si is old");
    }
}

3. Array of class types

An array used to store objects. The steps are as follows
(1) Declare array variables of class type, and allocate memory space to the array with new operator;
(2) Create a new object with new, allocate memory space to it, and let the array point to it.

class Person{
    private String name;
    private int age;
    public Person(String name,int age){
        this.name=name;
        this.age=age;
    }
    public void show (){
        System.out.println("full name:"+name+"  Age:"+age);
    }
}
public class Test1 {
    public static void main(String[] args) {
       Person[] per=new Person[3];//Declare an array of class types and allocate memory space with new
       per[0]=new Person("Zhang San",20);
       per[1]=new Person("Li Si",21);
       per[2]=new Person("Wang Wu",22);//Create a new object with new and assign it to the array elements
       per[2].show();
       per[1].show();//Call the show method with the object per[1]
    }
}

4. Method call with object array as parameter

As can be seen from the above example, arrays can store objects. Therefore, object arrays can also be passed into methods as parameters.
Pass the method with the object array as a parameter and return the smallest member variable in the object array

class Person{
    private String name;
    private int age;
    public Person(String name,int age){
        this.name=name;
        this.age=age;
    }
    public static int minAge (Person[] p){   //Passing an object array as a parameter to a method
        int min=Integer.MAX_VALUE;//Set the initial value of min to the maximum value of int type integer
        for (int i=0;i< p.length;i++){
            if (p[i].age<min)
                min=p[i].age;//Store the minimum value of the member variable age in the array object in min
        }
        return min;//Returns the value of the smallest member variable in the object array
    }
}
public class Test1 {
    public static void main(String[] args) {
       Person[] per=new Person[3];
       per[0]=new Person("Zhang San",20);
       per[1]=new Person("Li Si",21);
       per[2]=new Person("Wang Wu",22);
        System.out.println("The minimum age is:"+Person.minAge(per));
    }
}

Class inheritance

Class inheritance is to derive a new class from an existing class. It is the concept of program code reuse.

The inherited class is called parent class or super class, and the inherited class is called subclass. A parent class can have multiple subclasses, and a class can only have one direct parent.

A parent class is actually a collection of public members of all subclasses, and a subclass is a specialization of the parent class.

Subclasses inherit member variables and member methods accessible to the parent class, and can also modify, override and add member variables and member methods

1. Creation of subclasses

Class inheritance in Java language is realized through the extends keyword. The format is as follows:

class SubClass extends SuperClass
{
      ...   
}

The above statement declares SubClass as a direct SubClass of class SuperClass
If there is no extends keyword, the class is obtained by default from the java.lang.Object class

Construction method of subclass

class Person1    //The Person class is a subclass of the java.long.Object class
{
    private String name;
    private int age;
    public Person1()//Parameterless construction method of Person class
    {
        System.out.println("Called a human constructor Person()");
    }
    public void setNameAge(String name,int age)
    {
        this.name=name;
        this.age=age;
    }
    public void show(){
        System.out.println("full name:"+name+"  Age:"+age);
    }
}
class Student extends Person1   //Defines that the Student class inherits from the Person class
{
    private String department;
    public Student()  //Nonparametric construction method of Student class
    {
        System.out.println("Called the constructor of the student class Student()");
    }
    public void setDepartment(String dep){
        department=dep;
        System.out.println("I am"+department+"student");
    }
}
public abstract class Test2 {
    public static void main(String[] args) {
        Student stu = new Student();//Create a Student object and call the constructor
        stu.setNameAge("Zhang San",12);//Call parent method
        stu.show();
        stu.setDepartment("Computer Department");//Call subclass method
    }
}

In Java language inheritance, the parameterless constructor of the parent class will be called before executing the constructor of the child class. The purpose is to help the members inherited from the parent class to perform initialization operations

Strictly speaking, the constructor of the parent class cannot be inherited, but it does not mean that the child class cannot call the constructor of the parent class

Call a specific constructor in the parent class

The implementation through the super() statement must be written in the first line of the subclass constructor
The format is super (parameter list), and super() can be overloaded
Before Java executes the construction method of a subclass, if there is no super(), it will call the parameterless construction method of the parent class first, so the parent class only defines the parameterless construction method, and the compilation will cause an error. The solution is to define a parameterless construction method in the parent class

class Person1    //The Person class is a subclass of the java.long.Object class
{
    private String name;
    private int age;
    public Person1()//Parameterless construction method of Person class
    {
        System.out.println("Called a human parameterless constructor Person()");
    }
    public Person1(String name,int age)
    {
        System.out.println("Called a human parameterized constructor");
        this.name=name;
        this.age=age;
    }
    public void show(){
        System.out.println("full name:"+name+"  Age:"+age);
    }
}
class Student extends Person1   //Defines that the Student class inherits from the Person class
{
    private String department;
    public Student()  //Nonparametric construction method of Student class
    {
        System.out.println("The parameterless constructor of the student class was called Student()");
    }
    public Student(String name,int age,String dep){
        super(name,age);//Call the parameterized constructor of the parent class
        department=dep;
        System.out.println("I am"+department+"student");
        System.out.println("Called the parameterized constructor of the student class");
    }
}
public abstract class Test2 {
    public static void main(String[] args) {
        Student stu1= new Student();//Create a Student object and call the parameterless constructor
        Student stu2= new Student("Zhang San",12,"Computer Department");//Create an object and call a parameterized constructor
        stu1.show();
        stu2.show();
    }
}

super() calls the parent class constructor from the child class constructor
this() calls other constructor methods within the same class
Both must be placed on the first line within the constructor, so they cannot coexist in the same constructor

2. Access parent class members in subclasses

super can access not only the construction method of the parent class, but also the member variables and member methods of the parent class, but cannot access the members added in the subclass. The application format is as follows
super. Variable name;
super. Method name ();
private members of the parent class cannot be accessed in subclasses, but protected members can be accessed

class Person1    //The Person class is a subclass of the java.long.Object class
{
    protected String name;
    protected int age;
    public Person1()//Parameterless construction method of Person class
    {}
    public Person1(String name,int age)
    {
        this.name=name;
        this.age=age;
    }// The parameter constructor in the parent class is useless in this example
    public void show(){
        System.out.println("full name:"+name+"  Age:"+age);
    }
}
class Student extends Person1   //Defines that the Student class inherits from the Person class
{
    private String department;
    int age=20;
    public Student(String xm,String dep){
        name=xm;//Directly access the protected member of the parent class in the child class
        department=dep;
        super.age=25;//Assign the parent class age with super
        System.out.println("In subclasses age="+age);
        super.show();// super can be removed
        System.out.println("Department:"+department);
    }
}
public abstract class Test2 {
    public static void main(String[] args) {
        Student stu1= new Student("Zhang San","Information system");
    }
}

protected can be called directly in subclasses or super

3. Coverage

The concept of override is similar to that of method overload. Overload refers to defining multiple methods with the same name but different parameter numbers or types in the same class, while override refers to defining methods with the same name, parameter numbers and types in the subclass as those in the parent class to override the functions of methods with the same name in the parent class.

Override method of parent class

Methods declared as final or static in the parent class cannot be overridden in a subclass. Overriding means that the method header of the subclass is exactly the same as that of the parent class and cannot be inherited at this time

class Person1    //The Person class is a subclass of the java.long.Object class
{
    protected String name;
    protected int age;
    public Person1(String name,int age)
    {
        this.name=name;
        this.age=age;
    }
    protected void show(){
        System.out.println("full name:"+name+"  Age:"+age);
    }
}
class Student extends Person1   //Defines that the Student class inherits from the Person class
{
    private String department;
    int age=20;
    public Student(String name,int age,String dep){
        super(name,age);
        department=dep;
    }
    protected void show(){
        System.out.println("Department:"+department);
    }
}
public class Test2 {
    public static void main(String[] args) {
        Student stu1= new Student("Zhang San",22,"Information system");
        stu1.show();
    }
}

Note: when overriding the method of the parent class in a subclass, you can expand the permission of the method in the parent class, but you cannot reduce the permission of the classification method

Use the object of the parent class to access the members of the child class

Change the main class of the above code to:

public class Test2 {
    public static void main(String[] args) {
       Person1 per= new Student("Zhang San",22,"Information system");//Declare that the parent class object points to the child class object
       per.show();//Call the show() method with the parent class object per
    }
}

Note: subclass methods can only be called through parent objects when overrides occur

Non inheritable members and final classes

Final modifies the member variable, indicating that the member variable is the final variable, that is, a constant. Other parts of the program can be accessed, but cannot be modified. If final modifies a member method, the method cannot be overridden by subclasses and is the final method. Final modifies a class, which can no longer be inherited by other classes, that is, the class cannot have subclasses, which is called the final class
If a member variable is limited by two modifiers of static final, it is a constant and can only be assigned at the time of definition. If you define a member variable and only use final instead of static, it must and can only be assigned once and cannot be defaulted. You can assign an initial value when defining a variable or assign a value in a construction method

Object class

The Object class is the source of all classes.

equals() method

Use the "= =" and equals() methods to compare the similarities and differences of objects

class A{
    int a=1;
}
public class Obj {
    public static void main(String[] args) {
        A obj1=new A();
        A obj2=new A();
        String s1,s2,s3="qwe",s4="qwe";
        s1=new String("qwe");
        s2=new String("qwe");
        System.out.println("s1.equals(s2)yes"+(s1.equals(s2)));
        System.out.println("s1==s3 yes"+(s1==s3));
        System.out.println("s1.equals(s3)yes"+(s1.equals(s3)));
        System.out.println("s3==s4 yes"+(s3==s4));
        System.out.println("obj1.equals(obj2)yes"+(obj1.equals(obj2)));
        System.out.println("obj1==obj2 yes"+(obj1==obj2));
        System.out.println("obj1=obj2 after obj1.equals(obj2)yes"+(obj1.equals(obj2)));
    }
}

”=="Compare the first addresses of two objects in memory, and the equals () method compares whether the contents of the two strings are the same

toString() method

Function: convert the content of the object calling this method into a string and return its content

getClass() method

Function: returns the class to which the runtime object belongs

abstract class

Abstract classes are divided into pipe classes. Objects cannot be created, and classes of instance objects cannot be created with the new operator. It is shared by all its subclasses as a parent class

Abstract classes and abstract methods

Abstract class is a class decorated with abstract. The syntax format of defining abstract class is as follows:

abstract class Class name
{
    Declare member variables;
    The data type method name of the return value(Parameter table)
    {
    }
    abstract The data type method name of the return value(Parameter table);-Abstract method. Method body cannot be defined in abstract method
}

Abstract classes only need declarations, not implementations.
A subclass of an abstract class must implement all the abstract methods in the parent class, or declare itself abstract. When a method is declared as an abstract method, it means that the method must be overridden by the subclass's method.
abstract cannot modify the same method in parallel with private, static, final or native.

Application of abstract classes

Example: define a Shape abstract class Shape, and take this abstract class as the parent class to derive the circular subclass Circle and the rectangular subclass Rectangle.

abstract class Shape{
    protected String name;
    public Shape(String name){
        this.name=name;
        System.out.print("name"+name);
    }
    abstract public double getArea();
    abstract public double getLength();
}
class Circle extends Shape{
    private final double pi=3.14;
    private double radius;
    public Circle(String shapeName,double r)
    {
        super(shapeName);
        radius = r;
    }

    @Override
    public double getArea() {   //Implementing methods in abstract classes
        return pi*radius*radius;
    }

    @Override
    public double getLength() {    //Implementing methods in abstract classes
        return 2*pi*radius;
    }
}
class Ractangle extends Shape{
    private double width;
    private double height;
    public Ractangle(String shapeName,double width,double height){
        super(shapeName);
        this.width=width;
        this.height=height;
    }

    @Override
    public double getArea() {
        return width*height;
    }

    @Override
    public double getLength() {
        return 2*(width+height);
    }
}
public class A {
    public static void main(String[] args) {
        Shape rec=new Ractangle("rectangle",6.5,10.3);
        System.out.print(";the measure of area="+rec.getArea());
        System.out.println(";Perimeter="+rec.getLength());
        Shape cir=new Circle("circular",10.2);
        System.out.print(";the measure of area="+cir.getArea());
        System.out.println(";Perimeter="+cir.getLength());
    }
}

Interface

The data members of the interface are static and must be initialized, that is, the data members must be static constants;
In addition to declaring abstract methods, static methods and default methods can also be defined in the interface, but general methods cannot be defined.

Definition of interface

The syntax format is as follows:

[public] interface Interface name [extends List of parent interface names]
{
    [public] [static] [final]Data type constant name=constant;    //Define constants
    [public] [abstract]Data type and method name of the return value (parameter table);   //Define abstract methods
    [public] static Data type and method name of the return value (parameter table)
    {
         Method body
    }     //Define static methods
    [public] default Data type and method name of the return value (parameter table)
    {
         Method body
    }    //Define default method

Abstract methods in interfaces cannot have method implementations, i.e. method bodies, while static methods and default methods in interfaces must have method implementations, i.e. method bodies must be defined.

Implementation and reference of interface

Interfaces, like abstract classes, cannot create objects directly with new, so you must use the nature of the interface to create a new class, and then use it to create objects.
The process of creating a new class using an interface is called interface implementation. Similar to inheritance, the syntax format is as follows:

class Class name implements Interface name table{
}

When a class wants to implement an interface, pay attention to the following problems.

  1. If the class implementing an interface is not an abstract class, all abstract methods of the specified interface must be implemented in the definition part of the class
  2. When a class implements the abstract method of an interface, it must use the same method name. Otherwise, it is only defining a new method instead of implementing the existing abstract method
  3. Class must explicitly use the public modifier when implementing methods, otherwise it will be warned by the system that the access control scope of the methods defined in the interface has been narrowed
interface Shape{
    static final double pi=3.14;
    abstract public double getArea();
    abstract public double getLength();//Declare abstract methods
}
class Circle implements Shape{  //Implementing classes with interfaces
    double radius;
    public Circle(double r)
    {
        radius = r;
    }

    @Override
    public double getArea() {
        return pi*radius*radius;//Implementing methods in interfaces
    }

    @Override
    public double getLength() {
        return 2*pi*radius;
    }
}
class Ractangle implements Shape{
    private double width;
    private double height;
    public Ractangle(double width,double height){
        this.width=width;
        this.height=height;
    }

    @Override
    public double getArea() {
        return width*height;
    }

    @Override
    public double getLength() {
        return 2*(width+height);
    }
}
public class A {
    public static void main(String[] args) {
        Shape rec = new Ractangle(6.5, 10.3);//Declare a parent interface variable that points to a subclass object
        System.out.print("Rectangular area=" + rec.getArea());
        System.out.println(";Perimeter=" + rec.getLength());
        Shape cir = new Circle(10.2);
        System.out.print("Circular area=" + cir.getArea());
        System.out.println(";Perimeter=" + cir.getLength());
    }
}

Interface inheritance

Unlike class inheritance, an interface can have more than one parent interface, separated by commas to form a list of parent interfaces. The new interface will inherit all constants, abstract methods and default methods in the parent interface, but cannot inherit the static methods of the parent interface or be inherited by the implementation class. If the interface implemented by a class inherits from another interface, the Class must implement all methods defined in the interface inheritance chain.

interface Face1{
    static final double pi=3.14;
    abstract double area();
}
interface Face2{
    abstract void setColor(String c);
}
interface Face3 extends Face1,Face2{
    abstract void volume();
}
public class Cylinder implements Face3
{
    private double radius;
    private int height;
    protected String color;
    public Cylinder(double r,int h){
        radius=r;
        height=h;
    }
    public double area(){
        return pi*radius*radius;
    }
    public void setColor(String c){
        color=c;
        System.out.println("Color:"+color);
    }

    public void volume(){
        System.out.println("Cylinder volume:"+area()*height);
    }

    public static void main(String[] args) {
        Cylinder volu=new Cylinder(3.0,2);
        volu.volume();
        volu.setColor("gules");
    }
}

Keywords: Java

Added by danwguy on Sun, 21 Nov 2021 08:47:48 +0200