Q9: How to let the expression "be one" and "have a" relationship. Or, explain "inheritance" and "combination." What is the difference between composition and aggregation.
A9: "A" is a relationship that represents inheritance and the "one" relationship is the representation combination. Inheritance and grouping all allow you to put child objects into the new class. The two main techniques for code reuse are class inheritance and object composition.
Inheritance is one-way. For example, a house is a building, but a building is not a house. Inheritance uses the extends keyword.
Combination: Used to express the house has a bathroom. It's not accurate to say that the house is a bathroom. The combination simply uses instance variables to refer to other objects, such as house class owning an instance variable, referencing a bathroom object.
Q: Which one is better. Combination or inheritance.
A: The guide is to use inheritance only if the subclass is a parent class. Do not use inheritance just for code reuse. If there is no "one" relationship, you should use combinatorial syntax. Overuse of implementation inheritance (using the "extended" keyword) destroys all subclasses, especially if the superclass needs to be modified. Don't use inheritance just to get polymorphism. If there is no "one" relationship and you want polymorphism, then use interface inheritance and combinatorial syntax.
Q: What is the difference between composition and aggregation?
A: They all express the relationship between the whole and the local. Aggregation relationships, where local can exist independently of the whole. For example, a line item and product are overall and partial relationships. If a row item is deleted, the corresponding product does not need to be deleted. So aggregation is a weaker relationship. A combination of relations, the local can not be independent of the whole and exist. If a whole is deleted, all parts will also be deleted. For example, an order and a project are a whole and a partial relationship. If an order is deleted, the corresponding line item should also be deleted. So the combination has a stronger relationship.
Q10: How do you understand inheritance, encapsulation, polymorphism, and dynamic binding?
A10:polymorphism Polymorphism -describes the ability that a variable of a given type can be used to refer to different types of objects (of course, these types are required to be a subclass of a given type), but the invocation is a method on the specific type of the object referenced by the variable. In short, polymorphism is a bottom-up method invocation. The advantage of polymorphism is that it is easy to add new extension classes without breaking the original calling code. When sending a message to an object (calling a method), you don't even know the exact type of the object, but the correct behavior occurs, which is polymorphism.
The process of implementing polymorphism in object-oriented programming languages is called dynamic binding. (Run-time type inference.) )
Inheritance Inheritance --the behavior of the base class (that is, the method) and the state (that is, the variable) are included in the derived class so that they can be accessed in the derived class. The key benefit is that it provides a formal mechanism for code reuse.
The public part of any business logic can be moved from a derived class to a base class, doing so during refactoring to avoid code duplication and improve the maintainability of the code.
An existing class is called a base class and a derived class is called a subclass. Inheritance can also be defined as a process in which an object obtains the characteristics of one or more other objects, just as a child obtains features from his or her parents.
There are two types of inheritance:
1, implementation inheritance: You can extend a program by inheriting the functionality already implemented in some or all of the parent classes. In Java, you can inherit only from a superclass. Implementation inheritance promotes reusability, but incorrect inheritance usage can lead to programming nightmares because it destroys encapsulation and poses problems for future changes. With implementation inheritance, subclasses become tightly coupled with the parent class. This makes the design vulnerable, and if you want to change the parent class, you have to understand the details of the subclasses to avoid destroying them. So use implementation inheritance to ensure that subclasses depend only on the behavior of the parent class, not the actual implementation.
2. Interface inheritance: Interfaces provide a mechanism for linking unrelated classes--by specifying a series of common methods that must be contained by these implementation classes. (Implementation classes can be unrelated.) Interface inheritance promotes the principle of "interface-oriented programming rather than implementation-oriented programming." This reduces the coupling between the systems. In Java, you can implement any number of interfaces. This is more flexible than "implementation inheritance" because it does not lock you in to a specific implementation that makes subclasses difficult to maintain. Also be careful that modifying an interface destroys the implementation class.
Which one to use? Preference is given to interfaces because they conform to the concept of "interface-oriented programming" and can reduce coupling. Interface inheritance enables the reuse of code with the help of an object combination. If you look at the Gof design pattern, you will find that they prefer interface inheritance to actual inheritance.
Implementation Inheritance Case:
Package CH08_EXTENDS3;
/** * Suppose that a demand deposit and a term deposit have a type of behavior on the access behavior, we define the implementation of these two behaviors in the parent class.
* <p> but demand and term deposits behave differently in calculating interest.
* @author Zhengwei 2013-7-13 * * Public abstract class Account {public void deposit (double amount) {
System.out.println ("depositing" + amount);
public void withdraw (double amount) {System.out.println ("withdrawing" + amount);
public abstract double Calculateinterest (double amount); Class SavingsAccount extends Account {public double calculateinterest (double amount) {/CAL
Culate interest for SavingsAccount return amount * 0.03; public void deposit (double amount) {Super.deposit (amount); Get code reuse//does something else} public void withdraw (double amount) {SUPER.W Ithdraw (amount); Get code reuse//Do something else} class Termdepositaccount extends AcCount {public double calculateinterest (double amount) {//Calculate interest for SavingsAccount
return amount * 0.05; public void deposit (double amount) {Super.deposit (amount); Get code reuse//does something else} public void withdraw (double amount) {Super.withdra W (amount); Get code reuse//Do something else}}
Interface Inheritance Case:
Package CH08_EXTENDS3;
The/** * interface inherits the sample code and uses a combination to reuse the code.
* <p> in the following example, the Deposite and withdraw methods share code snippets in Accounthelper. * <p> Calculateinterest Method has a unique implementation in its respective implementation * @author Zhengwei 2013-7-13/public interface account {public abstract
Double calculateinterest (double amount);
public abstract void deposit (double amount);
public abstract void withdraw (double amount);
} interface Accounthelper {public abstract void deposit (double amount);
public abstract void withdraw (double amount);
}/** * Class ACCOUNTHELPERIMPL has reusable code as methods deposit (double amount) * and withdraw (double amount). * <P>ACCOUNTHELPERIMPL contains reusable code: Deposit method and Withdraw method */class Accounthelperimpl implements Accounthelper {public V
OID deposit (double amount) {System.out.println ("depositing" + amount);
public void withdraw (double amount) {System.out.println ("withdrawing" + amount); } class Savingsaccountimpl implements account {//composed helper class (i.e. composition).
Accounthelper helper = new Accounthelperimpl ();
Public double calculateinterest (double amount) {//Calculate interest for savingsaccount return amount * 0.03; public void deposit (double amount) {Helper.deposit (amount);//code reuse via composition} public void Withdraw (double amount)
{Helper.withdraw (amount);//code reuse via composition}}
Class Termdepositaccountimpl implements account {//composed helper class (i.e. composition).
Accounthelper helper = new Accounthelperimpl ();
Public double calculateinterest (double amount) {//Calculate interest for savingsaccount return amount * 0.05; public void deposit (double amount) {Helper.deposit (amount);//code reuse via composition} public void Withdraw (double amount) {Helper.withdraw (amount);//code reuse via composition}}
You can use the following test code in two ways:
Package CH08_EXTENDS3;
/**
*
* @author zhengwei 2013-7-13
/public class Test {public
static void Main (string[] args) {
account acc1 = new Savingsaccountimpl ();
Acc1.deposit (50.0);
Account ACC2 = new Termdepositaccountimpl ();
Acc2.deposit (25.0);
Acc1.withdraw (a);
Acc2.withdraw (ten);
Double cal1 = acc1.calculateinterest (100.0);
Double cal2 = acc2.calculateinterest (100.0);
System.out.println ("Savings-->" + cal1);
System.out.println ("Termdeposit--> " + cal2);
}
Output results:
Depositing 50.0
Depositing 25.0
Withdrawing 25.0
Withdrawing 10.0
Savings--> 3.0
Termdeposit--> 5.0
Q: Why do I prefer to reuse code instead of inheritance by combining it?
A: You can see that there are two ways to take advantage of polymorphism and reuse the code, and the results are consistent, but the advantage of class inheritance is that its reuse is done statically at compile time and is easy to use. The disadvantage of class inheritance is that it is static, and implementations that inherit from the parent class cannot be changed during the runtime. In the object mix, the (combined) function is obtained dynamically at runtime and is achieved through the collection of references to other objects by objects. The advantage of this approach is that the combined "real object" can be replaced at run time. This is because we rely on the object's interface type, and the calling object is only through their interface, so one object can be replaced with the other as long as they have the same type (interface). For example: A combination of types Accounthelperimpl can be replaced with a more efficient implementation when needed:
public class Efficientaccounthelperimpl implements Accounthelper {public
void deposit (double Amount) {
System.out.println ("efficient depositing" + amount);
}
public void withdraw (double amount) {
System.out.println ("efficient withdrawing" + amount);
}
It doesn't feel right here. I say the question, "parents can't be replaced dynamically, but friends can be dynamic replacements." Once you inherit a class, you cannot replace the inheritance relationship, but in combination, we can temporarily change the type of the assembled object by means of a constructor pass or setter method, provided that the type of the object and the dependent interface type are not the same.
Further, reusing code is either Super.somemethod (), and this super points to the parent object, which you can't change. or reuse code through Brother.somemethod (), the brother is a domain member in combinatorial syntax that points to a collaborative, or dependent, object that can be replaced with just one set method.
Another problem is that in implementation inheritance, subclasses rely on the parent class implementation. This makes subclasses difficult to reuse, especially when the inherited implementation is no longer satisfactory and thus undermines encapsulation. In addition, modifications to the parent class not only affect subclasses along the inheritance hierarchy, but also other code that simply uses subclasses, which are very vulnerable to the design of the parent class. However, it is easy to change the interface/implementation of the composite object.
It's the same point I said above.
Because of the flexibility and strength of the object mix, most design patterns prioritize object combinations rather than inheritance whenever possible. Often, a design pattern using a combination shows a clever way to solve a common problem, rather than a standard, less flexible, inheritance based solution.
Encapsulation Encapsulation -refers to keeping all relevant members (variables and methods) together in one object. Specify that member variables are private to hide variables and methods. Objects should hide their internal workings from the outside world. Good encapsulation improves code modularity by preventing objects interacting in an unexpected way, making future development and refactoring work easier.
Sample code:
Class Mymarks {
private int vmarks = 0;
private String name;
public void Setmarks (int mark) throws Markexception {
if (Mark > 0)
this.vmarks = Mark;
else {
throw new markexception ("No negative Values");
}
public int Getmarks () {return
vmarks;
}
Getters and setters for attribute name goes.
}
Being able to encapsulate the members of a class is extremely important for security and integrity. We can protect the variable from receiving an illegal value. The example code above describes how to protect mymarks from negative values by encapsulation. Any modification of the member variable "Vmarks" must be done through the setter method Setmarks (int). This prevents the object "Mymarks" from having a negative value, and the caller passing in a negative value gets an exception.