简体   繁体   English

实例化内部类

[英]Instantiating inner class

I working on a sample problem of over-ridding hashCode and equals method but getting an error: " No enclosing instance of type CustomHashCodeExample is accessible. Must qualify the allocation with an enclosing instance of type CustomHashCodeExample (egxnew A() where x is an instance of CustomHashCodeExample). " I wrote an inner class HashPerson and I am getting this error when I am trying to instantiate this inner class in another method called testHashCodeOverride().我正在处理一个覆盖 hashCode 和 equals 方法的示例问题,但收到错误:“没有类型 CustomHashCodeExample 的封闭实例是可访问的。必须使用 CustomHashCodeExample 类型的封闭实例限定分配(egxnew A(),其中 x 是一个实例的 CustomHashCodeExample。 ”我写了一个内部类 HashPerson,当我尝试在另一个名为 testHashCodeOverride() 的方法中实例化这个内部类时,我收到了这个错误。

public static void testHashCodeOverride(){   
    System.out.println("\nTest HashCode Override Method");
    System.out.println("==================================\n");

    HashPerson william = new HashPerson("willy");
    HashPerson bill = new HashPerson("willy");          
}

This code works fine, even though I dont see static inner class or instantiation of outer class, confused :(这段代码工作正常,即使我没有看到静态内部类或外部类的实例化,也很困惑:(

public class HashCodeExample {

    public static void testHashCodeOverride() {

        HashPerson william = new HashPerson("Willy");
        HashPerson bill = new HashPerson("Willy");
        System.out.println("Hash code for william  = " + william.hashCode());
        System.out.println("Hash code for bill     = " + bill.hashCode());

        HashMap table = new HashMap();
        table.put(william, "Silly");

        if (table.containsKey(william)) {
            System.out.println(table.get(william));
        } else {
            System.out.println("Key " + william + " not found");
        }

        if (table.containsKey(bill)) {
            System.out.println(table.get(bill));
        } else {
            System.out.println("Key " + bill + " not found");
        }


    }

    class HashPerson {
        private static final int HASH_PRIME = 1000003;

        public HashPerson(String name) {
            this.name = name;
        }

        public String toString() {
            return name;
        }

        public boolean equals(Object rhs) {
            if (this == rhs)
                return true;

            // make sure they are the same class
            if (rhs == null || rhs.getClass() != getClass())
                return false;

            // ok, they are the same class. Cast rhs to HashPerson
            HashPerson other = (HashPerson) rhs;

            // our test for equality simply checks the name field
            if (!name.equals(other.name)) {
                return false;
            }

            // if we get this far, they are equal
            return true;
        }
        public int hashCode() {
            int result = 0;
            result = HASH_PRIME * result + name.hashCode();
            return result;
        }
        private String name;

    }
}

I think you want to declare the HashPerson class as static .我认为您想将HashPerson类声明为static Otherwise it can only be instantiated in the context of the containing class, either in a method of the containing class or using code like this:否则,它只能在包含类的上下文中实例化,在包含类的方法中或使用如下代码:

ContainingClass container = new ContainingClass();
HashPerson william = container.new HashPerson("willy");

Actually, my rule-of-thumb is to make any nested class static, unless I have a special reason not to.实际上,我的经验法则是将任何嵌套类设为静态,除非我有特殊原因不这样做。 This is also more efficient, because non-static nested classes (called inner classes ) always contain an implicit reference to the containing object.这也更有效,因为非静态嵌套类(称为内部类)始终包含对包含对象的隐式引用。

You need to either make your inner class static, or refer to it through an instance of the outer class.您需要将内部类设为静态,或者通过外部类的实例引用它。 Most likely you just want to make your inner class static.很可能你只是想让你的内部类是静态的。

Non-static members of a class (variables, methods, inner classes) are per instance of the class.类的非静态成员(变量、方法、内部类)是每个类的实例 Therefore, when accessing non-static members from a static context (such as a static method like testHashCodeOverride ), you need to specify an instance of the enclosing class.因此,当从静态上下文(例如像testHashCodeOverride这样的静态方法)访问非静态成员时,您需要指定封闭类的实例。

As i can see there could be different possible ways to instantiate the Inner Classes正如我所看到的,可能有不同的方法来实例化内部类

  1. Static Inner Class : When Inner class is static, let say code looks like as describe.静态内部类:当内部类是静态时,假设代码看起来像描述一样。

     class OuterClass { static int outer_x = 10; int outer_y = 20; // static nested class static class StaticNestedClass { void display() { } } } OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();

or Just this could be sufficient for static classes或者这对于静态类就足够了

 new StaticNestedClass();
  1. Local inner Classes (Non Static) : Inner Classes which are not static, one good thing with local inner classes that they can access all private data members of enclosed class.本地内部类(非静态):非静态的内部类,本地内部类可以访问封闭类的所有私有数据成员是一件好事。

     OuterClass outerObject = new OuterClass(); OuterClass.InnerClass innerObject = outerObject.new InnerClass();
  2. Anonymous Inner Class (implementing Interface) : This type of classes generally hidden, One can't directly see the Class{...} block in code , That is why known as Anonymous Inner Class.匿名内部类(实现接口) :这类类一般是隐藏的,不能直接看到代码中的 Class{...} 块,所以称为匿名内部类。 Here describes how to instantiate it in case inner class implementing an interface Runnable Interface.这里描述了如何在内部类实现接口 Runnable 接口的情况下实例化它。

     Runnable r = new Runnable() { //This is Anonymous Class public void run() { System.out.println("Child Thread"); } };
  3. Anonymous Inner Class (Extending One Class) :We can have an anonymous inner class that extends a class, Here i am taking example of Thread Class,匿名内部类(扩展一个类) :我们可以有一个匿名内部类来扩展一个类,这里​​我以线程类为例,

     Thread t = new Thread(new Runnable() { //Anonymous Inner class public void run() { System.out.println("Child Thread"); } });
  4. Anonymous Inner class that defines inside method/constructor argument : Inner Classes could be define within methods as well, here giving example how can we define and instantiate it within argument定义内部方法/构造函数参数的匿名内部类:内部类也可以在方法中定义,这里举例说明如何在参数中定义和实例化它

    public static void main(String[] args) { //Here we are using Anonymous Inner class //that define inside argument, here constructor argument Thread t = new Thread(new Runnable() { public void run() { System.out.println("Child Thread"); } }); t.start();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM