Object Type Declaration

Good. So, when you have a hierarchy of classes like

public class A {...}

and

public class B extends A {...}

... When you create objects, what is the difference between them:

A object = new A();
A object = new B();
B object = new B();

Thank you for your time.

+4
source share
6 answers
public class A
{
    public void methodA(){}
}
public class B extends A
{
    public void methodB(){}
}

Hope this can demonstrate the difference.

A obj = new A();

a.methodA(); //works

A obj = new B();

obj.methodA(); //works
obj.methodB(); //doesn't work
((B)obj).methodB(); //works

B obj = new B();

obj.methodA(); //works
obj.methodB(); //works
+2
source
A object = new A();

You create A instancea type A link. You can only access methods / properties and properties-methods and properties.

A object = new B();

B instance A. , object , , object.method() method B, . , . / /. , .

B object = new B();

B instance B. / B / .

+2
A object = new B();

, object A ( null). A, , A ( ). , A :

A object1 = new B();
B object2 = new B();

// reassign later
object1 = new A();  // legal
object2 = new A();  // ILLEGAL

class C extends A { ... }
object1 = new C();  // legal
object2 = new C();  // ILLEGAL

, object A. B, , B A.

. - , ( ) A, B.

+1
A object = new A();

object A ( A)

A object = new B();

object A ( B, A)

B object = new B();

object B ( A B)

+1
A object1 = new A();
A object2 = new B();
B object3 = new B();

object1 A. B A, (new A(), new B() ).

object2 A, B. , B eatFood(). object2.eatFood(), , eatFood B. , B, , A - . eatFood, : ((B)object2).eatFood().

object3 B B. A, B.

+1

,

A var = new B();

.

A var;         // (1) Make a variable of TYPE A.
var = new B(); // (2) Make an object of CLASS B, that from now on may be 
               // referred to by the variable var.

, , . . , . , .

. B A, , B A. Object. , , B, , . , - , , - , - .

, A B, A - , B . A, B. , , A display(), B , explain(). display() A, explain(). , , explain() , B, .

, , B, B. , , A. , B A, B , A - .

, : -

A var = new B();

B , var ?

, , . : ", , B, , A. , .

, , . , C, , , :

public class C {
    public void process(A arg){
        // Do some stuff
    }

    public void process(B arg){
        // Do some other stuff
    }
}

process , . ,

C processor = new C();
A var = new B();
processor.process(var);

process - , A . - .

C processor = new C();
B var = new B();
processor.process(var);

process - , B .

+1

All Articles