Abstract Classes and Abstract Methods
abstract : abstract
abstract can be used to modify: classes, methods
abstract modifier class
> This class is called an abstract class
> abstract classes cannot be instantiated
> Abstract classes contain constructors, because the instantiation of objects of subclasses requires direct or indirect calls to the constructor of the parent class.
> An abstract class can have no abstract methods in it. Conversely, the class in which an abstract method resides must be an abstract class.
abstract method
> This method is an abstract method.
> Abstract methods have only method declarations, not method bodies.
> Abstract methods have a defined function (defined by the declaration of the method), but it is not known how to implement it (reflected in the absence of a method body).
> the subclass must override all abstract methods in the parent class before it can be instantiated, otherwise the subclass is still an abstract class (with abstract methods)
public abstract class Person { //abstract class String name; int age; public Person(){ } public Person(String name, int age){ this.name = name; this.age = age; } public abstract void eat(); //abstract method public void sleep(){ ("People will sleep."); } }
public class Student extends Person{ String school; public Student() { } public Student(String name, int age, String school) { super(name, age); this.school = school; } public void eat(){ ("Students eat more nutritious food."); } public void sleep() { ("Students need to get their sleep."); } }
public class AbstractTest { public static void main(String[] args) { // Person p1 = new Person(); no objects can be created after Person is set as an abstract class Student s1 = new Student(); (); } }
Scenarios where abstract cannot be used
abstractincapable of being modified: properties, constructors, code blocks, etc.
What keywords can't abstract be shared with: (self-consistent)
You cannot use abstract to modify private methods, static methods, methods that are final, or classes that are final.
> private methods cannot be overridden
> Avoid calling static methods with this class.
> final's methods cannot be overridden.
> A class modified by final cannot have subclasses.
TemplateMethod design pattern (TemplateMethod)
Problems solved:
- When part of the implementation within the function is deterministic and another part of the implementation is uncertain. At this point the uncertain part can be exposed for subclasses to implement.
- In other words, when implementing an algorithm in software development, the overall steps are very fixed and generic, and these steps are already written in the parent class.But some parts are mutable, and the mutable parts can be abstracted for different subclasses to implement, which is a template pattern.
Here we have designed a template method to calculate the time taken for the code to run, here code can be overridden in subsequent subclasses to calculate the time taken for the code to run.
/** * :: Abstract use case: design patterns for template approach */ public class TemplateTest { public static void main(String[] args) { PrintPrimeNumber p = new PrintPrimeNumber(); (); } } abstract class Template{ //Calculate the time it takes for a particular piece of code to execute public void spendTime(){ long start = (); code(); long end = (); ("The time spent was:" + (end -start)); } public abstract void code(); } class PrintPrimeNumber extends Template{ public void code(){ for (int i = 2; i <= 100000; i ++){ boolean isFlag = true; for (int j = 2; j <= (i); j++){ if (i % j == 0){ isFlag = false; break; } } if (isFlag){ (i); } } } }
case (law)
Write a payroll system to implement monthly payroll for different types of employees (polymorphic). If the birthday of an Employee object occurs during the month, increase the employee's salary by $100
Lab Description.
(1) Define aEmployee classThis class contains.
private member variables name, number, birthday, where birthday is an object of class MyDate.
Providing the necessary constructors, the
The abstract method earnings(), returns the amount of wages.
The toString() method outputs the name, number and birthday of the object.
public abstract class Employee { private String name; private int number; private MyDate birthday; public Employee() { } public Employee(String name, int number, MyDate birthday) { this.name = name; this.number = number; this.birthday = birthday; } public abstract double earnings(); //Abstract method Returns the amount of salary @Override public String toString() { return "name='" + name + "', number=" + number + ", birthday=" + birthday ; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getNumber() { return number; } public void setNumber(int number) { this.number = number; } public MyDate getBirthday() { return birthday; } public void setBirthday(MyDate birthday) { this.birthday = birthday; } }
(2) MyDate classContains.
private member variables year, month, day.
Provide the necessary constructors; the
The toDateString() method returns the string corresponding to the date, xxxx year xx month xx day
public class MyDate { private int year; private int month; private int day; public MyDate() { } public MyDate(int year, int month, int day) { this.year = year; this.month = month; this.day = day; } @Override public String toString() { return year + "Year." + month + "Moon." + day + "Day."; } public int getYear() { return year; } public void setYear(int year) { this.year = year; } public int getMonth() { return month; } public void setMonth(int month) { this.month = month; } public int getDay() { return day; } public void setDay(int day) { this.day = day; } }
3) DefinitionsSalariedEmployee classInherit Employee class to implement employee handling for monthly payroll calculation
This class contains: private member variable monthlySalary.
Provide the necessary constructors; the
Implements the parent class's abstract method earnings() This method returns the monthlySalary value.
The toString() method outputs the employee type information and the employee's name, number, and birthday. e.g.: SalariedEmployee[name = ' ' ,number = , birthday = xxxx year xx month xx day]
public class SalariedEmployee extends Employee{ private double monthlySalary; public SalariedEmployee() { } public SalariedEmployee(String name, int number, MyDate birthday, double monthlySalary) { super(name, number, birthday); this.monthlySalary = monthlySalary; } @Override public double earnings() { return monthlySalary; } @Override public String toString() { return "SalariedEmployee[ " + super.toString() + "]"; } public double getMonthlySalary() { return monthlySalary; } public void setMonthlySalary(double monthlySalary) { this.monthlySalary = monthlySalary; } }
(4) Define the HourlyEmployee class with reference to the SalariedEmployee class, which implements hourly payroll employee processing. The class includes
private member variables wage and hour.
Provide the necessary constructors; the
Implements the parent class's abstract method earnings() This method returns the value waqe*hour.
The toString0 method outputs the employee type information and the employee's name, number, birthday.
public class HourlyEmployee extends Employee{ private double wage; private int hour; public HourlyEmployee() { } public HourlyEmployee(String name, int number, MyDate birthday, double wage, int hour) { super(name, number, birthday); this.wage = wage; this.hour = hour; } @Override public double earnings() { return wage * hour; } @Override public String toString() { return "HourlyEmployee = [" + super.toString() + "]"; } public double getWage() { return wage; } public void setWage(double wage) { this.wage = wage; } public int getHour() { return hour; } public void setHour(int hour) { this.hour = hour; } }
(5) Define the PayrollSystem class, create and initialize the Employee variable array, which holds references to various employee objects.
Iterate through the elements of the array using the loop structure and output the type, name, number, birthday, and birthday of each object.
When the keyboard enters the value of the month, if this month is the birthday of an Employee object, also output the increase in salary information.
import ; public class PayrollSystem { public static void main(String[] args) { Scanner scan = new Scanner(); Employee[] employees = new Employee[2]; employees[0] = new SalariedEmployee("Little Ming.",10001,new MyDate(2000,12,25),3000); employees[1] = new HourlyEmployee("Little Red.",10002,new MyDate(2001,1,9),100,32); ("Please enter the current month:"); int month = (); for (int i = 0; i < ; i++){ (employees[i].toString()); if (month == employees[i].getBirthday().getMonth()){ ("This month's birthday!!!"); ("Wages:" + (employees[i].earnings() + 100)); }else{ ("Wages:" + employees[i].earnings()); } } } }
connector
Interfaces are essentially contracts, standards, and specifications. Like laws, they are made and then everyone has to follow them
The keyword that defines the interface:interface
A description of the internal structure of the interface:
> can be declared:
Attribute: must be modified with public static final
Methods: Prior to jdk8: Declare abstract methods, modified as public abstract
jdk8: declare static methods, default methods
jdk9: declaring private methods
> Cannot declare: constructors, code blocks, etc.
Interface-Class Relationship: Implementation Relationship
Format: class A extends SuperA implements B,C{ }
A is called a subclass compared to SuperA.
A is called an implementation class compared to B,C.
After satisfying this relation, the description:
> Classes can implement multiple interfaces.
> Multi-implementation of classes against interfaces compensates, to some extent, for the limitations of single inheritance of classes.
> A class must override (or implement) all of the abstract methods in the interface it implements before it can be instantiated. Otherwise, this implementing class must be declared as an abstract class.