85.8k views
1 vote
Choose a superclass and a subclass.

Create the code for your chosen superclass and subclass.
Use a simple constructor and toString() method should to see the relationships formed by extending a class.
Add additional instance variables and methods
JAVA
SAMPLE:
{

private String name;




public Person(String n)

{ name = n; }



public String toString()

{return name;}

}

public class Student extends Person

{

private int id;

public Student(String n,int i)

{
super(n);
id = i;

}


public String toString()

{ return super.toString() + " ID: " + id; }


public static void main(String[] args)

{

Student s = new Student("Nancy", 55);

System.out.println(s instanceof Student);

System.out.println(s instanceof Person);

System.out.println(s);

}

}

1 Answer

5 votes

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.

User Maslow
by
7.7k points