1

This question is just for me to understand this concept. How can null be casted to (Throwable)? null is not a class right? This question is propably stupid.

I know that:

public class SuperClass{
    int id = 0;
    public SuperClass(int id){
        this.id = id;
    }
}

public class SubClass extends SuperClass{
    public SubClass(int id) {
        super(id);
    }       
}

public class Tester{
    SubClass sub = new SubClass(1);
    SuperClass s = new SuperClass(2);
    SuperClass s1 = new SubClass(3);

    public Tester(){
        if(s1 instanceof SubClass){
            //true
            SubClass subClass = (SubClass) s1;
        }
    }       
}`
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
theo231022
  • 329
  • 2
  • 12

4 Answers4

1

The key point to note is you can cast null to any reference type, after all the result is null again.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
1

null is not a type. it may conceptually be comparable to an instance of any class

String s = (String)null;
Integer i = (Integer)null;
Sharon Ben Asher
  • 13,849
  • 5
  • 33
  • 47
  • ok now makes sense to me, I have seen this somewhere in the classes from the system after an exception occured. – theo231022 Apr 13 '16 at 08:26
1

How can null be casted to (Throwable)? null is not a class right?

null doesn't have a type. null can be cast to any class or interface type. It can't be cast to a primtive.

Throwable is a class in the package of java.lang.

You can't cast classes, only references.

String s = "Hello";

Here the variable s is a reference not a class or an object, nor even a String.

Throwable t = new Throwable();

Here the variable t is a reference to a Throwable but it can be set to null;

Throwable t = null; // the reference doesn't point to any object.
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

As others have written, you can cast null to everything.

Normally, you wouldn't need that, you can write:

String nullString = null;

without putting the cast there.

The only place where such casts make sense are:

a) if you want to make sure that a specific method is called, like:

void foo(String bar) {  ... }
void foo(Object bar) {  ... }

then it would make a difference if you type

foo((String) null) vs. foo(null)

b) if you intend to use your IDE to generate code; for example I am typically writing unit tests like:

@Test(expected=NullPointerException.class)
public testCtorWithNullWhatever() {
    new MyClassUnderTest((Whatever) null);
}

I am doing TDD; this means that the class "MyClassUnderTest" probably doesn't exist yet. By writing down that code, I can then use my IDE to first generate the new class; and to then generate a constructor accepting a "Whatever" argument.

GhostCat
  • 137,827
  • 25
  • 176
  • 248