Bi Xiangdong - JAVA Foundation - Inheritance and Abstraction

1. Inheritance and abstract applications

/*
Suppose we need to model employees when developing a system, and employees contain 3 attributes:
Name, job number and salary. Managers are also employees. In addition to the attributes of employees, there is another
Bonus properties. Please use the idea of ​​inheritance to design employee class and manager class. Required methods are provided in the required class
method for attribute access.

Employee class: name id pay

Manager class: inherits employees and has its own unique bonus.

Managers and employees have no inheritance relationship, and have some common attributes and functions, but different functional content
*/
abstract class Employee
{
	private String name;
	private String id;
	private double pay;

	Employee(String name,String id,double pay)
	{
		this.name=name;
		this.id=id;
		this.pay=pay;
	}

	public abstract void work();
}

class Professional extends Employee
{
	Professional(String name,String id,double pay)
	{
		super(name,id,pay);
	}

	public void work()
	{
		System.out.println("professional work");
	}
}

class Manager extends Employee
{
	private int bonus;

	Manager(String name,String id,double pay,int bonus)
	{
		super(name,id,pay);
		this.bonus=bonus;
	}

	public void work()
	{
		System.out.println("namager work");
	}
}

2. Template method design pattern

/* Template method design pattern:
In the template method, when defining the function, part of it is determined, part of it is not determined, and the part that is determined uses the indeterminate part;
Expose the uncertain part, which is done by subclasses, not necessarily abstract, but can have default methods;
Certain parts can sometimes prevent duplication. final
*/

/*
Requirement: Get the running time of a program.
Principle: Get the start and end times of the program and subtract them.
*/
abstract class GetTime
{
	public final void getTime() //final avoid overwriting
	{
		long start=System.currentTimeMillis();//Get time

		runCode();

		long end=System.currentTimeMillis();

		System.out.println("Elapsed milliseconds: "+(end-start));
	}

	public abstract void runCode();//抽象
}

class SubTime extends GetTime
{
	public void runCode()//Override
	{
		for(int i=0;i<2000;i++)
		{
			System.out.print(i);
		}
	}
}

class GetTimeDemo
{
	public static void main(String[] args)
	{
		SubTime gt=new SubTime();
		gt.getTime();
	}
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324550751&siteId=291194637