CHAPTER 1: IS MANAGEMENT: ISSUES AND

advertisement
CHAPTER 4: Objects and Classes
Chapter Objectives
Upon completion of this chapter, you would have learnt:
a) Encapsulation, polymorphism, and inheritance : concept and its
implementation in Java
b) How to create classes and objects
c) How to use methods with arguments and return values, and how to use
constructors
d) Data hiding, method and constructor overloading
e) Sub-classing, the usage of extends, super and instanceof keywords,
casting objects
f) Methods overriding
g) How to invoke parent class constructors
h) static variables, methods and initializers
i) The final keyword, abstract classes and methods
j) How to define and implement interfaces
k) Access control and Wrapper classes
l) Programming exercises.
4-1
CS214
CHAPTER 4: OBJECTS and CLASSES
1.0 Objects Fundamental
OOP paradigm enables real-world concepts to be modeled in a computer program.
3 key features of OOP languages
- encapsulation
- polymorphism
- inheritance
OOP encapsulates data ( attributes ) and methods (behaviour) into objects ie. data
and object are tied together.
Objects have the property of information hiding ie. although objects know how to
communicate with one another across well-defined interface, objects are not
allowed to know how other objects are implemented
1.1 Class Fundamentals
In Java, the unit of programming is the class from which objects are instantiated
(created)
A class provides a definition for a particular type of object.
A class defines the data inside an object and the functionality provided by that
object to act on its own data.
A class is a template and objects are constructed based on their class model.
Please take note : The class defines what an object is, but it is not itself an object.
4-2
CS214
CHAPTER 4: OBJECTS and CLASSES
There is only one copy of a class definition in program, but there can be several
objects that are instances of that class
A class header has 3 parts :
a) an optional access modifier
b) the keyword class
c) any legal identifier for classname
The body of a class consists of
a) instance variables
b) methods
which is enclosed within a set of curly braces ( { } ).
Example
class StudInfo {
String name;
String id;
String classcode;
void printdetails ( ) {
System.out.println( name + “ ”+ id + “ ” + classcode );
}
}
The data, or variable ( or fields ) defined within a class are called instance
variable.
For the above example, name, id, and classcode are instance variables.
Methods and variables defined within a class are called members of the class.
4-3
CS214
CHAPTER 4: OBJECTS and CLASSES
1.2 How to create objects ?
As mentioned in the previous chapter, the new operator is used to create an object
of a class.

The new operator dynamically allocates memory for an object and returns a
reference to it. The reference is the address in memory of the object allocated
by new. This reference is then stored in the variable.
Example ( To instantiate an object and then assign values to the members ) :
StudInfo student = new StudInfo();
student.name = “Albert Lim”;
student.id = “0208-0101-1001”;
student.classcode = “AD0101PT”;
// calls method to print the details
student.printdetails( );

It is important to understand that new allocates memory for an object during
run-time. The advantage is that your program can create as many or as few
objects as it needs during the execution of your program.

Once you have created the object, you never have to worry about destroying it
since objects are automatically garbage collected in Java.
4-4
CS214
CHAPTER 4: OBJECTS and CLASSES
// the class StudInfo could be stored in a separate file, called StudInfo.java
class StudInfo {
String name;
String id;
String classcode;
void printDetails() {
System.out.println( name + " " + id + " " + classcode );
}
} // end of class StudInfo
class StudentDetails {
public static void main ( String args[] ) {
// to create a student's object
StudInfo student = new StudInfo();
// to access the object's variables
student.name = "Albert Lim";
student.id = "0208-0101-1001";
student.classcode = "AD0101PT";
// calls method to print the details
student.printDetails();
}
} // end of class StudentDetails
Try to create more StudInfo’s objects and display their details.
2.0 Methods
A method is a series of statements that perform certain task.
2.1 Method declaration :
<modifiers> <return type> <methodname> ( <argument_list> )
[ throws <exception> ] { <block> }
4-5
CS214
CHAPTER 4: OBJECTS and CLASSES
Example ( method requires no arguments, returns no value ) :
class Circle {
double radius =10;
double area;
static final double PI = 3.14;
void calArea() {
area = PI*radius*radius;
System.out.println("Radius = " + radius );
System.out.println("Area = " + area );
}
}
public class NoArgsNoReturn {
public static void main ( String args[] ) {
Circle myCircle = new Circle();
myCircle.calArea();
}
}
Example ( method requires single arguments, returns no value ) :
class Circle {
double radius;
double area;
static final double PI = 3.14;
void calArea(double r) {
area = PI*r*r;
System.out.println("Radius = " + r );
System.out.println("Area = " + area );
}
}
public class SingleArgsNoReturn {
public static void main ( String args[] ) {
Circle myCircle = new Circle();
myCircle.calArea(10.0);
}
}
4-6
CS214
CHAPTER 4: OBJECTS and CLASSES
Example ( method requires multiple arguments, returns no value ) :
class Circle {
double radius;
double area;
String colour;
static final double PI = 3.14;
void calArea(double r, String s) {
area = PI*r*r;
System.out.println("Radius of a circle = " + r );
System.out.println("Circle's colour = " + s );
System.out.println("Area of the circle = " + area );
}
}
public class MultiArgsNoReturn {
public static void main ( String args[] ) {
Circle myCircle = new Circle();
myCircle.calArea(10.0,"blue");
}
}
Example ( method requires multiple arguments, returns a value ) :
class Staff {
double salary;
String name;
Staff ( String n, double s ) {
name = n;
salary = s;
}
double calBonus (double extra, double rate) {
double bonus = (salary * rate) + extra ;
return bonus;
}
void display () {
System.out.println("Name = " + name );
System.out.println("Salary = " + salary );
}
}
4-7
CS214
CHAPTER 4: OBJECTS and CLASSES
public class MultiArgsReturnValue {
public static void main ( String args[] ) {
Staff staff1 = new Staff("Lim", 1200.0);
staff1.display();
System.out.println("Bonus = " + staff1.calBonus(100.0, 2.0));
}
}
2.2 Pass-by-value

The Java programming language only passes arguments by value. When an
object instance is passed as an argument to a method, the value of the
argument is a reference to the object. The contents of the object can be
changed in the called method, but the object reference is never changed.
class MyDate {
int day, month, year;
MyDate( int d, int m, int y ) {
day = d;
month = m;
year = y;
}
void setDay ( int d ) {
day = d;
}
void print() {
System.out.println("Date : " + day + "/" + month + "/" + year);
}
}
public class PassByValue {
public static void changeInt ( int val ) {
val = 55;
}
public static void changeObjectRef ( MyDate my ) {
my = new MyDate(15,3,1966 );
}
public static void changeObjectAttr ( MyDate my ) {
my.setDay(5);
}
4-8
CS214
CHAPTER 4: OBJECTS and CLASSES
public static void main ( String args[] ) {
MyDate date;
int value;
value =11;
changeInt(value); // try to change it
System.out.println("Value = " + value );
date = new MyDate( 27,4,1967 );
changeObjectRef(date);
date.print();
changeObjectAttr (date);
date.print();
}
}
Please take note : The MyDate object is not changed by the changeObjectRef( ),
however, the day attribute of the MyDate object is changed by the
changeObjectAttr( ).
2.3 this keyword

this can be used inside any method to refer to the current object or class
instance, i.e., this is always a reference to the object on which the method was
invoked.
Example :
public class TheDate {
private int day, month, year;
public void tomorrow ( ) {
this.day = this.day + 1;
// ….
}
}
4-9
CS214

CHAPTER 4: OBJECTS and CLASSES
Java automatically associates all instance variable and method references with
the this keyword.

Using this keyword in the previous code is redundant. An equivalent code is :
public class TheDate {
private int day, month, year;
public void tomorrow ( ) {
day = day + 1;
// …..
}
}

There are occasions when the keyword is not redundant. For example :
Birthday myDOB = new Birthday ( this );
class MyDate {
int day = 1, month=1, year=2001;
MyDate( int d, int m, int y ) {
this.day = d;
this.month = m;
this.year = y;
}
MyDate( MyDate date ) {
this.day = date.day;
this.month = date.month;
this.year = date.year;
}
MyDate addDays( int moreDays ) {
MyDate newDate = new MyDate(this);
newDate.day = newDate.day + moreDays;
return newDate;
}
void print() {
System.out.println("Date : " + day + "/" + month + "/" + year);
}
}
4 - 10
CS214
CHAPTER 4: OBJECTS and CLASSES
public class ThisSample {
public static void main ( String args[] ) {
MyDate myDOB = new MyDate(15,3,1966);
MyDate nextweek = myDOB.addDays(7);
nextweek.print();
}
}
3.0 Data Hiding

Data hiding is referred to as encapsulation

distinguishes the outside interface to the class from its implementation

hides the implementation details of a class

forces the user to use an interface to access data

makes the code much more maintainable
4.0 Constructors

A constructor initializes an object immediately upon creation. Once defined,
the constructor is automatically called immediately after the object is created,
before the new operator completes.
4 - 11
CS214

CHAPTER 4: OBJECTS and CLASSES
Constructors are identified by the 2 following rules :
a) the method name must exactly match the classname
b) there must not be a return type declared for the method
Example
public class Xyz {
// member variables go here
public Xyz ( ) {
// set up the object
}
public Xyz ( int x ) {
// set up the object with a parameter
}
}
Every class has at least one constructor. If you do not write a constructor, the Java
programming language provides one ( i.e. default constructor ) for you. The
default constructor takes no arguments and has an empty body.
5.0 Methods Overloading

In Java, it is possible to define two or more methods within the same class that
share the same name, as long as their parameter declarations are different.

When this is the case, the methods are said to be overloaded and the process is
referred to as method overloading.

Method overloading is one of the ways that Java implements polymorphism.
4 - 12
CS214

CHAPTER 4: OBJECTS and CLASSES
2 rules apply to overload method
a) arguments lists must differ
b) return types can be different
When an overloaded method is invoked, Java uses the type and/or number of
arguments as its guide to determine which version of the overloaded method to
actually call. Therefore, the overloaded methods must differ in the type and/or
number of arguments.
Example ( different types of argument ) :
public void print( int i )
{}
public void print ( float f )
{}
public void print ( String s )
{}
Example ( different number of arguments ) :
public void calculateArea( ) {
}
public void calculateArea ( double radius ) {
}
public double calculateArea( double radius, double diameter ){
}
4 - 13
CS214
CHAPTER 4: OBJECTS and CLASSES
class Weight {
boolean checkWeight (double weight) {
return weight>60;
}
String checkWeight (double weight, double height) {
if ((height < 150 ) && (weight > 80))
return "Need to exercise!";
else
return "OK";
}
void checkWeight (double weight, double height, char gender) {
System.out.println("Weight = " + weight );
System.out.println("Height = " + height );
System.out.println("Gender = " + gender );
if ((height > 150 ) && (gender =='M')) {
System.out.println("Still OK..");
} else {
System.out.println("Need to figure out yourself!");
}
}
}
class OverloadedMethods {
public static void main ( String args[] ) {
Weight myWeight = new Weight();
System.out.println("Am I overweight ? : " + myWeight.checkWeight(70.0));
System.out.println("Height= 130cm, Weight=80kg, Advice = " +
myWeight.checkWeight(130.0,80.0));
myWeight.checkWeight( 80.0, 170.0, 'F');
}
}
Identify the output.
6.0 Overloading Constructors
In addition to overloading methods, you can overload constructors too. The proper
overloaded constructor is called based upon the parameters specified when new is
executed.
4 - 14
CS214
CHAPTER 4: OBJECTS and CLASSES
Example :
// overloaded constructors
class Employee {
private String name;
private int salary;
public Employee ( String n , int s ) {
name = n;
salary = s;
}
public Employee ( String n ) {
this (n, 0 );
}
public Employee ( ) {
this ( "unknown");
}
public void display() {
System.out.println();
System.out.println("Name : " + name );
System.out.println("Salary : " + salary);
}
}
class OverloadedConstructor {
public static void main ( String args[] ) {
Employee e1 = new Employee();
e1.display();
Employee e2 = new Employee("Mary", 3000);
e2.display();
Employee e3 = new Employee("Bond");
e3.display();
}
}
Modify this program to make it more interactive.
4 - 15
CS214
CHAPTER 4: OBJECTS and CLASSES
7.0 Inheritance
Sub-classing is a way to create a new class from an existing class.
A subclass inherits all methods and variables from the superclass (parent class).
A subclass does not inherit the constructor from the superclass. The only way for
a class to gain a constructor is by either writing it explicitly or using the default
constructor.
7.1 the extends keyword
To inherit a class, use the extends keyword.
Example :
public class Employee {
String name, id, jobtitle;
double salary;
}
public class Manager extends Employee {
String dept;
Employee [ ] subordinates;
}
More examples below ( in the super examples ).
4 - 16
CS214
CHAPTER 4: OBJECTS and CLASSES
7.2 the super keyword
super is used in a class to refer to the member variables of its superclass.
Superclass behaviour is invoked as if the object was part of the superclass. The
behaviour invoked does not have to be in the superclass, it can be further up in the
hierarchy.
super has 2 general forms :
a) using super to call superclass constructors
Example :
class Box {
double width;
double length;
double height;
Box( double w, double l, double h ) {
width = w;
length = l;
height = h;
}
double calArea( double w, double l ) {
return w*l;
}
double calVolume ( double w, double l, double h) {
return w*l*h;
}
void display() {
System.out.println("Width = " + width );
System.out.println("Length = " + length );
System.out.println("Height = " + height );
System.out.println("Area : width * length = " +
calArea(width, length));
System.out.println("Volume : width * length * height = " +
calVolume(width,length,height));
}
}
4 - 17
CS214
CHAPTER 4: OBJECTS and CLASSES
class JumboBoxWeight extends Box {
double weight;
JumboBoxWeight( double w, double d, double h, double m ) {
super ( w, d, h );
weight = m;
}
void display() {
super.display();
System.out.println("Weight = " + weight );
}
}
class TwoUseSuperA {
public static void main ( String args[] ) {
JumboBoxWeight jbw = new JumboBoxWeight ( 2, 3, 4, 45 );
jbw.display();
}
}
b) using super to access a member ( either a method or an instance variable )
of the superclass that has been hidden by a member of a subclass
Example :
class A {
int x;
}
class B extends A {
int x;
B ( int a, int b ) {
super.x = a; // x in A
x = b;
// x in B
}
void show() {
System.out.println("x in superclass:" + super.x );
System.out.println("x in subclass:" + x );
}
}
class TwoUseSuper {
public static void main ( String args [ ] ) {
B subObject = new B ( 1, 5 );
subObject.show();
}
}
4 - 18
CS214
CHAPTER 4: OBJECTS and CLASSES
More example :
class Human {
int hands = 2;
}
class Employee extends Human {
String name;
double salary ;
Employee ( String n, double s ) {
name = n;
salary = s;
}
String getDetails() {
return "\nName : " + name + "\nSalary : " + salary;
}
}
class Manager extends Employee {
String dept ;
Manager ( String n, double s, String d ) {
super(n,s); // calls superclass’s constructor
dept = d;
}
String getDetails() {
return super.getDetails() + "\nDept : " + dept
+ "\nHands : " + super.hands;
// can access attributes further up in the hierarchy
}
}
class SuperTestEmployee {
public static void main ( String args[] ) {
Manager m1 = new Manager("Ginger", 1000.0, "Mgt");
System.out.println(m1.getDetails());
Manager m2 = new Manager ("Swee Lim", 2000.0,"Finance");
System.out.println(m2.getDetails());
Manager m3 = new Manager ("Su Kheng", 3000.0, "Sales");
System.out.println(m3.getDetails());
}
}
Modify this program to make it more interactive.
4 - 19
CS214
CHAPTER 4: OBJECTS and CLASSES
7.3 the instanceof keyword
When you pass objects around using references to their parent classes, sometimes
you might want to know what you actually have. This is the purpose of the
instanceof operator.
You can use the instanceof operator to test the type of the object
Example : place the Employee and Manger classes in separate files
public class Employee {
String name;
double salary ;
Employee ( String n, double s ) {
name = n;
salary = s;
}
String getDetails() {
return "Name : " + name + "\nSalary : " + salary;
}
}
public class Manager extends Employee {
String dept ;
Manager ( String n, double s, String d ) {
super(n,s); // calls superclass's constructor
dept = d;
}
String getDetails() {
return super.getDetails() + "\nDept : " + dept;
}
}
4 - 20
CS214
CHAPTER 4: OBJECTS and CLASSES
class Contractor extends Employee {
int yearOfContract;
Contractor ( String n, double s, int y ) {
super(n,s); // calls superclass's constructor
yearOfContract = y;
}
String getDetails() {
return super.getDetails() + "\nYear of Contract : " + yearOfContract;
}
}
class InstanceOf {
public static void main ( String args[] ) {
Manager m = new Manager("Lim", 4000.0,"Account");
Employee e = new Employee("Tan", 5000.0 );
Contractor c = new Contractor("Tay", 400.0,2);
System.out.println("Manager");
System.out.println("=======");
giveBenefits(m);
System.out.println("Employee");
System.out.println("========");
giveBenefits(e);
System.out.println("Contractor");
System.out.println("==========");
giveBenefits(c);
}
static void giveBenefits(Employee e ) {
System.out.println(e.getDetails());
if ( e instanceof Manager )
System.out.println("Give the manager a car!");
else if ( e instanceof Contractor )
System.out.println("Give the contractor the allowance!");
else
System.out.println("Give the employee the bonus!");
}
}
You may put the class Contractor in a separate file too.
4 - 21
CS214
CHAPTER 4: OBJECTS and CLASSES
7.4 Casting objects
In circumstances where you have received a reference to a parent class, and you
have determined that the object is actually a particular subclass by using the
instanceof operator, you can restore the full functionality of an object by casting
the reference.
Example :
public void method ( Employee e ) {
if ( e instanceof Manager ) {
Manager m = ( Manager ) e;
System.out.println( “Manager of” + m.dept );
}
}
If you do not make the cast, an attempt to reference e.dept would fail because the
compiler cannot locate a member called dept in the Employee class.
Check for proper casting using the following guidelines:
a) casts up the class hierarchy are done implicitly
b) downward cast must be to a subclass and is checked by compiler
c) the reference type is checked at runtime if the compiler allows the
cast
4 - 22
CS214
CHAPTER 4: OBJECTS and CLASSES
8.0 Methods Overriding
A subclass can modify behaviour inherited from a parent class
Subclass can create a method in a subclass with a different functionality than the
parent’s method but with the same
-
name
-
return type
-
argument list
Example: refer to the examples for instanceOf and super keywords
public class Employee {
String name;
int salary;
public String printDetails () {
return name + “ is paid ” + salary;
}
}
public class Manager extends Employee {
String dept;
public String printDetails () {
return name + “is the manager of ” + dept;
}
}

There are 4 types of methods that you cannot override in a subclass :
a) private methods
b) static methods
c) final methods
d) methods within final classes
4 - 23
CS214
CHAPTER 4: OBJECTS and CLASSES
8.1 Rules about Overidden methods

Must have a return type that is identical to the method it overrides

Cannot be less accessible than the method it overrides

Cannot throw more exceptions than the method it overrides
8.2 Why overriden methods ?
Overriden methods allow Java to support run-time polymorphism. Dynamic, runtime polymorphism is one of the most powerful mechanisms that object-oriented
design brings to bear on code reuse and robustness.
The ability of existing code libraries to call methods on instances of new classes
without recompiling while maintaining a clean abstract interface is a profoundly
powerful tools.
9.0 Invoking Parent class constructors

Initialization of objects is very structured. When an object is initialized,
the following sequence of actions occur :
a) the memory space is allocated and initialized to 0 values
b) explicit initialization is performed for each class in the hierarchy
c) a constructor is called for each class in the hierarchy
In many circumstances, the default constructor is used to initialize the parent
object.
4 - 24
CS214
CHAPTER 4: OBJECTS and CLASSES
When a class hierarchy is created, in what order are the constructors for the
classes that make up the hierarchy called ?
ANS : In a class hierarchy, constructors are called in the order of
derivation, from superclass to subclass.
Example :
class A {
A()
{ System.out.println("inside Constructor A"); }
} // end of class A
class B extends A {
B()
{ System.out.println("inside Constructor B"); }
}// end of class B
class C extends B {
C()
{ System.out.println("inside Constructor C"); }
} // end of class C
class CallingConstructors {
public static void main ( String args[] ) {
C abc = new C();
}
}
Identify the output.
4 - 25
CS214
CHAPTER 4: OBJECTS and CLASSES
10. Static variables, methods and initializers
10.1 Class ( static ) variables
Sometimes it is desirable to have a variable that is shared among all instances
of a class. You can achieve this effect by marking the variable with the
keyword static. Such a variable is sometimes called a class variable to
distinguish it from a member or instance variable which is not shared.
Example :
class Count {
private int serialNum;
private static int counter = 0;
Count( ) {
counter ++;
serialNum = counter;
}
void display( ) {
System.out.println("Serial number : " + serialNum);
}
}
public class UseStatic2 {
public static void main( String args[] ) {
Count product1 = new Count();
product1.display();
Count product2 = new Count();
product2.display();
Count product3 = new Count();
product3.display();
}
}
4 - 26
CS214
CHAPTER 4: OBJECTS and CLASSES
In this example, every object that is created is assigned a unique serial
number, starting at 1 and counting upwards. The variable counter is shared
among all instances, so when the constructor of one object increments counter,
the next object to be created receives the incremented value.
A static variable is similar in some ways to a global variable in other
programming languages. The Java programming language does not have
globals as such, but a static variable is a single variable accessible from any
instance of the class.
If a static variable is not marked as private, it can be accessed from outside the
class. To do this, you do not need an instance of the class, you can refer to it
through the class name.
class StaticVariables {
static int number = 56;
}
class MyClass {
void method() {
int x = StaticVariables.number; // access number via the class's name
System.out.println( " x = " + x);
}
}
class UseStatic {
public static void main ( String args[]) {
System.out.println("number = " + StaticVariables.number);
MyClass my = new MyClass();
my.method();
}
}
4 - 27
CS214
CHAPTER 4: OBJECTS and CLASSES
10.2 Class ( static ) methods
Sometimes you need to access program code when you do not have an
instance of a particular object available. A method that is marked using the
keyword static can be used in this way and is sometimes called a class method.
A static method can be invoked without any instance of the class to which it
belongs, i.e. methods that are static can be accessed using the class name
rather than a reference.
For example :
class GeneralFunt {
static int addUp(int x, int y ) {
return x+y;
}
}
class UseGeneral {
public void method( ) {
int a = 9, b = 10;
int c = GeneralFunt.addUp(a,b);
System.out.println ("addUp( ) gives " +c);
}
}
class StaticMethods {
public static void display( ) {
System.out.println("This is a static method.");
}
public static void main(String args[] ) {
UseGeneral us = new UseGeneral();
us.method( ); // call method() to call static addUp( )
display( ); // call static display method
}
}
Because a static method can be invoked without any instance of the class to
which it belongs, there is no this value. The consequence is that a static
method cannot access any variables apart from its own arguments and static
4 - 28
CS214
CHAPTER 4: OBJECTS and CLASSES
variables. Attempting to access non-static variables will cause a compiler
error.
For example :
public class Wrong {
int x;
public static void main ( String args [ ] ) {
x = 9; // compiler error!
}
}
// non-static variables are bound to an instance and can be accessed only
through instance references.
Important points to remember about static methods :
main() is static because it has to be accessible in order for an application to be
run, before any instantiation can take place
a static method cannot be overridden to be non-static.
10.3 Static Initializers
A class can contain code in a static block that does not exist within a method
body. Static block code executes only once, when the class is loaded.
For example :
4 - 29
CS214
CHAPTER 4: OBJECTS and CLASSES
class StaticInitDemo {
static int i = 5;
static {
System.out.println("Static code i = "+ i++);
}
}
public class StaticBlock {
public static void main (String args[ ] ) {
System.out.println("Main code i = " + StaticInitDemo.i);
}
}
11. The final keyword
Sometimes you will want to prevent a class from being inherited. A final class
cannot be subclassed. To do this, precede the class definition with final
keyword. Declaring a class as final implicitly declares all of its methods as
final, too.
For example :
public final class Employee {
}
public class Manager extends Employee {
} // compilation error !!
// it is illegal for Manager to inherit Employee since Employee is
// declared as final
Sometimes you will want to prevent method overriding from occurring. To
disallow a method from being overridden, specify final as a modifier at the
start of its declaration. A final method cannot be overridden.
4 - 30
CS214
CHAPTER 4: OBJECTS and CLASSES
For example :
class FinalMethod {
final void meth ( ) {
System.out.println(“This is a final method.”);
}
}
class CannotOverride extends FinalMethod {
void meth( ) { // ERROR! Cannot override
System.out.println(“Illegal”);
}
}
A variable can be declared as final. Doing so prevents its contents from being
modified. A final variable is a constant.
For example :
final int file_open = 5;
12. Abstract classes and methods
There are situations in which you will want to define a superclass that declares
the structure of a given abstraction without providing a complete
implementation of every method.
4 - 31
CS214
CHAPTER 4: OBJECTS and CLASSES
A class which declares the existence of methods, but not the implementation is
called an abstract class.
For example :
public abstract class Drawing {
public abstract void drawDot(intx,inty) ;
public void drawLine( int x1, int y1, int x2, int y2 ) {
// draw using drawDot method
}
}
Any class that contains one or more abstract methods must also be declared
abstract. There can be no objects of an abstract class. That is, an abstract class
cannot be directly instantiated with the new operator. Such objects would be
useless because an abstract class is not fully defined. Also, you cannot declare
abstract constructors, or abstract static methods.
Any subclass of an abstract class must either implement all of the abstract
methods in its superclass, or be itself declared abstract.
An abstract class can contain non-abstract methods and variables
13. Interfaces
An interface is a variation on the idea of an abstract class. Using interface, you
can specify what a class must do, but not how it does it.
4 - 32
CS214
CHAPTER 4: OBJECTS and CLASSES
Interfaces are syntactically similar to classes, but they lack instance variables
and their methods are declared without any body. In an interface, all methods
are abstract; none can have “bodies”
One class can implement any number of interfaces. To implement an interface,
a class must create the complete set of methods defined by the interface.
By providing the interface keyword, Java allows you to fully utilize the “ one
interface, multiple methods” aspect of polymorphism.
An interface can define only static final member variables.
Example :
public interface Transparency {
public static final int OPAQUE =1;
public static final int BITMASK=2;
public static final int TRANSLUCENT=3;
public int getTransparency ( ) ;
}
// access modifier is either public or default
Once an interface has been defined, one or more classes can implement that
interface. To implement an interface, include the implements clause in a class
definition, and then create the methods defined by the interface.
If a class implements more than one interface, the interfaces are separated with
a comma.
For example :
public class MyApplet extends Applet implements MouseListener,
ActionListener {
4 - 33
CS214
CHAPTER 4: OBJECTS and CLASSES
Interfaces are useful for
1. declaring methods that one or more classes are expected to implement
2. determining an object’s programming interface without revealing the actual
body of the class
3. capturing similarities between unrelated classes without forcing a class
relationship
4. describing “function-like” objects that can be passed as parameters to
methods invoked on other objects.
interface Flyer {
public void takeOff();
public void land();
public void fly();
}
class Airplane implements Flyer {
public void takeOff() {
System.out.println("Hang on... airplane is ready to take off..");
}
public void land() {
System.out.println("Hold on... airplane is ready to land..");
}
public void fly() {
System.out.println("Relax...we are flying..");
}
}
class Bird implements Flyer {
public void takeOff( ) {
System.out.println("Wings ready... Tweety to take off..");
}
public void land() {
System.out.println("Tweety is ready to land..");
}
public void fly() {
System.out.println("Tweety is flying..");
}
}
4 - 34
CS214
CHAPTER 4: OBJECTS and CLASSES
class Flying {
public static void main ( String args[] ) {
Flying airport = new Flying();
Airplane plane = new Airplane();
Bird tweety = new Bird();
System.out.println("Let tweety lands..");
airport.getpermissionToLand(tweety);
System.out.println("Let the airplane lands..");
airport.getpermissionToLand(plane);
}
void getpermissionToLand( Flyer f ) {
f.land();
}
}
14. Access control
Variables and methods can be at one of four access levels : public, protected,
default or private. Classes can be at public or default level.
_________________________________________________________
Modifier
Same
Same
Sub
Class
Package
class
Universe
_________________________________________________________
public
Yes
Yes
Yes
protected
Yes
Yes
Yes
default
Yes
Yes
private
Yes
Yes
4 - 35
CS214
CHAPTER 4: OBJECTS and CLASSES
15. Wrapper classes
To look at primitive data elements as objects, wrapper classes can be used
Primitive Data Type
Wrapper Classes
boolean
Boolean
byte
Byte
char
Character
short
Short
int
Integer
long
Long
float
Float
double
Double
16.Programming Exercises
1. Create a class named Sweets. Its main() method holds an integer variable
named numberofSweets to which you will assign a value. Create a method to
which you pass numberofSweets. The method displays the sweets in dozens.
For example, 40 sweets is 3 dozens and 4 left over.
2. Create a class named Shirt with data fields for collar size and sleeve length.
Include a constructor that takes arguments for each field. Also include a String
class variable named material and initialize it to “cotton”. Write a program
TestShirt to instantiate 3 Shirt objects with different collar sizes and sleeve
lengths, and then display all the data, including material, for each shirt.
4 - 36
CS214
CHAPTER 4: OBJECTS and CLASSES
17.0 References

Sun MicroSystem SL-275 ( chapter 5, 6 )

Java Programming: Comprehensive, Joyce Farrell ( chapter 2, 3, 8, 9 )

The Complete Reference to Java2, Patrick Naughton & Herbert Schildt,
Osborne, McGraw-Hill ( chapter 6, 7, 8, 9 )

JDK1.2 API documentation on the above topics.
4 - 37
Download