What is a Subclass [closed]
A subclass is a class that extends another class.
public class BaseClass{
public String getFoo(){
return "foo";
}
}
public class SubClass extends BaseClass{
}
Then...
System.out.println(new SubClass().getFoo());
Will print:
foo
This works because a subclass inherits the functionality of the class it extends.
A subclass is something that extends the functionality of your existing class. I.e.
Superclass - describes the catagory of objects:
public abstract class Fruit {
public abstract Color color;
}
Subclass1 - describes attributes of the individual Fruit objects:
public class Apple extends Fruit {
Color color = red;
}
Subclass2 - describes attributes of the individual Fruit objects:
public class Banana extends Fruit {
Color color = yellow;
}
The 'abstract' keyword in the superclass means that the class will only define the mandatory information that each subclass must have i.e. A piece of fruit must have a color so it is defines in the super class and all subclasses must 'inherit' that attribute and define the value that describes the specific object.
Does that make sense?
Subclass is to Class as Java is to Programming Language.
It is a class that extends another class.
example taken from https://www.java-tips.org/java-se-tips-100019/24-java-lang/784-what-is-a-java-subclass.html, Cat is a sub class of Animal :-)
public class Animal {
public static void hide() {
System.out.println("The hide method in Animal.");
}
public void override() {
System.out.println("The override method in Animal.");
}
}
public class Cat extends Animal {
public static void hide() {
System.out.println("The hide method in Cat.");
}
public void override() {
System.out.println("The override method in Cat.");
}
public static void main(String[] args) {
Cat myCat = new Cat();
Animal myAnimal = (Animal)myCat;
myAnimal.hide();
myAnimal.override();
}
}