Lecture 12
March 16, 2000
The Scope of a Variable
• What if there are two variables with the same name?– A local or block-local variable can have the
same name as a class or instance variable.– (Other languages are not so restrictive.)
• [ Scope.java ]
Object-Oriented Programming(OOP)
• Goals– Reduce development costs– Improve software reliability– Reduce maintenance costs
• Principles– Encapsulation– Inheritance– Polymorphism
Goals
• Reduce development costs– Code reuse– Find bugs sooner (easier to fix)– Enforce good programming practices
• Increase reliability– Find bugs automatically
• Reduce maintenance costs– Real-world programs last a long time
OOP PrinciplesEncapsulation
• Programs = Algorithms + Data Structures– Use classes to put data and the algorithms (methods)
that manipulate those data together.
• Example: You can use class Vector without knowing how it is implemented internally.– Public methods provide the “interface” to the class.– As long as you don’t change the signatures of the
public methods, you can change the internal details all you want.
• Benefits: Modularity, Maintainability
Encapsulation
Public Methods Private Methods Private Data
Class“Capsule”
Modularity
• Separate Compilation
• Parallel Development
• Intellectually Manageable “Chunks”
Maintainability
• Lifetime of a Program– Design
• Decide what it will do and how
– Implement• Write and test the code
– Maintain• Fix bugs and add features
• Academia– Professor designs. You write and test. End.
Object-Oriented ProgrammingInheritance
• A class can extend another class.– Java supports “single inheritance.”
• A subclass extends a superclass.
• Leads to a class hierarchy; a tree of classes.
rootNodes:
Java Class Hierarchy
• The root class is java.lang.Object– All other classes are direct or indirect
subclasses of class Object– You don’t have to declare that a class is a
subclass if it is a direct subclass of Object:• class MyClass { … }• class MyClass extends Object { … }• class MyClass extends java.lang.Object { … }
• Consider class javax.swing.JApplet
Subclasses and Superclasses• A subclass inherits methods and fields from its
superclass, super-superclass, etc.– A subclass object therefore is a superclass object, but
with additional features.– A superclass may override some or all of its superclass’
methods.
• Exercise: Write a superclass and a subclass that both implement a method named identifyYourself(), but differently from each other.– Have the subclass provide an additional method, saySomethingNice().
– [ TestClasses.java ]