当前位置:网站首页>Interface and abstract class / method learning demo
Interface and abstract class / method learning demo
2022-07-27 05:08:00 【if you never leave me, i will be with you till death do us apart】
Implement abstract methods
abstract class : Abstract classes simply cannot be used new Method to instantiate the class , That is, classes without concrete instance objects , Abstract classes are somewhat similar to “ Templates ” The role of , The purpose is to create and modify new classes according to their format , Objects cannot be created directly by abstract classes , New subclasses can only be derived from abstract classes , Then create objects from their subclasses , When a class is declared as an abstract class , You need to add a modifier in front of this class abstract, Member methods in abstract classes can include general methods and abstract methods
Abstract method : Abstract method is based on abstract The method of decoration , This method only declares the returned data type , Method name and required parameters , There is no method body , That is to say, the abstract method only needs to be declared and does not need to be declared in advance , When a method is abstract , This means that the method must be overridden by the method of the subclass , Otherwise, the method of its subclass is still abstract Of , And this subclass must also be abstract , That is to say abstract.
abstract class
understand :
1, When a class has no specific information to describe an object , Is defined as an abstract class .
characteristic :
1, Abstract class cannot be instantiated .
2, There are constructors ( Classes have constructors )
3, There can be no abstract methods in an abstract class , The class of the abstract method must be an abstract class
application : Model all the implementations that the parent class cannot determine , Instead, the subclass provides the class of the object to be implemented
Abstract method
1, The class of the abstract method must be an abstract class
2, Format : There is no method body {}
3, If a subclass inherits an abstract class , And rewrite all the abstract methods , Then this class is an entity class .
4, If you don't rewrite all abstract methods , Then this class must be an abstract class
5, Different objects have different processing methods , Then it makes no sense to define concrete in the parent class
Limit :
1,abstract Can't be used to modify properties , Constructors ,private,final,static
2, Constructors cannot be rewritten
3, Subclasses cannot override private The method of decoration
4,final Decorated cannot be rewritten
5,static Decorated direct call , If you use abstract There is no point in modifying it as abstract
Constructors , It's a special method . It is mainly used to initialize objects when creating objects , That is, to assign initial values to object member variables , Total and new Operators are used together in statements that create objects . A particular class can have multiple constructors , They can be distinguished according to the number of parameters or the type of parameters That is, overloading the constructor .
Interface ( english :Interface), stay JAVA Programming language is an abstract type , Is a collection of abstract methods , The interface usually uses interface To declare . A class inherits an interface by way of , So as to inherit the abstract methods of the interface .
Interfaces are not classes , Interfaces are written in a similar way to classes , But they belong to different concepts . Class describes the properties and methods of an object . The interface contains the methods that the class will implement .
Unless the class that implements the interface is an abstract class , Otherwise, the class will define all methods in the interface .
Interface cannot be instantiated , But it can be realized . A class that implements an interface , All methods described in the interface must be implemented , Otherwise, it must be declared as an abstract class . in addition , stay Java in , The interface type can be used to declare a variable , They can be a null pointer , Or be bound to an object implemented by this interface .
Please check the details rookie
describe
Known abstract classes Base It defines calculate Method , The calculation process of this method depends on sum() and avg(), The latter two methods are abstract methods . It is required to define Base Subclasses of Sub class , And implement the abstract method of the parent class , bring main The operation logic in the function is executed correctly .
Input description :
Two integers
Output description :
The sum of two integers divided by the average of the two integers ( The average value is int type , The decimal problem is not considered )
public static void main(String[] args) {
// Sub You need to define subclasses
Base base = new Sub();
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextInt()) {
int x = scanner.nextInt();
int y = scanner.nextInt();
base.setX(x);
base.setY(y);
System.out.println(base.calculate());
}
}
}
abstract class Base {
private int x;
private int y;
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public int calculate() {
if (avg() == 0) {
return 0;
} else {
return sum() / avg();
}
}
/** * return x and y And */
public abstract int sum();
/** * return x and y Average value */
public abstract int avg();
}
class Sub extends Base {
//write your code here......
}
Analysis of the answer :
Because the member variable of the parent class is private Type of , Therefore, subclasses can only be accessed through the functions of the parent class . Parent class calculate Method is called sum and avg Method , But these two methods are abstract methods , There is no definition in the parent class , We need to complete it in subclasses .
So we override in subclasses sum and avg Method , Calls a method of the parent class getX and getY Calculate the sum and mean value after obtaining the variable value .
public static void main(String[] args) {
// Sub You need to define subclasses
Base base = new Sub();
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextInt()) {
int x = scanner.nextInt();
int y = scanner.nextInt();
base.setX(x);
base.setY(y);
System.out.println(base.calculate());
}
}
}
abstract class Base {
private int x;
private int y;
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public int calculate() {
if (avg() == 0) {
return 0;
} else {
return sum() / avg();
}
}
/** * return x and y And */
public abstract int sum();
/** * return x and y Average value */
public abstract int avg();
}
class Sub extends Base {
@Override
public int sum() {
System.out.println(" and "+ (getX()+getY()));
return getX()+getY();
}
@Override
public int avg() {
System.out.println(" Average "+ (getX()+getY())/2);
// return (getX()+getY())/2;
return sum()/2;
}
The result is
5
6
Average 5
and 11
and 11
Average 5
and 11
2
Implementation interface
describe
Known interface Comparator, The interior defines max function , Used to return the maximum of two integers . Please define the implementation class of this interface , bring main The comparison logic in the method can be executed correctly , The name of the implementation class is required to be ComparatorImpl.
Input description :
Two integers
Output description :
The maximum of two integers
public static void main(String[] args) {
Comparator comparator = new ComparatorImpl();
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextInt()) {
int x = scanner.nextInt();
int y = scanner.nextInt();
System.out.println(comparator.max(x, y));
}
}
}
interface Comparator {
/** * Returns the maximum of two integers */
int max(int x, int y);
}
Analysis of the answer :
ComparatorImpl Implementation class override max Method
public static void main(String[] args) {
Comparator comparator = new ComparatorImpl();
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextInt()) {
int x = scanner.nextInt();
int y = scanner.nextInt();
System.out.println(comparator.max(x, y));
}
}
}
interface Comparator {
/** * Returns the maximum of two integers */
int max(int x, int y);
}
class ComparatorImpl implements Comparator{
@Override
public int max(int x, int y) {
// Three mesh operation
return x>y?x:y;
}
The result of the operation is
5
6
6
边栏推荐
- On the problem that Gorm's beforedelete hook method does not work
- Plato farm is expected to further expand its ecosystem through elephant swap
- What about PS too laggy? A few steps to help you solve the problem
- Flexible array and common problems
- 使用Druid连接池创建DataSource(数据源)
- 35.滚动 scroll
- How to sinicize the JMeter interface?
- Svn usage details
- 一道数学题,让芯片巨头亏了5亿美金
- 文件对话框
猜你喜欢

微淼联合创始人孙延芳:以合规为第一要义,做财商教育“正规军”

Svn usage details

Raspberry pie output PWM wave to drive the steering gear

"Photoshop2021 tutorial" adjust the picture to different aspect ratio

Review of various historical versions of Photoshop and system requirements

MySQL storage engine and its differences
![[search] - multi source BFS + minimum step model](/img/42/11b5b89153ab48d837707988752268.png)
[search] - multi source BFS + minimum step model
![[Niuke discussion area] Chapter 7: building safe and efficient enterprise services](/img/62/2b170e8dd5034708aebc6df0bc2b06.png)
[Niuke discussion area] Chapter 7: building safe and efficient enterprise services
![[error reporting]: cannot read properties of undefined (reading 'prototype')](/img/e4/528480610b9eed6028d7b3b87571e2.png)
[error reporting]: cannot read properties of undefined (reading 'prototype')

报错:cannot read poperties of undefined(reading ‘then‘)
随机推荐
Plato farm is expected to further expand its ecosystem through elephant swap
【搜索】Flood Fill 和 最短路模型
.htaccess learning
Use of file i/o in C
34. 分析flexible.js
Advantages of smart exhibition hall design and applicable industry analysis
Event Summary - common summary
Installation and template setting of integrated development environment pychar
节流函数的demo——正则表达式匹配
How to copy Photoshop layers to other documents
[untitled] I is circularly accumulated under certain conditions. The condition is usually the length of the loop array. When it exceeds the length, the loop will stop. Because the object cannot judge
Event filter
Svn usage details
The execution process of a select statement in MySQL
Approval of meeting OA
Introduction to dynamic memory functions (malloc free calloc realloc)
[search] connectivity model of DFS + search order
Constraints of MySQL table
再一个技巧,每月稳赚3万+
Hiding skills of Photoshop clipping tool