Lecture 4

home Contents Index Prev Next

Lecture Topic:

Classes, Methods, Members, Inheritance and Encapsulation

class_type

members

field

methods

data variable

code

Example

class Point {
public double x, y;
}
Point p1 = new Point( );
p1.x = 10; // malloc not available
P1.y = 11; // in Java code.

Example

// what is the print out of the following code
import java.awt.*;
import java.applet.Applet;
class apple {
int i = 1; // a.i = 1;
}
class inc {
static int add_one( int i ) {
i = i + 1;
return i;
}
static void add_one ( apple a ) {
a.i = a.i + 1;
}
}
public class : ref extends Applet {
public static void main ( string args [] ) {
apple a = new apple ( );
system.out.println ( a.i + "\t" + inc.add_one(a.i) + "\t" + a.i);
inc.add_one( a );
system.out.println ( a.i );
}
}
Answer:

Class & Overloaded methods

Object and Classes Object have type

Class Definition

class <class name> [extends <class name>] [implements <interface name>] {
[<variable_declaration>;]
[<method_declaration>;]
}

Example

class Lamp {
boolean on;
}
Lamp l = new Lamp ( );
l.on = true;

Overloaded methods

Default constructor takes null.

Example

class Lamp {
boolean on;
int Wattage;
Lamp ( ) { // if, Lamp ( int w ) here
Wattage = 100; // then, Wattage = w; or Lamp bulb = new Lamp ( 100 ) here
} // otherwise, Lamp bulb = new Lamp ( ) , syntax error
}
Class don't need methods!

Example

Class CS410 {
student[] sa;
int number_of_student;
final string name = "programming in Java"; // cant be changed
CS410( int i ) {
number_of_student = i;
}
}
void Print ( ) {
system.out.println(" I have" + number_of_student +" in my class.");
}
Class instance

CS410 c.i = new CS410(30);

Static variables propagate to all instances of classes.

Example

class Student{
static int student_count = 0;
void Student ( ) {
student_count++;
}
}
Static method a good for grouping utility functions.

Example

class Trig {
static float area ( float r ) {
return Math.PI * r * r;
}
float A = Trig.area(10);
Default for numeric fields not explicitly initialized to a different value is 0.

system.out class has a static method called println.

A static method cannot make reference to a non-static method.

Example

class foo {
static int inc( int i ) {
return i++;
}
int wow( int i ) { // OK
return inc( i );
}
static int wee( int i ) {
return wow( i );
}
}

Example

double negative ( ) {
return Math.SQRT ( x * x + y * y );
}
void Print ( ) {
system.out.println ( this.getclass( ).getname( ) + " = " );
system.out.println ( x + " " + y );
}



Sample Quiz

1. A static method cannot make reference to a non-static method.

True

False
2. Default constructor does not takes null in overloaded method.

True

False


home Contents Index Prev Next



UBLOGO Last Update: 9/31/96
Copyright ©1996 - Douglas Lyon
Lyon@cse.bridgeport.edu