java abstract classes and interfaces

1. Abstract class

       java classes modified by abstract are abstract classes.

1.1 role of abstract class

       For example, charging by car, taxis have charging function, and buses have charging function, but the specific charges of each mode of transportation are different, such as 1 yuan / km for taxis and 1 yuan for buses.

      The common is the car charging function, but the difference is that they rewrite the charging function respectively. Therefore, we can understand that the car is an abstract class. Taxis / buses are subclasses of cars. Taxis / buses will inherit the charging function from the car, and then rewrite the charging function according to their actual situation to obtain their own charging function.

      Abstract classes actually provide the public content of the same type of things. The subclasses of abstract classes implement the public content provided by this abstract class according to their own actual situation. In this way, subclasses do not need to create this public content, but only need to inherit to rewrite it.

      Subclasses of abstract classes are often of the same type.

1.2 elements in abstract classes

       Abstract class ---- instance variable, static member variable, construction method, instance method, static method, [abstract method]

      Misunderstanding: whether a class is an abstract class does not depend on whether there are abstract methods. Abstract classes can have abstract methods or not. It mainly depends on whether there is abstract before class.

      abstract method format: the modifier abstract returns the value name ([parameter]);

                                  Note that there is no method body

Example:

//abstract class

public abstract class TestClass {

            public int  id=1001; //Instance variable

            public static String name="zhangsan"; //Static member variable

            public TestClass(){

                  System.out.println("Construction method");

            }

            public void shili(){

                  System.out.println("Example method");

            }

            public static void staticmethod(){

                  System.out.println("Static method");

            }

            //Abstract method -- a method without method body modified by abstract

            //abstract method: modifier abstract return value    Name ([parameter])

            public abstract  void abstractmethod();

}

1.3 specific usage of abstract class

       (1) Abstract classes cannot be new. If you need to access instance elements in an abstract class, you need to use subclasses to access them.

      (2) If an ordinary java class inherits an abstract class, you need to rewrite all the abstract methods in the abstract class, otherwise change the ordinary java class into an abstract class.

Example:

//Subclass

public class TestSonClass extends TestClass{

      //There are abstract methods in the parent abstract class, and the abstract methods need to be rewritten in the child class, otherwise an error will be reported

      public void abstractmethod() {

            System.out.println("Override abstract methods in subclasses");   

      }

}

Test class:

public class Main1 {

      public static void main(String[] args) {

            //new TestClass(); report errors

            //Access abstract classes with Subclasses

            TestSonClass tsc=new TestSonClass();

            System.out.println(tsc.id);

            System.out.println(TestSonClass.name);

            tsc.shili();

            TestSonClass.staticmethod();

            tsc.abstractmethod();

      }

}

      (3) Abstract classes can inherit other abstract classes without overriding abstract methods.

      (4) Create an abstract class object using the upper transformation object.

Upper transformation object:

      The object of the subclass is assigned to the variable of the parent class, and the subclass is transformed upward into the parent object.

      The upper transformation object cannot access the variables and methods of the subclass itself because it has been transformed into a parent class. If you need to access the variables and methods of the subclass itself, you need to force type conversion.

Example:

//Parent class

public class Person {

      public void methodPerson(){

            System.out.println("Person Class");

      }

}

//Subclass of Person

public class Student extends Person{

      public void methodStudent(){

            System.out.println("Student Class");

      }

}

Test class:

public class Main2 {

      public static void main(String[] args) {

            //Upper transformation object --- the object of the subclass is assigned to the variable of the parent class

            Person per=new Student();//At this point, per is the parent object

            //Try accessing subclass methods

            //per.methodStudent; report errors

            //Access parent object

            per.methodPerson();//Output the instance method of the Person class

           

            //If you need to output subclass objects and methods, you can cast them

            Student stu=(Student)per;

            stu.methodStudent();//Output instance method of Student class

      }

}

      (5) Abstract class objects can access instance variables, class variables, construction methods, instance methods, class methods, and abstract methods in abstract classes.

Example: only call abstract methods are demonstrated here. Instance variables, class variables, construction methods, instance methods and class methods in other call abstract classes are not demonstrated

//abstract class

public abstract  class TestClass {

      //Abstract method

      public abstract void  info();

}    



//Subclass

public class TestSonClass extends TestClass{

      public void info() {

            System.out.println("TestSunClass Subclass overrides parent TestClass Abstract method of");

      }

}

Test class:

public class Main3 {

      public static void main(String[] args) {

            //Create an abstract class on the transformation object

            TestClass tc=new TestSonClass();//tc is an abstract class

            tc.info();

           

      }



}

      (6) When an abstract class object accesses an abstract method, it actually accesses the abstract method after subclass rewriting.

      (7) When the method parameter in an ordinary java class is an abstract class type, it can pass the upper transformation object or a subclass object of the abstract class.

For example: ordinary java classes

public class PuTongClass {

      //When the method parameter in an ordinary java class is the abstract class type of the parent class

            public  void  testPuTong(TestClass tc){

                  System.out.println("PuTongClass Class");

                  tc.info();

            }

}

Test class:

public class Main3 {

      public static void main(String[] args) {

            PuTongClass puc=new PuTongClass();

            //puc.testPuTong(tc); An error is reported. The parameter TC is an abstract class and is not created in the main method

            //Back to creating abstract classes, the first method is to create abstract classes using upper transformation objects

            TestClass tc1=new TestSonClass();

            puc.testPuTong(tc1);

            //Create an abstract class. The second method uses the new subclass to create an abstract class

            TestSonClass tsc=new TestSonClass();

            puc.testPuTong(tsc);

      }

}

1.4 abstract class - game character instance

Example:

//Role parent

public abstract class JueSe {

      public abstract void attack();

}



//Role subclass - shooter

public class SheShou extends JueSe{

      public void attack() {

            System.out.println("Shooting physical attack");

      }

}



//Role subclass - mage

public class FaShi extends JueSe{

      public void attack() {

            System.out.println("Magic attack");

      }

}



//Ordinary java class -- games

public class Game {

            public static JueSe chooseJueSe(String name){

                  JueSe js=null;

                  if(name.equals("shooter")){

                       js=new SheShou();

                  }

                  if(name.equals("master")){

                       js=new FaShi();

                  }

                  return js;

      }

}

Test class:

//Main method

import java.util.Scanner;

public class YongHu {

      public static void main(String[] args) {

            System.out.println("Please select your role");

            //data input

            Scanner sc=new Scanner(System.in);

            String name=sc.next();

            //

            JueSe js=Game.chooseJueSe(name);

            js.attack();

      }

}

2. Interface

      The java element modified by the interface keyword is the interface.

      Format: public   interface   Interface name {}

                    interface   Interface name {}

2.1 interface function

      In order to overcome the single inheritance of java, multiple interfaces can be implemented.

      For example: charging, car taxi has the charging function [1 yuan / km], and aircraft has the charging function [1000 yuan for the whole journey]. Taxis and aircraft are not the same thing, but have the same function.

      In fact, an interface is to provide the public content of different types of things. The subclasses of the interface implement the public content provided by the interface according to their own actual situation. In this way, subclasses do not need to create this public content, but only need to inherit to rewrite it.

2.2 elements in the interface

       There can be class variables, static methods and abstract methods in the interface. Only these three types must be public modifiers. There can be no others. You can save them.

      (1) Variables in the interface must be class variables modified by public static; Public static can be omitted.

      (2) Class methods in the interface must be modified by public, which can be omitted;

      (3) The abstract methods in the interface must be modified by public abstract, which can be omitted.

Example:

//Interface

public interface TestInterface {

      //Static member variable

      int id=1000;//Is not an instance variable because public static is omitted

      static String name="zhangsan";//Omit public

      public int age=24;//Omit static Province

      //Example method

      //public void method(){}   // report errors

      //Static method

      public static void staticMethod(){}

      //Construction method

      //public TestInterface() {} / / error

   //Abstract method

      public abstract void method1();

}

Test class:

public class Main5 {

      public static void main(String[] args) {

      //Is the variable in the test interface a static member variable or an instance variable

      //The difference is that instance variables cannot be accessed by class names

            System.out.println(TestInterface.id);//Can be accessed by class name

            System.out.println(TestInterface.name);//Can be accessed by class name

            //TestInterface.id=1001;// An error is reported, indicating that the value cannot be modified. Variables that cannot be modified are constants  

      }

}

Therefore, the interface can be modified to include constants, static methods and abstract methods

      (1) Variables in the interface must be class variables modified by public static final; Public static final can be omitted.

      (2) Class methods in the interface must be modified by public, which can be omitted;

      (3) The abstract methods in the interface must be modified by public abstract, which can be omitted.

2.3 interface usage

       (1) The interface cannot be new. If you need to access abstract methods, you need to use the interface subclass

              The variables and static methods in the interface are static and can be accessed directly by class name without creating objects. However, to access the abstract methods in the interface, you can't use new. You need to use the interface subclass.

      (2) Class can implement one or more interfaces through the implements keyword.

      (3) If an ordinary class implements one or more interfaces, it needs to rewrite the abstract methods in each interface, otherwise it needs to change the ordinary class into an abstract class.

Example:

public interface TestInterface {

      public abstract void method1();

}

public interface DoxInterface {

      //Abstract method

      void abstractMethod();

}

public class PuTongClass implements TestInterface,DoxInterface{

      //There are abstract methods to override

      public void abstractMethod() {   

      }

      public void method1() { 

      }

}

      (4) Abstract classes implement one or more interfaces without rewriting the abstract methods in the interface.

                  Because there can be abstract methods in abstract classes, not ordinary classes

      (5) Interfaces can inherit interfaces and all elements in the parent interface.

            public interface DoxInterface extends TestInterface{ }

      (6) Create an interface object using the interface callback object

Interface callback object

         ① The interface callback object is very similar to the upper transformation object. The interface callback object - the subclass object of the interface is assigned to the interface variable.

         ② The interface callback object can only access the abstract method of the interface. In fact, it asks the abstract method rewritten by the subclass.

         ③ The interface callback object cannot access the method of the subclass itself. If you want to access it, you need to force type conversion.

Example:

//Interface parent class

public interface PersonInterface {

      void info();

}

//Interface subclass

public class Student implements PersonInterface{



      public void info() {

            System.out.println("Abstract method of rewriting interface");

      }

      public void me(){

            System.out.println("Methods of the subclass itself");

      }

}

public class Main6 {

   public static void main(String[] args) {

            //Interface cannot be new

            //new PersonInterface; report errors

            //Create interface object with interface callback object

            PersonInterface psi=new Student();//Interface object

            //The interface callback object can only access the abstract method of the interface. In fact, it asks the abstract method rewritten by the subclass

            psi.info();

            //The interface callback object cannot access the method of the subclass itself. If you want to access it, you need to force type conversion

            //psi.me(); report errors

            Student st=(Student)psi;

            st.me();      

      }

}

      (7) When the method parameter in a common java class is an interface type, you can pass an interface callback object or a subclass object of the interface.

3. Differences between abstract classes and interfaces

abstract class

Interface

abstract class

interface

Inheritance relationship

Extends   Single inheritance

Implementation relationship

Implements implements one or more interfaces

Provide public content of the same type of things

Provide public content for different types of things

There are instance variables, class variables, construction methods, instance methods and class methods

There are class variables (constants here), JDK8.0 class methods and abstract methods

Abstract methods can have public, protected, and default modifiers

The default modifier of interface method is public. Other modifiers cannot be used

4. Four keywords static this super final

4.1 static modifier

      (1) The variables modified by static are static member variables, which can be accessed by class name or object;

      (2) The method modified by static is a static method, which can be accessed by class name or object;

      (3) Static methods in the same class cannot access instance elements, and this cannot appear.

4.2 this current class object

      (1) In which class it appears, it represents the object of which class;

      (2) Accessing variables and methods in the current class in the constructor / instance method in the current class can be omitted.

(3) It cannot be omitted when accessing hidden member variables in constructor / instance methods in the current class.

4.3 objects of super parent class

       (1) When the first sentence of the construction method appears in the subclass, the super() parent class has no parameter construction method / the super (parameter) parent class has a parameter construction method;

      (2) The instance methods that appear in the subclass are variables / methods that represent accessing the parent class;

      (3) Access the hidden parent variable, super. Variable name. At this time, this super represents the object of the parent class. Generally, it refers to accessing the parent class method before overriding. The super. Method name ([parameter]). At this time, this super represents the object of the parent class

4.4 final modifier

       (1) The class modified by final cannot be inherited and has no subclasses;

public final class TestClass {

}

//Error: The type TestSunClass cannot subclass the final class TestClass

public class TestSunClass extends TestClass{

}

(2) Variables modified by final are constants and cannot be re assigned;

public class Main {

      public  static  void  main(String args[]){

            final String name="zhangsan"; //local variable

            System.out.println("name=="+name);

            //Error: the variable modified by final is a constant and cannot be re assigned

            //name="lisi";

            System.out.println("name=="+name);

      }

}

(3) The method modified by final cannot be overridden.

public  class TestClass {

      public final void  info(){

            System.out.println("TestClass Class");

      }

}

public class TestSunClass extends TestClass{

      /*

      Methods modified by fianl cannot be overridden.

      public  void  info(){

            System.out.println("Override info method inherited from parent class "");

      }

      */

}

Tags: Java Back-end

Posted on Fri, 05 Nov 2021 17:34:21 -0400 by tazz