简体   繁体   English

此Java代码是否有可能出现ClassCastException / IllegalStateException?

[英]Is there any chance of ClassCastException/IllegalStateException with this java code?

I was a bit confused with both classcastexception and illegalstateexception, as it seems similar in most of the cases. 我对classcastexception和llegalstateexception有点困惑,因为在大多数情况下,这似乎很相似。

Here i come across with an issue in this java code 在这里我遇到了这个Java代码中的问题

 class consumer
    {
         LOC----
    }

     public class provider extends consumer
       {
        public static void main(String args[])
        {
            consumer st=new provider();     
            provider est=(provider)st;
        }
     }

I was stuck with this part. 我被这部分困住了。 According to me, it should generate an exception (classcast or illegalstate). 据我说,它应该产生一个异常(类广播或非法状态)。 but there is no exception in execution, there might be a classcastexception or an illegalstateexception. 但是执行中没有异常,可能存在classcastexception或非法stateException。 But the code executes without any exception, Reason??? 但是代码执行没有任何异常,原因???

I was a bit week in exception handling, trying hard to master exception handling. 我花了一个星期的时间来处理异常,努力掌握异常处理。 can any one explain why it doesn't show error at the lines 谁能解释一下为什么没有显示错误

    consumer st=new provider();     
    provider est=(provider)st;

Also explain classcast and illegalstate exceptions... 还要解释类广播和非法状态异常...

Why do you expect a ClassCastException here? 您为什么在这里期望ClassCastException? st is a provider , you explicitely created one, so assigning a provider object to a reference of type provider is OK. stprovider ,您已明确创建了一个provider ,因此可以将provider对象分配给类型provider的引用。

The only thing is that the compiler does not 'know' that st will point to a provider object at runtime. 唯一的问题是编译器不“知道” st在运行时将指向provider对象。 Because the static type of st is consumer , the explicit cast to provider is required in the second line. 因为st的静态类型是consumer ,所以在第二行中需要显式强制转换为provider But that's nothing special... 但这没什么特别的...

consumer st=new provider(); 消费者st = new provider();

Here you are pointing to a provider object (RHS) and telling - "This is a consumer"(reference) , Which is true because provider extends consumer. 在这里,您指向提供者对象(RHS)并告诉-“这是一个使用者”(引用),这是正确的,因为提供者扩展了使用者。

  provider est=(provider)st;

Here, you are pointing to a provider object (RHS) and telling- "This is a provider"(reference). 在这里,您指向一个提供程序对象(RHS),并告诉-“这是一个提供程序”(参考)。 Which is also correct. 这也是正确的。 So, you should/will not get any error. 因此,您应该/不会得到任何错误。

The ClassCastException is thrown by the JVM when you try to cast an object to a type which is unreachable in this hierarchy. 当您尝试将对象强制转换为在此层次结构中无法访问的类型时,JVM抛出ClassCastException

As per your code, there is no reason for such exception and here there is why: 根据您的代码,没有理由会出现这种异常,这里是为什么:

1) You have two classes: consumer and provider , and the latter extends the former: 1)您有两类: consumerprovider ,后者扩展了前者:

public class provider extends consumer

2) Your code is instantiating a provider class and assigning it to a consumer variable: 2)您的代码实例化了provider类,并将其分配给consumer变量:

consumer st=new provider();

There is no reason here for any kind of exception, since provider extends consumer , all instances of a provider class are also a consumer , so you can use the consumer type to reference any kind of provider . 这里没有理由对任何类型的异常,因为provider扩展consumer ,一的所有实例provider类也是一个consumer ,这样你就可以用consumer型引用任何类型的provider

3) You are casting a provider instance into a ... (drum roll) provider instance!: 3)您正在将provider实例投射到...(鼓卷) provider实例中!:

provider est=(provider)st;

The variable st is of consumer type, true; 变量stconsumer类型,为true; but you initialised it as provider before (remember the new provider() statement). 但您之前将其初始化为provider (请记住new provider()语句)。 So, internally it's a provider not a consumer so when make that cast nothing wrong happens. 因此,在内部,它是provider而不是consumer因此在进行强制转换时不会发生任何错误。

IllegalStateExceptions work in a different way, some classes from the JVM can throw it due to a number of reasons. IllegalStateExceptions工作方式不同,由于多种原因,JVM中的某些类可以将其抛出。 Even your code can throw it attending to your specific needs. 甚至您的代码也可以使其满足您的特定需求。 The reason why is it thrown depends on each class implementation. 抛出它的原因取决于每个类的实现。

A ClassCastException is thrown when objects of incompatible types are casted. ClassCastException不兼容类型的对象时,抛出ClassCastException For instance 例如

consumer c = new consumer();
provider p = (provider) c;

the above code will throw a classCastException as an object of type consumer can never be anprovider object. 上面的代码将抛出classCastException,因为消费者类型的对象永远不能成为提供者对象。

In your code you are creating an object of type provider and assigning that to a reference of type consumer . 在您的代码中,您将创建类型provider的对象,并将其分配给类型consumer的引用。 This is perfectly legal because all methods that would be in a consumer object will be in provider object. 这是完全合法的,因为所有将在consumer对象中使用的方法都将在provider对象中。 so there won't be any exception thrown. 这样就不会抛出任何异常。 It is called an Upcast . 这称为Upcast

When you are downcasting that is casting a an object from parent class to child class there may be a ClassCastException thrown if the object being cast is of the parent class type and the reference is of the child class type. 当向下转换将对象从父类转换为子类时,如果要转换的对象是父类类型,而引用是子类类型,则可能会引发ClassCastException。

provider p = (provider) c; // will give you a ClassCastException

as the methods in the class Child will not be present in the parent class which will cause a meltdown at runtime if a child specific method is called on a Parent type Object. 因为Child类中的方法不会出现在父类中,如果在父类型对象上调用子类专用方法,则会在运行时导致崩溃。

nothing wrong with program ..so it will run without any exception... But if you will try without excception then it will give error at compile time... try this program for class cast exeption 程序没有什么问题,所以它会毫无例外地运行...但是,如果您不加尝试就尝试运行,那么它将在编译时给出错误...请尝试将该程序用于类强制转换

class consumer
{
int a=0;
void method(Object ob)
{
    consumer st=(consumer)ob;
}

}
public class provider
{
public static void main(String args[])
{
    consumer st=new consumer();     
    provider est=new provider();
    st.method(est);
}
}

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

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