Here is an example superclass and subclass in Java:
public class Animal {
private String species;
private int age;
public Animal(String species, int age) {
this.species = species;
this.age = age;
}
public String getSpecies() {
return species;
}
public void setSpecies(String species) {
this.species = species;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String toString() {
return "Species: " + species + ", Age: " + age;
}
}
public class Cat extends Animal {
private String name;
public Cat(String species, int age, String name) {
super(species, age);
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String toString() {
return super.toString() + ", Name: " + name;
}
public void meow() {
System.out.println(name + " says meow!");
}
}
In this example, Animal is the superclass and Cat is the subclass. Animal has instance variables for species and age, and Cat adds an instance variable for name. Animal has a constructor that takes in species and age, while Cat adds an additional parameter for name. Both classes have a toString() method that returns a formatted string containing the object's attributes.
In addition, Cat has a meow() method that prints a message to the console.
To create an instance of Cat, we could use the following code:
Cat cat = new Cat("Cat", 2, "Fluffy");
System.out.println(cat);
cat.meow();
This would create a new Cat object with the species "Cat", age 2, and name "Fluffy". Calling cat.toString() would return "Species: Cat, Age: 2, Name: Fluffy". Finally, calling cat.meow() would print "Fluffy says meow!" to the console.