Reputation: 3
Just had this in a unit test. So:
abstract class A {...}
class B extends A {...}
A a = new B();
Pretty much doubt it's viable, but I'm totally confused at the moment. The content of the classes is irrelevant.
Upvotes: 0
Views: 113
Reputation: 1
Interface - every method is always public and abstract whether you are declaring it or not. You can’t declare an interface method with the following modifiers. Every variable present inside interface is always public static and final whether we are declaring or not. You can’t declare an interface variable with the following modifiers, private, protected, transient and volatile. The variables present within abstract class don’t have to be public, static and final. There are no restrictions on abstract class variable modifiers. For abstract class variable are not required to perform initialization at the time of declaration. An abstract class can declare instance and static blocks. Inside interface we can’t declare instance and static blocks otherwise we will get compile time error. Interface can’t declare constructors. Just keep these fun facts in mind.
Upvotes: 0
Reputation: 1853
yes this concept is known as polymorphism
in java . a parent can contains reference of child class. and parent can be either interface
or abstruct class
. even you need not to cast
. for example .
a animal can be horse or cat , here animal is an interface or abstract class.
i recommend (SCJP Sun Certified Programmer -kathy sierra)book has lot of concepts related to java language.
Upvotes: 1
Reputation: 91
Its valid in java. this is called implicit up casting (JVM casts sub type to super type object) where reference of super type can refer to sub type but with super type reference you can only get access to only those variables and methods which are declared/defined in super type.
Upvotes: 0
Reputation: 1620
It's valid. As per Java's fundamental rule "Super class reference (A a) can refer sub class object (b= new B())".
Upvotes: 0
Reputation: 113
Yes this is a valid java assignment statement.
A a = (A) new B();
In java a child object can be referenced from the parent class.
Upvotes: 0
Reputation: 13854
Yes this is valid in java
abstract class A {...}
class B extends A {...}
A a = new B();
Upvotes: 0