Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Analysis of inheritance examples in Java

2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)05/31 Report--

This article focuses on "inheritance case Analysis in Java". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn the inheritance case Analysis in Java.

Interface (Interface) and class (Class)?

Once, I attended a meeting of the Java user group. In the meeting, Jams Gosling (the father of Java) spoke as the sponsor. In the unforgettable Java section, he was asked, "what do you want to change if you restructure Qrooma?" "I want to abandon classes," he replied. After the laughter died down, it explained that the real problem was not the class itself, but the implementation of inheritance (extends) relationships. Interface inheritance (implements relationships) is better. You should avoid implementing inheritance as much as possible.

Lost flexibility.

Why should you avoid implementing inheritance? The first problem is to explicitly use a specific class name to fix you to a specific implementation, adding unnecessary difficulties to the underlying changes.

In the current agile programming methods, the core is the concept of parallel design and development. Before you design the program in detail, you start programming. This technique is different from the traditional method-the traditional way is that the design should be completed before the coding starts-but many successful projects have proved that you can develop high-quality code more quickly, compared to the traditional step-by-step approach. But at the core of parallel development is to advocate flexibility. You have to write your code in some way so that newly discovered requirements can be incorporated into existing code as painlessly as possible.

Rather than achieving the characteristics you may need, you only need to achieve the characteristics you clearly need and be moderately tolerant of change. If you don't have this kind of flexible, parallel development, it's impossible.

Programming for Inteface is at the core of flexible structures. To explain why, let's take a look at what happens when they are used. Consider the following code:

F ()

{

LinkedList list = new LinkedList ()

/ /...

G (list)

}

G (LinkedList list)

{

List.add (...)

G2 (list)

}

Suppose a requirement for a quick query is raised so that the LinkedList cannot be solved. You need to replace it with HashSet. In existing code, changes cannot be localized because you need to modify not only f () but also g () (which takes the LinkedList parameter), but also any code to which g () passes the list. Rewrite the code as follows:

F ()

{

Collection list = new LinkedList ()

/ /...

G (list)

}

G (Collection list)

{

List.add (...)

G2 (list)

}

By changing Linked list to hash, you may simply use new HashSet () instead of new LinkedList (). That's all. There is nothing else that needs to be changed.

As another example, compare the following two pieces of code:

F ()

{

Collection c = new HashSet ()

/ /...

G (c)

}

G (Collection c)

{

For (Iterator I = c.iterator (); i.hasNext ())

Do_something_with (i.next ())

}

And

F2 ()

{

Collection c = new HashSet ()

/ /...

G2 (c.iterator ())

}

G2 (Iterator I)

{

While (i.hasNext ())

Do_something_with (i.next ())

}

The G2 () method can now traverse the derivation of Collection, just like the key-value pairs you can get from Map. In fact, you can write iterator, which produces data instead of traversing a Collection. You can write iterator, which gets information from the framework or file of the test. This will have great flexibility.

Coupling

A more critical issue for implementing inheritance is coupling-the irritating dependency of one part of that program on another. Global variables provide classic examples of why strong coupling can cause trouble. For example, if you change the type of a global variable, all functions that use that variable may be affected, so all of this code will be checked, changed, and retested. Moreover, all functions that use this variable are coupled to each other through this variable. That is, if the value of a variable is changed when it is difficult to use, one function may incorrectly affect the behavior of another function. This problem is significantly hidden in multithreaded programs.

As a designer, you should try to minimize the coupling relationship. You cannot decouple at the same time, because the method call from the object of one class to the object of another class is a loosely coupled form. You can't have a program that doesn't have any coupling. However, you can minimize a certain amount of coupling by following OO rules (most importantly, the implementation of an object should be completely hidden from the object that uses it). For example, an instance variable of an object (not a member domain of a constant) should always be private. I mean for a certain period of time, without exception, constantly. (you can occasionally effectively use protected methods, but protected instance variables are an abomination.) for the same reason, you should not use get/set functions-they just feel too complicated about being common to a domain (although in some cases the access function that returns decorated objects rather than primitive type values is for reasons, in which case, the returned object class is a key abstraction at design time).

Here, I'm not bookish. In my own work, I found a direct correlation between the rigour of my OO approach, rapid code development and easy code implementation. Whenever I violate the central OO principle, such as implementing hiding, I end up rewriting that code (usually because the code is undebuggable). I didn't have time to rewrite the code, so I followed those rules. What I care about is completely practical? I'm not interested in the reason for cleanliness.

Fragile base class problem

Now, let's apply the concept of coupling to inheritance. In an inheritance implementation system using extends, the derived class is very closely coupled to the base class, if and such a tight connection is not expected. Designers have used the nickname "fragile base class problem" to describe this behavior. The base class is considered fragile because you modify the base class when it seems safe, but when inheriting from a derived class, the new behavior may cause the derived class to become dysfunctional. You can't tell that changes to the base class are safe by simply checking the base class under isolation; you must also look at (and test) all derived classes. Also, you have to check all the code, which is also used in base and derived class objects, because this code may be broken by the new behavior. A simple change to the underlying class may make the entire program inoperable.

Let's examine the problem of fragile base class and base class coupling. The following class extends Java's ArrayList class to make it function like a stack:

Class Stack extends ArrayList

{

Private int stack_pointer = 0

Public void push (Object article)

{

Add (stack_pointer++, article)

}

Public Object pop ()

{

Return remove (--stack_pointer)

}

Public void push_many (Object [] articles)

{

For (int I = 0; I

< articles.length; ++i )    push( articles[i] );   }   }   甚至一个象这样简单的类也有问题。思考当一个用户平衡继承和用ArrayList的clear()方法去弹出堆栈时:   Stack a_stack = new Stack();   a_stack.push("1");   a_stack.push("2");   a_stack.clear();   这个代码成功编译,但是因为基类不知道关于stack指针堆栈的情况,这个stack对象当前在一个未定义的状态。下一个对于push()调用把新的项放入索引2的位置。(stack_pointer的当前值),所以stack有效地有三个元素-下边两个是垃圾。(Java的stack类正是有这个问题,不要用它).   对这个令人讨厌的继承的方法问题的解决办法是为Stack覆盖所有的ArrayList方法,那能够修改数组的状态,所以覆盖正确的操作Stack指针或者抛出一个例外。(removeRange()方法对于抛出一个例外一个好的候选方法)。   这个方法有两个缺点。第一,如果你覆盖了所有的东西,这个基类应该真正的是一个interface,而不是一个class。如果你不用任何继承方法,在实现继承中就没有这一点。第二,更重要的是,你不能够让一个stack支持所有的ArrayList方法。例如,令人烦恼的removeRange()没有什么作用。唯一实现无用方法的合理的途径是使它抛出一个例外,因为它应该永远不被调用。这个方法有效的把编译错误成为运行错误。不好的方法是,如果方法只是不被定义,编译器会输出一个方法未找到的错误。如果方法存在,但是抛出一个例外,你只有在程序真正的运行时,你才能够发现调用错误。   对于这个基类问题的一个更好的解决办法是封装数据结构代替用继承。这是新的和改进的Stack的版本:   class Stack   {   private int stack_pointer = 0;   private ArrayList the_data = new ArrayList();   public void push( Object article )   {   the_data.add( stack_poniter++, article );   }   public Object pop()   {   return the_data.remove( --stack_pointer );   }   public void push_many( Object[] articles )   {   for( int i = 0; i < o.length; ++i )    push( articles[i] );   }   }   到现在为止,一直都不错,但是考虑脆弱的基类问题,我们说你想要在stack创建一个变量, 用它在一段周期内跟踪最大的堆栈尺寸。一个可能的实现也许象下面这样:   class Monitorable_stack extends Stack   {   private int high_water_mark = 0;   private int current_size;   public void push( Object article )   {   if( ++current_size >

High_water_mark)

High_water_mark = current_size

Super.push (article)

}

Publish Object pop ()

{

-- current_size

Return super.pop ()

}

Public int maximum_size_so_far ()

{

Return high_water_mark

}

}

This new class works well, at least for a while. Unfortunately, this code discovers the fact that push_many () runs by calling push (). First of all, this detail doesn't seem like a bad choice. It simplifies the code, and you can get a derived version of push (), even when Monitorable_stack is accessed through Stack's reference, so that high_water_mark can be updated correctly.

At this point, I believe you have a deeper understanding of "inheritance instance Analysis in Java". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report