Defining Superclasses and Subclasses

J.E.D.I

11.2.1 Defining Superclasses and Subclasses

To derive a class, we use the extends keyword. In order to illustrate this, lets create a sample parent class. Suppose we have a parent class called Person. public class Person { protected String name; protected String address; Default constructor public Person{ System.out.println“Inside Person:Constructor”; name = ; address = ; } Constructor with 2 parameters public Person String name, String address { this.name = name; this.address = address; } Accessor methods public String getName{ return name; } public String getAddress{ return address; } public void setName String name { this.name = name; } public void setAddress String add { this.address = add; } } Notice that, the attributes name and address are declared as protected. The reason we did this is that, we want these attributes to be accessible by the subclasses of the superclass. If we declare this as private, the subclasses wont be able to use them. Take note that all the properties of a superclass that are declared as public, protected and default can be accessed by its subclasses. Introduction to Programming I 171 J.E.D.I Now, we want to create another class named Student. Since a student is also a person, we decide to just extend the class Person, so that we can inherit all the properties and methods of the existing class Person. To do this, we write, public class Student extends Person { public Student{ System.out.println“Inside Student:Constructor”; some code here } some code here } When a Student object is instantiated, the default constructor of its superclass is invoked implicitly to do the necessary initializations. After that, the statements inside the subclass are executed. To illustrate this, consider the following code, public static void main String[] args { Student anna = new Student; } In the code, we create an object of class Student. The output of the program is, Inside Person:Constructor Inside Student:Constructor The program flow is shown below. Introduction to Programming I 172 Figure 11.2: Program Flow J.E.D.I

11.2.2 The super keyword