Reputation: 3820
I have read a lot of explanations about the java sub-typing and the true sub-typing and the subclass but every time I get more confused, please I need a perfect explanation to all the mentioned above, I am right at following statements?
thanks in advance
Upvotes: 0
Views: 450
Reputation: 4314
every class the inherits from another class is a subclass
I will correct this to
"every class that extends another class is a subclass"
and FYI every class in java extends java.lang.Object
class by default except Object
class itself.
some class is a java sub-class to another class if it has the same methods
This is not true. consider following example
class A {
public void someMethod(){
// method code
}
}
class B {
public void someMethod(){
// method code
}
}
Both are independent class, B
is not subclass of A
or A
is not subclass of B
.
true sub-typing is when we can replace a reference between two classes
EDIT :
class A {
public void someMethod(){
// method code
}
}
class B extends A{
public void someMethod(){
// method code
}
}
You can create object of class B
which is subclass of A
as
A objB = new B();
This concept is Runtime Polymorphism. and you can check an article Inheritance in Java on that.
Upvotes: 1
Reputation: 41417
Only the first of these statements is true.
#2: If a class is the sub-class of another class, it will have the same methods (The reverse of this statement is not necessarily true). Consider this example:
public class Animal
{
public void sayHello ()
{
System.out.println ("Hello!");
};
}
public class Dog extends Animal
{
public void sayHello ()
{
System.out.println ("Woof! I'm a dog.");
};
}
public class WebApplication
{
public void sayHello ()
{
System.out.println ("Welcome!");
};
}
Both WebApplication
and Dog
have a similar sayHello
method, but only Dog
is a sub-class of Animal
.
#3: I don't know what you mean by "replace a reference". If Dog
is a sub-class of Animal
, you can assign a Dog
object to an Animal
reference, but not vice versa.
Upvotes: 0