Casting objects in Java

2019-01-01 11:07发布

I'm confused about what it means to cast objects in Java.

Say you have...

Superclass variable = new Subclass object();
(Superclass variable).method();

What is happening here? Does the variable type change, or is it the object within the variable that changes? Very confused.

10条回答
呛了眼睛熬了心
2楼-- · 2019-01-01 11:19

The example you are referring to is called Upcasting in java.

It creates a subclass object with a super class variable pointing to it.

The variable does not change, it is still the variable of the super class but it is pointing to the object of subclass.

For example lets say you have two classes Machine and Camera ; Camera is a subclass of Machine

class Machine{

    public void start(){

        System.out.println("Machine Started");
    }
}

class Camera extends Machine{
     public void start(){

            System.out.println("Camera Started");
        }
     public void snap(){
         System.out.println("Photo taken");
     }
 }
Machine machine1 = new Camera();
machine1.start();

If you execute the above statements it will create an instance of Camera class with a reference of Machine class pointing to it.So, now the output will be "Camera Started" The variable is still a reference of Machine class. If you attempt machine1.snap(); the code will not compile

The takeaway here is all Cameras are Machines since Camera is a subclass of Machine but all Machines are not Cameras. So you can create an object of subclass and point it to a super class refrence but you cannot ask the super class reference to do all the functions of a subclass object( In our example machine1.snap() wont compile). The superclass reference has access to only the functions known to the superclass (In our example machine1.start()). You can not ask a machine reference to take a snap. :)

查看更多
春风洒进眼中
3楼-- · 2019-01-01 11:24

Superclass variable = new subclass object();
This just creates an object of type subclass, but assigns it to the type superclass. All the subclasses' data is created etc, but the variable cannot access the subclasses data/functions. In other words, you cannot call any methods or access data specific to the subclass, you can only access the superclasses stuff.

However, you can cast Superclassvariable to the Subclass and use its methods/data.

查看更多
旧人旧事旧时光
4楼-- · 2019-01-01 11:26

Have a look at this sample:

public class A {
  //statements
}

public class B extends A {
  public void foo() { }
}

A a=new B();

//To execute **foo()** method.

((B)a).foo();
查看更多
爱死公子算了
5楼-- · 2019-01-01 11:26

in some cases we can’t provide guarantee for the type of elements or objects present inside our collection or wise, at the time of retrieval compulsory we should perform type casting otherwise we will get compile time error.

Arrays are always type safe that is we can provide the guarantee for the type of elements present inside array. to achieve type safety we have to use typecasting.

查看更多
不再属于我。
6楼-- · 2019-01-01 11:29

Lets say you have Class A as superclass and Class B subclass of A.

public class A {

    public void printFromA(){
        System.out.println("Inside A");
    }
}
public class B extends A {

    public void printFromB(){
        System.out.println("Inside B");
    }

}

public class MainClass {

    public static void main(String []args){

        A a = new B();
        a.printFromA(); //this can be called without typecasting

        ((B)a).printFromB(); //the method printFromB needs to be typecast 
    }
}
查看更多
只若初见
7楼-- · 2019-01-01 11:29

Casting is necessary to tell that you are calling a child and not a parent method. So it's ever downward. However if the method is already defined in the parent class and overriden in the child class, you don't any cast. Here an example:

class Parent{
   void method(){ System.out.print("this is the parent"); }
}

class Child extends Parent{
   @override
   void method(){ System.out.print("this is the child"); }
}
...
Parent o = new Child();
o.method();
((Child)o).method();  

The two method call will both print : "this is the child".

查看更多
登录 后发表回答