Learning Objectives By the end of today's class, you should know...
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
public class Person {
|
Example Subclass
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
public class Student extends Person {
|
Example Test Application
1 2 3 4 5 6 7 8 9 10 11 |
public class StudentApp {
|
Adding Methods to Subclasses
- We added a member variable to the
Student
subclasspublic class Student extends Person { private int studentNumber;
- A
Student
has this attribute in addition to aname
name
is inherited fromPerson
- Also, we added a new instance method to the subclass:
public int getStudentNumber() { return studentNumber; }
- A
Student
has this method in addition to all the methods of the superclass
Overriding Methods
- In addition to adding new members, we can change the way a method works for objects of a subclass
- Changing the way a method works in a subclass is known as overriding a method
- We overrode this method in our
Student
subclass
@Override public void printAttributes() {
super.printAttributes();System.out.println("Student Number : "
+ studentNumber);
super.special();
}
- Both superclass and subclass has a
printAttributes
method - Both methods have the same parameters (i.e. none)
- Thus, they have the same signature
- The method from the subclass overrides the superclass method
- Note that a subclass method will NOT override a superclass method if the parameters are different
- Would have different signatures
- Note
that calling this method has a different effect whether it is called
for an object of type Person or an object of type Student:
System.out.println("Printing " + al.getName() + "'s information:");
al.printAttributes();
System.out.println("\nPrinting " + xing.getName() + "'s information:");
xing.printAttributes();
al.printAttributes();
System.out.println("\nPrinting " + xing.getName() + "'s information:");
xing.printAttributes();
- Sometimes people confuse overriding with overloading
- See the table below for the similarities and differences
Overriding Verses Overloading
Overriding Overloading
- Same method name
- Same method name
- Same signature
- One method in superclass, one in subclass
- Different signature
- Both methods can be in same class
Constructors and Inheritance
- Constructors are not inherited by a subclass
- Instead, superclass constructors are called by the subclass constructor
- Superclass constructors are called either implicitly or explicitly using
super()
Examples of Subclass Constructors
- Here is a no-parameter constructor for
Student
:public class Student extends Person { private int studentNumber; public Student() { super(); studentNumber = 0; } ...
- The first statement of the constructor is
super()
which calls the no-argument constructor of the superclass - After the superclass constructor finishes, this constructor then initializes the attribute
studentNumber
to 0 - We could have left out the call to
super()
because Java automatically includes it if not explicitly stated - If you want to call a different constructor, then you use
super()
with arguments of the correct type:... public Student(String name, int number) { super(name); studentNumber = number; }
- This constructor passes the parameter
name
to the constructor of the superclass - After which the
Student()
constructor initializes the instance variablestudentNumber
- Note that
super()
must be first action in a constructor definition
Activity 11.1: An Employee Subclass (10 pts)
- In the same folder where you saved Address.java, Person.java and PersonTest.java, add two more classes:
- Employee.java
- EmployeeTest.java
- Copy and paste the below starter code into Employee.java:
/**
* Employee.java extends Person.java
* @author
* CIS 36B, Activity 11.1
*/
public class Employee extends Person {
private static int numEmployees = 0;
private double salary;
private String title;
/**
* Default constructor for the
* Employee class. Calls the
* default constructor of the
* superclass and also initializes
* salary and title to default
* values
*/
public Employee() {
}
/**
* Multi-argument constructor for the
* Employee class. Calls the
* multi-argument constructor of the
* superclass and also initializes
* salary and title to the
* specified values
*/
public Employee(String name, int age, String gender, Address a, double salary, String title) {
}
/**
* Returns the annual salary
* @return the salary
*/
public double getSalary() {
* Employee.java extends Person.java
* @author
* CIS 36B, Activity 11.1
*/
public class Employee extends Person {
private static int numEmployees = 0;
private double salary;
private String title;
/**
* Default constructor for the
* Employee class. Calls the
* default constructor of the
* superclass and also initializes
* salary and title to default
* values
*/
public Employee() {
}
/**
* Multi-argument constructor for the
* Employee class. Calls the
* multi-argument constructor of the
* superclass and also initializes
* salary and title to the
* specified values
*/
public Employee(String name, int age, String gender, Address a, double salary, String title) {
}
/**
* Returns the annual salary
* @return the salary
*/
public double getSalary() {
return -1.0;
}
/**
* Returns the title (position)
* of the employee in the company
* @return the title
*/
public String getTitle() {
/**
* Returns the title (position)
* of the employee in the company
* @return the title
*/
public String getTitle() {
return "";
}
/**
* Returns the total number of employees
* @return the number of employees
*/
public static int getNumEmployees() {
/**
* Returns the total number of employees
* @return the number of employees
*/
public static int getNumEmployees() {
return -1;
}
/**
* Updates the salary with a new value
* @param salary the new salary
*/
public void setSalary(double salary) {
}
/**
* Updates the title of the employee
* @param title the new title
*/
public void setTitle(String title) {
}
/**
* Increments numEmployees
*/
public static void updateNumEmployees() {
}
/**
* To String method for an employee
* Calls the toString method of the
* superclass and also appends the title
* and salary information
*/
@Override public String toString() {
/**
* Updates the salary with a new value
* @param salary the new salary
*/
public void setSalary(double salary) {
}
/**
* Updates the title of the employee
* @param title the new title
*/
public void setTitle(String title) {
}
/**
* Increments numEmployees
*/
public static void updateNumEmployees() {
}
/**
* To String method for an employee
* Calls the toString method of the
* superclass and also appends the title
* and salary information
*/
@Override public String toString() {
return "";
}
}
}
- Notice that this class is a subclass of Person (it extends Person).
- Your job is to implement the method bodies of the above methods, as described in the method javadoc comments
- When you have implemented all methods, copy and paste the below code into EmployeeTest.java, and make sure your output works as shown.
/**
* EmployeeTest.java
* @author
* CIS 36B, Activity 11.1
*/
import java.util.Scanner;
public class EmployeeTest {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String name, gender, street, title;
int age, number;
double salary;
Employee employee;
System.out.print("Welcome!\n\nEnter your name: ");
name = input.nextLine();
System.out.print("Enter your age: ");
age = input.nextInt();
System.out.print("Enter your gender: ");
gender = input.next();
System.out.print("Enter the street number of your address: ");
number = input.nextInt();
System.out.print("Enter the name of your street: ");
input.nextLine();
street = input.nextLine();
Address address = new Address(number, street);
System.out.print("Enter your title in the company: ");
title = input.nextLine();
System.out.print("Enter your annual salary: ");
salary = input.nextDouble();
employee = new Employee(name, age, gender, address, salary, title);
Employee.updateNumEmployees();
System.out.println("\nYour Summary:\n" + employee);
input.close();
}
}
* EmployeeTest.java
* @author
* CIS 36B, Activity 11.1
*/
import java.util.Scanner;
public class EmployeeTest {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String name, gender, street, title;
int age, number;
double salary;
Employee employee;
System.out.print("Welcome!\n\nEnter your name: ");
name = input.nextLine();
System.out.print("Enter your age: ");
age = input.nextInt();
System.out.print("Enter your gender: ");
gender = input.next();
System.out.print("Enter the street number of your address: ");
number = input.nextInt();
System.out.print("Enter the name of your street: ");
input.nextLine();
street = input.nextLine();
Address address = new Address(number, street);
System.out.print("Enter your title in the company: ");
title = input.nextLine();
System.out.print("Enter your annual salary: ");
salary = input.nextDouble();
employee = new Employee(name, age, gender, address, salary, title);
Employee.updateNumEmployees();
System.out.println("\nYour Summary:\n" + employee);
input.close();
}
}
- When
your program works as shown in the sample output, upload Employee.java
to Canvas.
Sample Output:
Enter your name: Rajya Chahal
Enter your age: 32
Enter your gender: F
Enter the street number of your address: 21899
Enter the name of your street: Summit Rd
Enter your title in the company: Vice President of Operations
Enter your annual salary: 185000
Your Summary:
Name: Rajya Chahal
Age: 32
Gender: F
Address: 21899 Summit Rd
Salary: $185000.0
Title: Vice President of Operations
2. Using Access Modifiers
- You use the keywords
public
,private
andprotected
to control access to class members - Controls access to class instance variables and methods
public
Access: Interface Access
- Least restrictive of all access modifiers
public
fields and methods can be accessed from anywhere the class is accessible:public class MyClass { public double x; public void foo() {} }
private
Access: Don't Touch That!
- Most restrictive of all access modifiers
private
fields and methods cannot be accessed from outside of the class- Good design practice to make all variables
private
and to provide accessor methods where needed - Auxiliary ("helper") methods are declared
private
often as well - Generally do not declare a class private -- how would you use it?
public class MyClass { private double x; private void foo() {} }
protected
Access: Inheritance Access
- Accessible in the package of this class and any subclass of this class (which may be in other packages)
- More restrictive than
public
accessibility but less restrictive than defaultpublic class MyClass { protected double x; protected void foo() {} }
Package Access: the Default
- No access modifier: known as default or package accessibility
- Only accessible to other classes in the same package (directory)
- Less restrictive than
private
accessibility, but more restrictive thanpublic
orprotected
accessclass MyClass { double x; void foo() {} }
In our course, we will be using
private
andpublic
access modifiers only as these are the most common
Group Activity: Why will the below code not compile?
public class Parent {
private String name;
private int age;
@Override public String toString() {
return "Name: " + name + "\nAge: " + age;
}
}
public class Child extends Parent {
private double height;
@Override public String toString() {
return "Name: " + name + "\nAge: " + age + "\nHeight: " + height;
}
}
Wrap Up:
- Answer the practice exam questions questions for this lesson on Canvas.
Upcoming Assignments:
- Activity 11.1 due Tuesday at 11:59pm on Canvas
- Lesson 11 Practice Exam Questions due Tuesday at 11:59pm on Canvas
- Quiz 5 due Friday at 11:59pm on Canvas
- Peer Reviews for Lesson 11 Practice Exam Questions due Saturday at 11:59pm on Canvas
~ Have a Great Day! ~