Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

lesson3-javabasic-structure_java_class-access_modifiers_intro_to_inheritance

This lesson covers the structure and components of Java source code files, including the definition of classes and interfaces, the use of import and package statements, and the concept of executable versus non-executable classes. It explains access modifiers (public, protected, default, private) and their implications for class accessibility, as well as the principles of inheritance in Java, emphasizing the reusability of code and the relationship between base and derived classes. Additionally, it highlights the importance of inheritance in creating logical structures and facilitating code modification.

Uploaded by

dalianmarks4
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

lesson3-javabasic-structure_java_class-access_modifiers_intro_to_inheritance

This lesson covers the structure and components of Java source code files, including the definition of classes and interfaces, the use of import and package statements, and the concept of executable versus non-executable classes. It explains access modifiers (public, protected, default, private) and their implications for class accessibility, as well as the principles of inheritance in Java, emphasizing the reusability of code and the relationship between base and derived classes. Additionally, it highlights the importance of inheritance in creating logical structures and facilitating code modification.

Uploaded by

dalianmarks4
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

LESSON 3: JAVA BASIC AND INHERITANCE

Structure and components of a Java source code file


A Java source code file is used to define classes and interfaces. All your Java code should be defined
in Java source code files (text files whose names end with .java). The exam covers the following
aspects of the structure of a Java source code file:
 Definition of a class and an interface in a Java source code file
 Definition of single or multiple classes and interfaces within the same Java source code file
 Application of import and package statements to all the classes in a Java source code file

DEFINITION OF INTERFACES IN A JAVA SOURCE CODE FILE


An interface is a group of related methods and constants, but the methods in an interface cannot
define any implementation. An interface specifies a contract for the classes to implement.
No matter which brand of television each one of us has, every television provides the common
functionality of changing the channel and adjusting the volume. You can compare the controls of a
television set to an interface, and the design of a television set to a class that implements the
interface controls.

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.

Executable Java classes versus nonexecutable Java classes


An executable Java class is a class which, when handed over to the JVM, starts its execution at a
particular point in the class—the main method, defined in the class. The JVM starts executing the
code that is defined in the main method. You cannot hand over a nonexecutable Java class to the
JVM and ask it to start executing the class. In this case, the JVM won’t know how to execute it
because no entry point is marked, for the JVM, in a nonexecutable class.

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

Application UserData UserReferences

LaunchApplicsation public static void main(String[]arg){

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");
}
}

This main method should comply with the following rules:


 The method must be marked as a public method.
 The method must be marked as a static method.
 The name of the method must be main.
 The return type of this method must be void.
 The method must accept a method argument of a String array or a variable argument of type
String.

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)

The need for packages


You can use packages to group together a related set of classes and interfaces. Packages also provide
access protection and namespace management. You can create separate packages to define classes
for separate projects, such as android games and online health-care systems. Further, you can create
subpackages within these packages, such as separate subpackages for GUIs, database access,
networking, and so on.

Using simple names with import statements


The import statement enables you to use simple names instead of using fully qualified names for
classes and interfaces defined in separate packages. Let’s work with a real-life example. Imagine
your Home and your neighbor’s Office. “LivingRoom” and “Kitchen” within your home can refer to
each other without mentioning that they exist within the same home. Similarly, in an office, a
Cubicle and a ConferenceHall can refer to each other without explicitly mentioning that they exist
within the same office. But “Home” and “Office” can’t access each other’s rooms or cubicles without
stating that they exist in a separate home or office.

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;
}

Java Access Modifiers


The Java access modifiers includes public, protected, and private—as well as default access, which is
the result when you don’t use an access modifier. Let’s start with an example. Examine the
definitions of the classes House and Book in the following code

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.

WHAT DO ACCESS MODIFIERS CONTROL?


Access modifiers control the accessibility of a class or an interface, including its members (methods
and variables), by other classes and interfaces. For example, you can’t access the private variables
and methods of another class. By using the appropriate access modifiers, you can limit access to
your class or interface, and their members, by other classes and interfaces.

CAN ACCESS MODIFIERS BE APPLIED TO ALL TYPES OF JAVA ENTITIES?


Access modifiers can be applied to classes, interfaces, and their members (instance and class
variables and methods). Local variables and method parameters can’t be defined using access
modifiers. An attempt to do so will prevent the code from compiling.

Java defines four access modifiers:


 public (least restrictive)
 protected
 default
 private (most restrictive)
The classes Book, CourseBook, and Librarian are defined in the package library. The classes
StoryBook and House are defined in the package building. Further, classes StoryBook and
CourseBook (defined in separate packages) extend class Book. Using these classes, they show how
the accessibility of a class and its members varies with different access modifiers, from unrelated to
derived classes, across packages. As we cover each of the access modifiers, we’ll add a set of
instance variables and a method to the class Book with the relevant access modifier. We’ll then
define code for the other classes that try to access class Book and its members.

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

Public access modifier


This is the least restrictive access modifier. Classes and interfaces defined using the public access
modifier are accessible across all packages, from derived to unrelated classes.

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;

public class House {


House() {
Book book = new Book();
String value = book.isbn;
book.printBook();
}
}

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

Public accessibility Same Package Separate Package


Derived classes  
Unrelated Classes  
Table 1.1 Classes that can access a public class and its members

Protected access modifier


The members of a class defined using the protected access modifiers are accessible to
 Classes and interfaces defined in the same package
 All derived classes, even if they’re defined in separate packages

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

Default access (package access)


The members of a class defined without using any explicit access modifier are defined with package
accessibility (also called default accessibility). The members with package access are only accessible
to classes and interfaces defined in the same package. Let’s define an instance variable issueCount
and a method issueHistory.

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)

Default accessibility Same Package Separate Package


Derived classes  
Unrelated Classes  
Table 1.3 Classes that can access members with Default access and its members

Private access modifier


The private access modifier is the most restrictive access modifier. The members of a class defined
using the private access modifier are accessible only to themselves. It doesn’t matter whether the
class or interface in question is from another package or has extended the class—private members
are not accessible outside the class in which they’re defined. private members are accessible only to
the classes and interfaces in which they are defined. Let’s see this in action by adding a private
method countPages to the class Book.

Examine the following definition of the class Book:

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

Inheritance is a reusability mechanism in object-oriented programming in which the common


properties of various objects are exploited to form relationships with each other. The abstract and
common properties are provided in the superclass, which is available to the more specialized
subclasses. For example, a color printer and a black-and-white printer are kinds of a printer (single
inheritance); an all-in-one printer is a printer, scanner, and photocopier (multiple inheritance). It
should be noted that Java does not support multiple inheritance but does support multiple-interface
inheritance (discussed in detail in Chapters 4 and 5). When we say that a class B is inherited from
another class A, then class B is referred to as a derived class (or subclass) and class A is called as a
base class (or superclass). By inheritance, the derived class receives the behavior of the base class,
such that all the visible member methods and variables of the base class are available in the derived
class. Apart from the inherited behavior, the derived class specializes its behavior by adding to or
overriding base class behavior.

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.

The Importance of Inheritance


 Smaller derived class definition
 Ease of modification of common properties and behaviors
 Extensibility
 Use tried-tested code from base class
 Concentrate on specializes behaviors of classes
 Logical Structures and grouping

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

2. Which of the following statements are true?


a) Inheritance enables you to reuse existing code.
b) Inheritance saves you from having to modify common code in multiple classes.
c) Polymorphism passes special instructions to the compiler so that the code can
run on multiple platforms.
d) Polymorphic methods cannot throw exceptions.

3. Examine the following code:


class Course {
String courseName;
}
class EJavaGuru {
public static void main(String args[]) {
Course c = new Course();
c.courseName = "Java";
System.out.println(c.courseName);
}
}
4. Which of the following statements will be true if the variable courseName is defined as
a private variable?
a )class EJavaGuru will print Java.
b )class EJavaGuru will print null.
c) class EJavaGuru won’t compile.
d )class EJavaGuru will throw an exception at runtime.

4.Given the following code, select the correct options:


package com.ejavaguru.courses;
class Course {
public String courseName;
public void setCourseName(private String name) {
courseName = name;
}
}
a) You can’t define a method argument as a private variable.
b )A method argument should be defined with either public or default accessibility.
c )For overridden methods, method arguments should be defined with protected
accessibility.
d) None of the above.

You might also like