XII [Java] object oriented abstract classes and abstract methods

Posted by cabldawg on Wed, 16 Feb 2022 22:54:58 +0100

catalogue

01 abstract class

1.1 examples of abstract application scenarios

1.2 abstract precautions

1.3 practice of abstract class

1.4 anonymous subclasses of abstract classes

1.5 concrete application of abstraction: template method

1.6 practice of abstract class

01 abstract class

With the definition of new subclasses in the inheritance hierarchy, the class becomes more and more specific, while the parent class is more general and general. Class design should ensure that parent and child classes can share features. Sometimes a parent class is designed so abstract that it has no concrete instance. Such a class is called an abstract class

Decorated class (abstract class)

/*
abstract Decoration class: abstract class
 * 	> This class cannot be instantiated
 *  > There must be a constructor in the abstract class, which is convenient for calling when subclass instantiation (involving: the whole process of subclass object instantiation)
 *  > During development, subclasses of abstract classes will be provided to instantiate subclass objects and realize relevant operations
*/
public class AbstractTest {
    public static void main(String[] args){
        Person1 person = new Person1(); // Error reporting cannot be instantiated
        Student student = new Student();

    }
}

abstract class Person1{  //Adjective class
    String name;
    int age;

    public Person1() {
    }

    public Person1(String name, int age) {
        this.name = name;
        this.age = age;
    }

}
// Subclasses can be instantiated
class Student extends Person1{
    public Student(String name, int age){
        super(name, age);
    }
}

Modification method (abstract method)

4.abstract Modification method:Abstract method
 *  > Abstract method, only method declaration, no method body.
 *  > A class containing abstract methods must be an abstract class. Conversely, there can be no abstract methods in an abstract class
           Abstract methods cannot be called, so it is necessary to ensure that classes cannot be instantiated
 *  > If a subclass overrides all the abstract methods in the parent class, the subclass can be instantiated. Otherwise, the subclass is also an abstract class

abstract class Creature{
	public abstract void breath();  // Can only be declared, no method body
}

abstract class Person extends Creature{
	String name;
	int age;
	
	public Person(){
		
	}
	
	public Person(String name,int age){
		this.name = name;
		this.age = age;
	}
	
	//Not an abstract method
//	public void eat(){
//		System.out.println("people eat");
//	}
	
	//Abstract method
	public abstract void eat();  // At this point, the Person class has two abstract methods
	
	public void walk(){
		System.out.println("Human walking");
	}
}

class Student extends Person{
	public Student(String name,int age){
		super(name,age);
	}
	public void eat(){  // Override the abstract method of the parent class
		System.out.println("Students should eat more nutritious food.");
	}
	@Override
	public void breath() { // Also override the abstract methods of the root class
		System.out.println("Students should breathe fresh haze free air");
	}
}

1.1 examples of abstract application scenarios

Abstract classes are classes used to model objects whose parent class cannot determine all implementations, but whose child classes provide concrete implementations.

/* Java Allows the class designer to specify that a superclass declares a method but does not provide an implementation, and the implementation of the method is provided by a subclass. Such methods are called abstract methods. A class with one or more abstract methods is called an abstract class.
 * Vehicle Is an abstract class with two abstract methods.
 * Note: abstract classes cannot instantiate new Vihicle(), which is illegal
 */
public abstract class Vehicle{
	public abstract double calcFuelEfficiency();//Abstract method for calculating fuel efficiency
	public abstract double calcTripDistance();//Abstract method for calculating driving distance
}

public class Truck extends Vehicle{
	public double calcFuelEfficiency(){ 
		//Write a specific method for calculating the fuel efficiency of trucks
	}
	public double calcTripDistance(){ 
		//Write down the specific method of calculating the distance traveled by the truck
	}
}

public class RiverBarge extends Vehicle{
	public double calcFuelEfficiency() { 
		//Write a specific method to calculate the fuel efficiency of the barge
	}
	public double calcTripDistance( )  {  
		//Write down the specific method for calculating the distance traveled by the barge
	}
}

1.2 abstract precautions

  • abstract cannot be modified: properties, constructors and other structures (constructors themselves cannot be rewritten and can only be overloaded)
  • abstract cannot be modified
    • Private method (private method cannot be overridden in subclass, but abstract will always be overridden in subclass)
    • The child and parent methods of static method are static, which is not called rewriting
    • Final methods and classes: final cannot be overridden; Nor can it be inherited

1.3 practice of abstract class

Employee (abstract class)

/*
 * Write an Employee class and declare it as an abstract class,
 * It contains the following three attributes: name, id and salary.
 * Provide the necessary constructor and abstract method: work().
 * For employees, the bonus category also has Bonus attribute.
 * Please use the idea of inheritance to design CommonEmployee class and Manager class,
 * Require the class to provide the necessary methods for property access.
 * 
 */
public abstract class Employee {
	
	private String name;
	private int id;
	private double salary;
	
	public Employee(){
		super();
	}

	public Employee(String name, int id, double salary) {
		super();
		this.name = name;
		this.id = id;
		this.salary = salary;
	}
	
	public abstract void work();	
}

Manager class

/*
 * For the Manager class, it is not only an employee, but also has the attribute of bonus.
 * 
 */
public class Manager extends Employee{

	private double bonus;	//bonus
	
	public Manager(double bonus) {
		super();
		this.bonus = bonus;
	}
	
	public Manager(String name, int id, double salary, double bonus) {
		super(name, id, salary);
		this.bonus = bonus;
	}


	@Override
	public void work() {
		System.out.println("Manage employees and improve the operation efficiency of the company.");		
	}
}

1.4 anonymous subclasses of abstract classes

public class Num {

}

abstract class Creature{
	public abstract void breath();
}

abstract class Person extends Creature{
	String name;
	int age;
	
	public Person(){
		
	}
	
	public Person(String name,int age){
		this.name = name;
		this.age = age;
	}
	
	//Not an abstract method
//	public void eat(){
//		System.out.println("people eat");
//	}
	
	//Abstract method
	public abstract void eat();
	
	public void walk(){
		System.out.println("Human walking");
	}
}

class Student extends Person{
	public Student(String name,int age){
		super(name,age);
	}
	public Student(){

	}
	public void eat(){
		System.out.println("Students should eat more nutritious food.");
	}
	@Override
	public void breath() {
		System.out.println("Students should breathe fresh air without haze");
	}
}

PersonTest class

/*
 * Anonymous subclass of abstract class
 * 
 */
public class PersonTest {
	public static void main(String[] args) {
		
		method(new Student());	//Anonymous object, anonymous object only used once
		
		Worker worker = new Worker(); 
		method1(worker);	//Non anonymous class non anonymous object
		
		method1(new Worker());	//Non anonymous class object
		
		System.out.println("*********************");
		
		//Created an object of an anonymous subclass: p here is an anonymous subclass
		Person p = new Person(){

			@Override
			public void eat() {
				System.out.println("Eat something");
			}

			@Override
			public void breath() {
				System.out.println("Breathe air");
			}
			
		};
		method1(p);

		System.out.println("**********************"); 
		//Create anonymous objects of anonymous subclasses
		method1(new Person(){

			@Override
			public void eat() {
				System.out.println("eat snacks between meals");
			}

			@Override
			public void breath() {
				System.out.println("Air in Yunnan");
			}
			
		});
	}
	
	public static void method1(Person p){
		p.eat();
		p.walk();
	}
	
	public static void method(Student s){
		
	}
}
class Worker extends Person{
	
	@Override
	public void eat() {
	}

	@Override
	public void breath() {
	}
}

1.5 concrete application of abstraction: template method

Abstract class embodies the design of a template pattern. Abstract class is the general template of multiple subclasses. Subclasses expand and transform on the basis of abstract class, but subclasses will retain the behavior of abstract class as a whole.

Problems solved:

When part of the internal implementation of a function is certain, part of the implementation is uncertain. At this time, you can expose the uncertain part and let the subclass implement it.

When implementing an algorithm in software development, the overall steps are very fixed and general. These steps have been written in the parent class. However, some parts are changeable, and the changeable parts can be abstracted for different subclasses to implement. This is a template mode.

 

ublic class TemplateTest {
    public static void main(String[] args){
        Template template = new subTemplate();
        template.spendTime();
    }

}


abstract class Template{

    // Calculate how long a piece of code takes to execute
    public void spendTime(){
        long start = System.currentTimeMillis();
        code();  // Uncertain part
        long end = System.currentTimeMillis();
        System.out.println(end - start);

    }

    public abstract void code(); // Abstract method
}

// Override abstract methods in subclasses
class subTemplate extends Template{

    @Override
    public void code() {

        for(int i = 2 ; i <= 1000; i++){
            boolean isFlag = true;
            for(int j = 2; j <= Math.sqrt(i) ; j++){
                if(i % j == 0){
                    isFlag = false;
                    break;
                }
            }
            if(isFlag == true){
                System.out.println(i);
            }
        }

    }
}

1.6 practice of abstract class

 

Class writing

abstract class Employee {
    private String name;
    private int id;
    private MyDate birthday;

    public Employee(String name, int id, MyDate birthday) {
        this.name = name;
        this.id = id;
        this.birthday = birthday;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public MyDate getBirthday() {
        return birthday;
    }

    public void setBirthday(MyDate birthday) {
        this.birthday = birthday;
    }

    public abstract double earings();

    public String toString(){
        return "Employee:" + name + " " + id + " " + birthday.toDateString();
    }
}

class MyDate{
    private int year;
    private int month;
    private int  day;

    public MyDate(int year, int month, int day) {
        this.year = year;
        this.month = month;
        this.day = day;
    }

    public String toDateString(){
        return year + "year" + month + "month" + day + "day";
    }

    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;
    }
}

class SalariedEmployee extends Employee{
    private double monthlySalary;

    public SalariedEmployee(String name, int id, MyDate birthday, double monthlySalary) {
        super(name, id, birthday);
        this.monthlySalary = monthlySalary;
    }


    @Override
    public double earings() {
        return monthlySalary;
    }

    @Override
    public String toString() {
        return "SalariedEmployee{" + this.getName() + " " +  this.getId() + " " + this.getBirthday().toDateString() +
                " monthlySalary=" + monthlySalary +
                '}';
    }
}

class HourlyEmployee extends Employee{
    private int wage;
    private int hour;

    public HourlyEmployee(String name, int id, MyDate birthday, int wage, int hour) {
        super(name, id, birthday);
        this.wage = wage;
        this.hour = hour;
    }

    public int getWage() {
        return wage;
    }

    public int getHour() {
        return hour;
    }

    public void setWage(int wage) {
        this.wage = wage;
    }

    public void setHour(int hour) {
        this.hour = hour;
    }

    @Override
    public double earings() {
        return wage * hour;
    }

    @Override
    public String toString() {
        return "HourlyEmployee{" + this.getName() + " " + this.getId() + " " + this.getBirthday().toDateString() + "}";
    }
}

Main program test

import java.util.Scanner;

public class PayrollSystem {
    public static void main(String[] args){
        Employee[] employees = new Employee[4];
        employees[0] = new SalariedEmployee("Masen", 1001, new MyDate(1997,12,30),5000);
            // Array initialization, each index is equivalent to a new object
        employees[1] = new SalariedEmployee("WangSan", 1002, new MyDate(1996,10,20),11000);
        employees[2] = new HourlyEmployee("LiSi", 1009, new MyDate(1996,10,20),10, 70);
        employees[3] = new HourlyEmployee("ZhangWu", 5000, new MyDate(1998,7,20),10, 70);

        Scanner scanner = new Scanner(System.in);
        int month = scanner.nextInt();
        for(int i = 0; i < employees.length; i++){
            System.out.print(employees[i].toString());
            if(month == employees[i].getBirthday().getMonth()){
                System.out.println("This month's bonus is 100 yuan");
            }
            System.out.println();
        }

    }
}

 

 

Topics: Java Back-end