您可以从java中的不同类静态方法访问派生类中的非静态方法吗?

时间:2015-02-17 04:23:45

标签: java linked-list

我无法从其他类访问派生类中的非静态方法。

public class Test
{
   public static void main(String args)
   {
      LinkedList myList = new LinkedListExtension();

      TestMethods.methodOne(myList);// passed the method myList
   }
}

public class TestMethods
{
   public static void methodOne(final LinkedList myList)
   {
      myList.clear(); // this is the part I am having trouble with
   }
}

public class LinkedList
{
   protected static class Node
   {
      public Comparable data;
      public Node next;
      public Node(final Comparable data)
      {
         this.data = data;
         this.next = null;
      }
         public Node()
      {
         this.data = null;
         this.next = null;
      }
         public Node(final Comparable data, final Node next)
      {
         this.next = next;
         this.data = data;
      }
   }

   protected Node head;
    protected int size;

   public LinkedList()
   {
      this.head = new Node();
      this.size = 0;
   }
}

public class LinkedListExtension extends LinkedList
{
   public void clear()
   {
      this.head = new Node(); 
      this.size = 0;
   }
}

我知道如果我在LinkedList类中有clear()方法,代码将编译并正常运行。因此,如果不更改LinkedList类和Test类中的任何内容,如何调用LinkedList扩展中的clear()方法?它可能吗?如果这个问题不清楚,我很抱歉,当涉及到编程时我仍然是一个菜鸟,我仍然很难理解继承。

1 个答案:

答案 0 :(得分:1)

您的LinkedList版本没有clear()方法。您可以将其从LinkedListExtension移至LinkedList,也可以编入LinkedListExtension

public static void methodOne(final LinkedListExtension myList) {
    myList.clear();
}