Chapter 6
Chapter 6
Learning Java
Inherits variables and methods not designated as private from its superclass
Define a method that has exactly the same method signature (name and argument types) as a method
in its superclass.
Overriding methods to change the behavior of objects is called subtype polymorphism
}
…
}
Faculty of Computer Science
class Book3 { Title: Webster English Dictionary
protected String title; Number of pages: 1500
protected int pages; Number of definitions: 52500
public Book3(String title,int pages){ Definitions per page: 35
this.title=title;
class Dictionary3 extends Book3{
this.pages=pages;
private int definitions;
}
public Dictionary3(String title,int pages, int definitions)
public void info(){
{
System.out.println("Title: "+title);
super(title,pages);
System.out.println("Number of
this.definitions=definitions;
pages: "+pages);
}
}
Public void info(){
}
super.info();
System.out.println("Number of definitions:
"+definitions);
System.out.println("Definitions per page:
class Books {
"+definitions/pages);
Public static void main(String args[]){
}
Dictionary3 webster2=new
}
Dictionary3("Webster English Dictionary",
1500, 52500);
webster2.info();
}
Faculty of Computer Science
}
I. Inheritance
Example
}
Faculty of Computer Science
I. Inheritance
Abstract - Example
Extend two or more interfaces, list them after the extends keyword, separated by
commas
ALL of the method headings listed in the interface definition must be implemented.
A Java interface is a collection of constants and abstract methods since all methods in an
interface are abstract, the abstract modifier is usually left off.
Interface Variables
interface Scaleable {
static final int BIG = 0, MEDIUM = 1, SMALL = 2;
void setScale( int size );
}
A Java class can only extend one parent class. Multiple inheritance is not allowed. Interfaces are not
classes, however, and an interface can extend more than one parent interface.
The implements keyword is used once, and the parent interfaces are declared in a comma-separated
list.
An interface can extend multiple interfaces.
A class can implement multiple interfaces.
However, a class can only extend a single class.
Class Visibility
Classes within a package can refer to each other by their simple names
To locate a class in another package, use import statements at the top of a compilation unit
Example: import java.io.InputStream;
Import all the classes in a package using the * wildcard notation
Example: import java.io.*;
static import
Example
• In main function ,
Animal monkey = new Animal();
Animal.Brain monkeyBrain = monkey.new Brain();
monkey.performBehavior();
monkeyBrain.restBrain();
Using inner classes strategically can make your code cleaner, more modular, and easier to
maintain.
@Override
public String toString(){