lesson3-javabasic-structure_java_class-access_modifiers_intro_to_inheritance
lesson3-javabasic-structure_java_class-access_modifiers_intro_to_inheritance
interface Controls {
void changeChannel(int channelNumber);
void increaseVolume();
void decreaseVolume();
}
DEFINITION OF SINGLE AND MULTIPLE CLASSES IN A SINGLE JAVA SOURCE CODE FILE
You can define either a single class or an interface in a single Java source code file, or many such
files. Let’s start with a simple example: a Java source code file called Single-Class.java that defines a
single class SingleClass:
class SingleClass {
//.. we are not detailing this part
}
Here’s an example of a Java source code file, Multiple1.java, that defines multiple interfaces:
interface Printable {
//.. we are not detailing this part
}
interface Movable {
//.. we are not detailing this part
}
You can also define a combination of classes and interfaces in the same Java source
code file. Here’s an example:
interface Printable {
//.. we are not detailing this part
}
class MyClass {
//.. we are not detailing this part
}
interface Movable {
//.. we are not detailing this part
}
class Car {
//.. we are not detailing this part
}
There is no required order for the multiple classes or interfaces that can be defined in a single Java
source code file.
Typically, an application consists of a number of classes and interfaces that are defined in multiple
Java source code files. Of all these files, a programmer designates one of the classes as an executable
class. The programmer can define the steps that the JVM should execute as soon as it launches the
application. For example, a programmer can define an executable Java class that includes code to
display the appropriate GUI window to a user and to open a database connection.
Windows ServerConnection
Classes in
displayGUI();
OpenDatabaseConnection();
---
---
Figure 1.3 Class LaunchApplication is an executable Java class, but the rest of the classes—
Window, UserData, ServerConnection, and UserPreferences—aren’t.
Main method
The first requirement in creating an executable Java application is to create a class with a method
whose signature (name and method arguments) match the main method, defined as follows:
public class HelloExam {
public static void main(String args[]) {
System.out.println("Hello exam");
}
}
It’s interesting to note that the placement of the keywords public and static can be interchanged,
which means that the following are both correct method declarations of the main method:
Eg.
public static void main(String[] args)
static public void main(String[] args)
home office
LivingRoom Cubicle
Kitching ConferenceHall
Figure 1.4 A UML representation of classes LivingRoom and Cubicle, defined in separate packages,
with their associations
Class Cubicle can refer to class LivingRoom without using an import statement:
package office;
class Cubicle {
home.LivingRoom livingRoom; Full qualified name goes without import statement.
}
Class Cubicle can use the simple name for class LivingRoom by using the import statement:
package office;
import home.LivingRoom;
class Cubicle {
LivingRoom livingRoom;
}
package building;
class House {}
package library;
class Book {}
With the current class definitions, the class House cannot access the class Book. Can you make the
necessary changes (in terms of the access modifiers) to make the class Book accessible to the class
House? This one shouldn’t be difficult.
A top-level class can be defined only using the public or default access modifiers. If you declare the
class Book using the access modifier public, it’ll be accessible outside the package in which it is
defined.
library building
extends
Book StoryBook
eeee
House
extends Librarian
CourseBook
Figure 1.5 A set of classes and their relationships to help understand access modifiers
To understand the public access modifier, let’s define the class Book as a public class and add a
public instance variable (isbn) and a public method (printBook) to it.
Definition of class Book:
package library;
public class Book {
public String isbn;
public void printBook() {}
}
The public access modifier is said to be the least restrictive, so let’s try to access the public class
Book and its public members from class House. We’ll use class House because House and Book are
defined in separate packages and they’re unrelated. Class House doesn’t enjoy any advantages by
being defined in the same package or being a derived class.
Here’s the code for class House:
package building;
import library.Book;
As you may notice in the previous example, the class Book and its public members—instance
variable isbn and method printBook—are accessible to the class House. They are also accessible to
the other classes: StoryBook, Librarian, House, and Course- Book
Here’s the code for the class Book (I’ve deliberately left out its public members because they aren’t
required in this section):
package library;
public class Book {
protected String author;
protected void modifyTemplate() {}
}
Class House throws a compilation error message for trying to access the method modifyTemplate
and the variable author, as follows:
House.java:8: modifyTemplate() has protected access in library.Book book.modifyTemplate();
This is because they are protected members of the class Book and are in separate package from the
class House.
Notice that the derived classes CourseBook and StoryBook can access the class Book’s protected
variable author and method modifyTemplate as if they were defined in their own classes. If class
StoryBook tries to create an object of class Book and then tries to access its protected variable
author and modifyTemplate, it will not compile:
Protected accessibility Same Package Separate Package
Derived classes
Unrelated Classes
Table 1.2 Classes that can access a protected class and its members
Here’s the code for the class Book (I’ve deliberately left out its public and protected members
because they aren’t required in this section):
package library;
public class Book {
int issueCount;
void issueHistory() {}
}
You can see how classes from the same package and separate packages, derived classes,
and unrelated classes access the class Book and its members (the variable issueCount and
the method issueHistory)
package library;
class Book {
private void countPages() {}
protected void modifyTemplate() {
countPages();
}
}
Default accessibility Same Package Separate Package
Derived classes
Unrelated Classes
Table 1.4 No class can access private members of another class
Applying inheritance
All living beings inherit the characteristics and behaviors of their parents. The offspring of a fly looks and
behaves like a fly, and that of a lion looks and behaves like a lion. But despite being similar to their parents, all
offspring are also different and unique in their own ways. Additionally, a single action may have different
meanings for different beings. For example, the action “eat” has different meanings for a fly and a lion. A fly
eats nectar, whereas a lion eats antelope.
Something similar happens in Java. The concept of inheriting characteristics and behaviors from
parents can be compared to classes inheriting variables and methods from a parent class. Being
different and unique in one’s own way is similar to how a class can both inherit from a parent and
also define additional variables and methods. Single actions having different meanings can be
compared to polymorphism in Java.
Let’s assume you’re supposed to store details of all Programmers and Managers in your office.
The code below shows the properties and behavior that you may have identified for a Programmer
and a Manager, together with their representations as classes.
Did you notice that the classes Programmer and Manager have common properties, namely, name,
address, phoneNumber, and experience? The next step is to pull out these common properties into
a new position and name it something like Employee.
class Programmer {
String name;
String address;
String phoneNumber;
float experience;
String[] programmingLanguages;
void writeCode() {}
}
class Manager {
String name;
String address;
String phoneNumber;
float experience;
int teamSize;
void reportProjectStatus() {}
}
Employee
Name
Address
phoneNumber
experience
Programmer Manager
Name Name
Address Address
phoneNumber phoneNumber
experience experience
programingLanguages teamSize
writeCode() reportProjectStatus()
Employee
Name
Address
phoneNumber
experience
Programmer Manager
programingLanguages teamSize
writeCode() reportProjectStatus
class Employee {
String name;
String address;
String phoneNumber;
float experience;
}
class Programmer extends Employee {
String[] programmingLanguages;
void writeCode() {}
}
class Manager extends Employee {
int teamSize;
void reportProjectStatus() {}
}
Inheriting a class is also referred to as subclassing. The inherited class Employee is also referred to as
the superclass, base class, or parent class. The classes Programmer and Manager that inherit the
class Employee are called subclasses, derived classes, extended classes, or child classes.
class HR {
void sendInvitation(Employee emp) {
System.out.println("Send invitation to" +emp.name + " at " +
emp.address);
}
}
EXAM TIP Inheritance enables you to reuse code that has already been defined by a class.
Inheritance can be implemented by extending a class.
Review Questions
1.What is the output of the following code?
class Animal {
void jump() { System.out.println("Animal"); }
}
class Cat extends Animal {
void jump(int a) { System.out.println("Cat"); }
}
class Rabbit extends Animal {
void jump() { System.out.println("Rabbit"); }
}
class Circus {
public static void main(String args[]) {
Animal cat = new Cat();
Rabbit rabbit = new Rabbit();
cat.jump();
rabbit.jump();
}
}
a )Animal
Rabbit
b) Cat
Rabbit
c) Animal
Animal
d) None of the above