Ihsan Ramli Ihsan Ramli - 1 year ago 77
Java Question

Java object class creation

I'm just learning Java. I know the concept for creating an object from class like this one below:

ClassName ObjName = new ClassName();

I don't understand the instance below:

public void methodName(Object other){
ClassName ObjName = (ClassName)other;

Why the object reference other need (ClassName) in front it?

Reference, 1.4 A Special-Purpose Class: A Bank Account:

Answer Source

That is called casting. It's when you change the reference type from a parent type to a child type.

In java, all classes are a child class to Object so Object can be casted into anything (as long as the object really is what you're trying to cast)

For example, say I have a method:

public void someMethod(Objet o){
    //does something

Then I can call that method like this:

someMethod(new String("some String"));

and that would work, but the type of o in the method would be string, even if the reference is of type object.

Casting one of the core ideas of oop (Object Oriented Programming).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download