Transcript class
Programming in Java
CSCI-2220
Object Oriented Programming
OOP Model
• Organization is centered around objects
rather than actions
• Central design of programs is based on
how data is defined and how it can be
manipulated rather than the sequential
logic of the program
• Java embraces this model as the core of
its design
Classes
• Everything in Java is a class (basically)
• A class defines a new data type and all of the properties
that an object of that type contains
– Fields (data members, instance variables, …)
– Methods (procedures to possibly manipulate the fields or provide
some other functionality)
• Each instance of a class has a copy of all non-static
fields and methods defined for that class
– Actually the method code is shared among all instances but
conceptually this is not important
• Only one copy of static fields and methods exists for
each class
Revisiting static
• static class members
– can be accessed from outside of its class through the use of the
class name
– can be accessed from inside any member class method with or
without the class name
• static methods
– Do not have access to non-static methods or fields (you will get
a compiler error if you try this)
– Makes sense since static members are not associated with any
particular object and exist even before any object of the class is
instantiated
Initializing data
• Three ways to initialize class member variables
– Right in the class body during variable declaration
class MyClass {
String myVariable = “foo”;
int a = 10;
}
– Initialization blocks (can also be static)
class MyClass {
int myArray[];
{
myArray = new int[10];
for(int i = 0; myArray.length < i++)
myArray[i] = i;
}
}
– Constructors
Constructors
• A constructor is a special method used to initialize class
members with custom specified data during instantiation
• Declared with no return type and a name which is the
same as the class name
class MyClass {
MyClass(..parameters..)
{
//initialize data here
}
}
• If you do not create a constructor, Java automatically
provides one that takes no arguments and does nothing
• If you create any constructor at all (including one with
arguments), the default constructor will not be created
for you
Method Overloading
• Methods with the same name in one class
can be created as long as they have
different parameters
• You can overload constructors just as you
can other methods
• You can call one constructor from another
constructor using the this keyword
Destructors
• No such thing!
• Java has a garbage collector that
automatically cleans up objects that are no
longer referenced in your program
• Each class also has a finalize() method
that is called when the object is garbage
collected
• You probably don’t want to do anything
with it
Packages
• Java has an additional level of support for organizing
your classes called packages
• You can put a class in a package by declaring the
package at the type of the file
package myPackage;
class MyClass {
MyClass(..parameters..)
{
//initialize data here
}
}
• Note: Java is strict with its file and directory naming
conventions and organization. All classes that you put
into a package must reside in a directory with that
package name
Modifiers
• Java has access attributes similar to C++
– No modifier
• Can be accessed by any class in the same package
– public
• Accessible by anyone
– private
• Can be accessed by any methods within the class. Note that this
includes a separate instantiation of the same class
– protected
• Can be accessed by any class in the same package and any
subclass in any package
Inheritance
• Sometimes when designing classes we run into the
following relationship
– Class1 is a more specialized form of Class2
• In this situation we do not want to duplicate all of the
functionality and attributes in Class1
• Instead we create Class2 as a subclass of Class1
• Class2 inherits all of the fields and methods provided in
Class1 and can also define additional functionality for its
specialized features
Inheritance
• We declare a class as a subclass of another through the
use of the extends keyword
class SubClass extends BaseClass{
…
}
• A class can be a subclass of only one other class
• All fields and methods of the base class are inherited by
the subclass
– Private data members of the base class do exist in the subclass
but they are not accessible directly by any method of the
subclass
– Static data members of the base class are also inherited
meaning that the sub class and base class share one copy of the
static members
Subclass Constructors
• Constructors of a subclass should always call one of the
constructors of the base class first
• This can be done with the super keyword
class SubClass extends BaseClass{
SubClass() {
super(..arguments..);
}
}
• If you do not call a constructor of the base class, Java
will automatically call the default constructor of the base
class at the beginning of your constructor
• If the base class does not have a default constructor, this
will generate an error
Method Overriding
• You can override any method of the base class by
declaring the method in your subclass with the same
signature (same return type, method name, and
parameter list)
• If you have overridden a base class method and wish to
access the base class version of it, you can again use
the super keyword
class SubClass extends BaseClass{
…
public String baseMethod() {
return super.baseMethod() + “\n”;
}
}
The Object class
• Every class in Java extends one and only one class
(except for one)
• If you don’t specify a base class, your class
automatically extends the Object class
– Every class in Java contains the basic functionality methods
defined in the Object class
– Refer to the Java API for a complete spec on the Object class
• The net result of this design is that Java classes make
up one giant hierarchy with the Object class at the top
Polymorphism
• The power of OOP programming is realized through
polymorphism
• Say we wish to work with a list of user accounts in the
RPI CS department
• We have defined a class called UserAccount with two
subclasses
– StudentUserAccount
– ProfessorUserAccount
• Polymorphism allows us work with a list of UserAccounts
without knowing or caring what type of accounts they are
Polymorphism
• In Java we can assign a variable of a certain class type
an instance of that particular class or an instance of any
subclass of that class
UserAccount myAccount = new StudentUserAccount();
• Now the myAccount variable looks like a UserAccount
object and can be treated exactly like one but under the
hood it is actually a StudentUserAccount object
• We can typecast it back to a StudentUserAccount type if
we ever need the specialized functionality of the
StudentUserAccount class
StudentUserAccount myStudentAccount =
(StudentUserAccount)myAccount;
Dynamic Type Checking!
• Java has support for dynamic type checking which is the
true power of polymorphism
• Example:
– UserAccount has a method named privileges() which returns a
list of privileges associated with that account
– StudentUserAccount and ProfessorUserAccount each have
overridden the privileges() method with their own specialized
functionality
– A UserAccount variable instantiated with a StudentUserAccount
object calls the privileges() method
– At run-time, Java checks the type of this object and sees that it is
a StudentUserAccount and therefore calls the
StudentUserAccount version of the privileges() method instead
of the UserAccount version
Abstract classes
• You can declare a class abstract with the abstract
keyword
public abstract class Animal {
public abstract void sound();
public Animal(String type) {
this.type = type;
}
public String toString() {
return “This is a “ + type;
}
private String type;
}
• Abstract classes provide a prototype but not an
implementation for some of its methods because the
context of the implementation is only important in
subclasses
Abstract classes
• Are intended to be base classes
• Cannot be instantiated
• You can declare variables of an abstract
class type but they can only be assigned
instantiations of a subclass of the abstract
class
Interfaces
• Takes the abstraction one step further
• Only defines a set of methods that represent the class
interface but does not provide an implementation
• Can also define constants
public interface Shape {
double PI = 3.14;
int Area();
String name();
}
• All methods of an interface are automatically public and
abstract so you do not need to explicitly specify this
Interfaces
• Java provides support for pseudo-multiple-inheritance
through the use of interfaces
– Classes can extend one and only one class
– However, classes can implement any number of interfaces
public class Circle implements Shape {
…
}
• A class that implements an interface must provide an
implementation for each method defined in the interface
• If a class implements more than one interface that have
identical methods, one implementation of the method is
sufficient as long as the return type is the same in both
interfaces
Interfaces
• Polymorphism can be used with interfaces
too!
• Example
– From the previous slide we can create a
variable of type Shape
– We can then assign this variable an
instantiation of the Circle class
• Interfaces cannot be instantiated (clearly)
Factory Creation Pattern
• Problem:
– You want to write an application that supports the native look and
feel of multiple GUI systems such as Windows and Mac
– You don’t want to rewrite your code for each system
• Solution:
– Define a common interface for using either interfaces or abstract
classes for each GUI element that you wish to use
– Define a concrete subclass of each GUI element for each
windowing system that you wish to support
– Your application works directly with the abstract class interface
and does not know or care what type of object it is using
Factory Creation Pattern
Button
MacButton
Application works directly
with the abstract classes
WindowsButton
Objects are instantiated using
the concrete subclasses.
Menu
MacMenu
WindowsMenu
Question: How can we work only with the abstract classes if we must
instantiate them using one of the concrete subclasses?
Answer: Factories
public interface WidgetFactory {
Button newButtonInstance();
Menu newMenuInstance();
}
public class WindowsWidgetFactory implements WidgetFactory {
public Button newButtonInstance()
{
return new WindowsButton();
}
public Menu newMenuInstance()
{
return new WindowsMenu();
}
}
public class MacWidgetFactory implements WidgetFactory {
public Button newButtonInstance()
{
return new MacButton();
}
public Menu newMenuInstance()
{
return new MacMenu();
}
}
Factory Creation Pattern
• Using the factories, you can instantiate your objects without even
knowing which subclass of the abstract class you’re instantiating!
public class FactoryTest {
public static void main(String[] args)
{
WidgetFactory factory = new WindowsWidgetFactory();
//WidgetFactory factory = new MacWidgetFactory();
Button myButton = factory.newButtonInstance();
Menu myMenu = factory.newMenuInstance();
}
}
Homework 2
• Homework 2 is out and posted online
• Due February 9 11:55 PM
• Don’t forget to submit HW1 by tonight!