About the relationship between objects, classes, abstract classes, interfaces and inheritance in Java:
Reading Guide:
During the winter vacation, I learned the basics of JavaSE. There are many concepts that are true and relevant. I will review some relevant knowledge points again and straighten out the relationship between them.
Text:
For example: if you want to define an animal now, the animal must be a public standard, and this public standard can be completed through the interface.
Animals are divided into two categories: mammals and oviparous animals. This standard is a further refinement of animal standards and should be called sub standard. Therefore, this relationship can be expressed by interface inheritance.
Mammals i can continue to be divided into human, dog, cat and other different types. Since these types do not represent specific standards of things, they can be represented by abstract classes.
If you want to express the concept of worker or student, it must be a specific definition. Use the way of class.
Then each student or worker is specific, then it is expressed by object;
As can be seen from the following figure, in all designs, interfaces should be designed first and inherited by subclasses.
Code instantiation:
package Java From introduction to project practice.Abstract classes and interfaces; //animal interface animal{ public abstract String breathe(); } //Mammalian - interface inheritance extend //Class implementation -- implements interface mammals extends animal { // Global method // Abstract method } //Oviparous animal interface Egg_laying_animals extends animal { // Global method // Abstract method } //Define human abstract classes (belonging to mammals) abstract class peopel implements mammals{ } //Define non-human abstract classes (input mammals) abstract class small_animal implements mammals{ } //Students belong to human beings class student extends peopel{ @Override public String breathe() { return null; } } public class Interface synthesis { public static void main(String[] args) { // Objects: instantiation of classes student std = new student(); System.out.println(std.breathe()); } }
Interface:
-
Basic definition of interface:
package Java From introduction to project practice.Abstract classes and interfaces; interface IMessageF{ //Global variables, abstract methods (public permissions), default methods and static methods can be defined in the interface; //If there are abstract methods in the interface, the interface must be instantiated by subclasses public static final String INFO = "xbhog"; //global variable public abstract String getInfo(); //Abstract method } class MessageIpml implements IMessageF{ @Override public String getInfo(){ //Method override return "hello xbhog!"; //Get message } } public class Basic use of interface { public static void main(String[] args) { //Call instantiation of interface IMessageF msg = new MessageIpml(); //Subclass instantiation parent class interface System.out.println(msg.getInfo()); } }
-
Subclasses implement multiple parent interfaces and instance transformations
package Java From introduction to project practice.Abstract classes and interfaces; interface Imessage1{ public static final String INFO = "xbhog"; public abstract String getInfo(); } interface IChannel{ public abstract boolean connect(); } //It implements multiple interfaces and inherits two, so it is necessary to override the abstract methods in the parent class in the subclass class MessageImpl1 implements Imessage1,IChannel{ @Override public String getInfo(){ if(this.connect()){ return "Blog address: www.cnblogs.com/xbhog/"; } return "[[default message]"+ Imessage1.INFO; } @Override public boolean connect(){ return true; } } public class Subclasses implement multiple parent interfaces { public static void main(String[] args) { Imessage1 msg = new MessageImpl1(); System.out.println(msg.getInfo()); //--------Observe interface instance conversion------------- Imessage1 msg1 = new MessageImpl1(); Object obj = msg1; //Upward transformation IChannel channel = (IChannel) obj; //Object is cast to an IChannel interface instance System.out.println(channel.connect()); } }
-
Subclasses inherit abstract classes and implement interfaces at the same time
package Java From introduction to project practice.Abstract classes and interfaces; //Message interface interface IMessage1{ public static final String INFO = "xbhog"; public abstract String getInfo(); } //Channel interface interface IChannel1{ public abstract boolean connect(); } //Define an abstract class abstract class DatabaseAbstract{ public abstract boolean getDatabaseConnection(); } //Inherit from abstract classes and implement interfaces at the same time class MessageImpl2 extends DatabaseAbstract implements IMessage1,IChannel1{ @Override public String getInfo() { if (this.connect()){ if(this.getDatabaseConnection()){ return "[[database message] blog address: https://www.cnblogs.com/xbhog/"; }else { return "Database message cannot be accessed!"; } } return "[[default message]:"+IMessage1.INFO; } @Override public boolean connect() { return true; } @Override public boolean getDatabaseConnection() { return true; } } public class Subclasses inherit abstract classes and implement interfaces { public static void main(String[] args) { IMessage1 msg = new MessageImpl2(); System.out.println(msg.getInfo()); } }
-
Extensions inherits multiple parent interfaces
Simplification of interfaces: when defining interfaces, the static final and abstract keywords can be omitted for global constants and abstract methods;
package Java From introduction to project practice.Abstract classes and interfaces; interface Imessage3{ public static final String INFO = "xbhog"; public abstract String getInfo(); } interface IChannel3{ public boolean connect(); //Abstract method, omitting abstract; } interface IService extends Imessage3,IChannel3{ public String service(); //Abstract method, omitting abstract; } class MessageService implements IService{ @Override public String getInfo() { return Imessage3.INFO; } @Override public boolean connect() { return false; } @Override public String service() { return "[Database message service]: https://www.cnblogs.com/xbhog/"; } } public class use extends Inherit multiple parent interfaces { public static void main(String[] args) { } }
-
Interface strengthening
Why we need to strengthen the interface: first of all, we need to understand that the subclass under the interface needs to overwrite the methods of the parent class. If there are more than 1000 subclasses under the interface, and unfortunately, the interface needs to add methods, then each subclass needs to overwrite the newly added methods. It's terrible to think about it; On this basis, the compensation method is added
-
Add the common method of default definition: it is convenient to expand the interface and simplify the design structure
package Java From introduction to project practice.Abstract classes and interfaces; interface IMessage{ // Must override public String message(); //abstract class public default String messageSmple(){ return "null"; }; // Defining common methods of interfaces increases the flexibility of interfaces // When there are too many subclasses and a new method is added, each subclass needs to be overridden // The common method of default solves this problem by overriding subclasses when needed and placing them when not needed public default boolean connect(){ System.out.println("Build attention xbhog Channel of...."); return true; } } class MessageImpl implements IMessage{ public String message(){ return "xbhog"; } } public class Enhanced use of interface definition default Define common methods { public static void main(String[] args) { IMessage msg = new MessageImpl(); if(msg.connect()){ System.out.println(msg.message()); } } }
-
default disadvantage: the object must be instantiated through the interface before it can be called. In order to avoid the dependence of the instantiated object, you can use the static method to hide the details of the interface call
package Java From introduction to project practice.Abstract classes and interfaces; interface ImessageS{ public String message(); // Defines a public method that is inherited by all subclasses public default boolean connect(){ System.out.println("Establish subscription xbhog Blog channel....."); return true; } // Establish static static methods, which can be called directly through the interface name public static ImessageS getInstance(){ // Get subclass object return new MessageImple(); } } class MessageImple implements ImessageS{ public String message(){ if(this.connect()){ return "www.cnblogs.com/xbhog"; } return "null"; } } public class Define in interface static method { public static void main(String[] args) { // Instantiate subclass interface object ImessageS msg = ImessageS.getInstance(); System.out.println(msg.message()); } }
-
Abstract class:
Characteristics of abstract classes:
-
A class containing abstract methods must be an abstract class
-
Abstract classes do not necessarily have abstract methods
-
Abstract classes can have both abstract and non abstract methods
-
If a subclass inherits an abstract method, either override the abstract method in the abstract class, or the subclass is declared as an abstract class
-
You cannot create an object because there is no concrete implementation of the method. Creating an object has no effect. Abstract classes are used to inherit
-
Basic definition
abstract class Message{ private String type; public abstract String getConnectInfo(); //Abstract method public void setType(String type){ //Common method this.type = type; } }
-
Construction method of abstract class
package Java From introduction to project practice.Abstract classes and interfaces; //Constructing abstract methods abstract class abMessage{ private String type; //At this time, no parameter free construction method is provided in the abstract class, so the single parameter construction method must be explicitly called in the subclass public abMessage(String type){ this.type = type; } public abstract String getContentInfo(); public String getType() { return type; } public void setType(String type) { this.type = type; } } class Database extends abMessage{ //Subclass construction public Database(String type) { //Call the parent class single parameter constructor super(type); } //Override abstract class methods @Override public String getContentInfo() { return "["+super.getType()+"]Database connection information"; } } public class Construction method { public static void main(String[] args) { abMessage demo = new Database("xbhog"); System.out.println(demo.getContentInfo()); } }
-
static method defined in abstract class: this kind of method is not limited by the instantiation object of abstract class
package Java From introduction to project practice.Abstract classes and interfaces; abstract class message{ public abstract String getInfo(); public static message getInstance(){ return new datamessage(); } } class datamessage extends message{ @Override public String getInfo() { return "xbhog Database connection"; } } public class Abstract class definition static { public static void main(String[] args) { //Because this method is modified by static, message is used globally GetInstance is equivalent to new datamessage(); message mes = message.getInstance(); System.out.println(mes.getInfo()); } }
-
Template design mode
package Java From introduction to project practice.Abstract classes and interfaces; //Abstract three public behaviors abstract class Action{ static final int EAT = 1; //Meal instruction static final int SLEEP = 5; //Sleep instruction static final int WORK = 10; //Work order public abstract void eat(); public abstract void sleep(); public abstract void work(); public void command(int code){ switch (code){ case EAT:{ this.eat(); break; } case SLEEP:{ this.sleep(); break; } case WORK:{ this.work(); break; } case EAT+SLEEP+WORK:{ this.eat(); this.sleep(); this.work(); break; } } } } //Figurative robot class Rebot extends Action{ @Override public void eat() { System.out.println("The robot needs to be powered on and charged"); } @Override public void sleep() { } //Robots don't need to sleep @Override public void work() { System.out.println("The robot works according to fixed settings"); } } //Figurative person class Person extends Action{ @Override public void eat() { System.out.println("People need to eat cereals to maintain vitality"); } @Override public void sleep() { System.out.println("You'll die if you don't sleep"); } @Override public void work() { System.out.println("Work every day 996"); } } //Figurative pig class pig extends Action{ @Override public void eat() { System.out.println("Eat hard, fatten up and sell money"); } @Override public void sleep() { System.out.println("No sleep, no fat"); } @Override public void work() { } } public class Template design mode { public static void main(String[] args) { Action rebotAction = new Rebot(); Action personAction = new Person(); Action pigAction = new pig(); System.out.println("Robot behavior---------"); rebotAction.command(Action.SLEEP); rebotAction.command(Action.WORK); System.out.println("Human behavior----------"); personAction.command(Action.WORK+Action.SLEEP+Action.EAT); System.out.println("Pig behavior-------"); pigAction.command(Action.SLEEP); } }
Comprehensive case exercise:
Implementation related codes:
package Java From introduction to project practice.Abstract classes and interfaces; //Define the human class abstract class people{ private String name; private String age; public people() {} public people(String name,String age){ this.name = name; this.age= age; } public abstract void eats(); //Define abstract methods public void setName(String name) { this.name = name; } public void setAge(String age) { this.age = age; } public String getName() { return name; } public String getAge() { return age; } } //Define an abstract class abstract class athletes extends people{ public athletes(){} public athletes(String name, String age){ super(name,age); } // Abstract method public abstract void study(); } interface speakEnglish{ public abstract void speak(); } //Define the abstract class of the coach abstract class coach extends people{ public coach(){} public coach(String name,String age){ super(name,age); } public abstract void teach(); } //Basketball players class Basketball_player extends athletes{ public Basketball_player(String name, String age){ super(name,age); } @Override public void eats() { System.out.println("The basketball player is having dinner...."); } @Override public void study() { System.out.println("Basketball players are learning......"); } } //Table tennis far mobilization class pingpang extends athletes implements speakEnglish{ public pingpang(String name, String age){ super(name,age); } @Override public void eats() { System.out.println("The table tennis player is eating...."); } @Override public void study() { System.out.println("Table tennis players are learning......"); } @Override public void speak() { System.out.println("Table tennis players practice oral English......"); } } //Table tennis coach class pingpangCoach extends coach implements speakEnglish{ public pingpangCoach(String name, String age){ super(name,age); } @Override public void eats() { System.out.println("The table tennis coach is having dinner....."); } @Override public void teach() { System.out.println("The table tennis coach is teaching...."); } @Override public void speak() { System.out.println("Table tennis coaches practice oral English....."); } } //Basketball coach class BasketballCoach extends coach{ public BasketballCoach(String name, String age){ super(name, age); } @Override public void eats() { System.out.println("The basketball coach is having dinner"); } @Override public void teach() { System.out.println("The basketball coach is teaching......"); } } public class Comprehensive case realization { public static void main(String[] args) { } }
end:
Sort out the relevant concepts of Java recently learned and clarify their ideas.
If there are mistakes, please correct them. Thank you for seeing the last!