Download - Welcome to Athens Learning Java Software Engineering Lab.

Transcript
Page 1: Welcome to Athens Learning Java Software Engineering Lab.

Welcome to Welcome to AthensAthens

Learning JavaLearning Java

Software Engineering Software Engineering Lab.Lab.

Page 2: Welcome to Athens Learning Java Software Engineering Lab.

Step 1 (α) - Introduction to JavaStep 1 (α) - Introduction to Java

Why Java?Why Java? Creating a simple Java programCreating a simple Java program Relation between Java and CRelation between Java and C

commentscomments constants, pre-processor, macros, conditional compilationconstants, pre-processor, macros, conditional compilation data typesdata types strings and objects (objects destruction)strings and objects (objects destruction) objects comparison and copyobjects comparison and copy functions and parameter passingfunctions and parameter passing pointers -the pointers -the nullnull value value arraysarrays operatorsoperators statements (if-else, for, while, switch, break, continue, finally, statements (if-else, for, while, switch, break, continue, finally,

synchronized)synchronized) Exceptions and ErrorsExceptions and Errors modifiers (final, native, synchronized, transient, volatile)modifiers (final, native, synchronized, transient, volatile)

Page 3: Welcome to Athens Learning Java Software Engineering Lab.

Why JavaWhy Java completely completely object orientedobject oriented creates code for the creates code for the Java Virtual MachineJava Virtual Machine (JVM) and (JVM) and

consequently the Java programs can run in any platformconsequently the Java programs can run in any platform has many similarities with C and C++has many similarities with C and C++ dynamicdynamic and and distributeddistributed

a Java class can be loaded and used dynamically in run timea Java class can be loaded and used dynamically in run time Java code, spread in Internet, can be used dynamically (Java Java code, spread in Internet, can be used dynamically (Java

Applets)Applets) simplesimple and and easyeasy to use to use safesafe, , reliablereliable and and securesecure

has no pointers (known problems and bugs of C/C++ programs do has no pointers (known problems and bugs of C/C++ programs do not exist)not exist)

automatic mechanism of memory automatic mechanism of memory management - garbage management - garbage collectioncollection

very powerful mechanism of exceptionsvery powerful mechanism of exceptions provides very strict safety rules on the network levelprovides very strict safety rules on the network level

multithreadedmultithreaded - simplifies the procedure of threads creation - simplifies the procedure of threads creation and concurrencyand concurrency

Page 4: Welcome to Athens Learning Java Software Engineering Lab.

Creating a simple program in JavaCreating a simple program in Javapackage simple;

public class HelloWorld{

public void printMessage(){System.out.println(“Hello World”);

}

public static void main(String[] args){HelloWorld hello = new HelloWorld();hello.printMessage();

}}

Step 1: Select a directory in which you want to write your java programs and add it to the CLASSPATH (ex. setenv CLASSPATH $CLASSPATH:$HOME/java)Step 2: Make a subdirectory simple and write your program named HelloWorld.javaStep 3: Compile your program: javac HelloWorld.javaStep 4: Run the program from any directory: java simple.HelloWorld

Page 5: Welcome to Athens Learning Java Software Engineering Lab.

How Java worksHow Java works

Page 6: Welcome to Athens Learning Java Software Engineering Lab.

Comments - Constants - some Comments - Constants - some differences with Cdifferences with C /*/* C - like comments- not nested C - like comments- not nested */*/ //// C++ - like comments C++ - like comments /**/** Special comments for documentation production by means of the Special comments for documentation production by means of the

javadocjavadoc tool - in html format - not nested tool - in html format - not nested*/*/ constants are defined as constants are defined as static final static final (ex. (ex. public static final double PI = public static final double PI =

3.14159;3.14159;)) macrosmacros do not exist - a good Java compiler should automatically be do not exist - a good Java compiler should automatically be

able to inline short methods where appropriateable to inline short methods where appropriate When the compiler understands that parts of code are never executed, When the compiler understands that parts of code are never executed,

it does not compile them. Conditional compilation is achieved by using it does not compile them. Conditional compilation is achieved by using the condition the condition if (if(DEBUG){} if (if(DEBUG){} where DEBUG is a boolean constantwhere DEBUG is a boolean constant))

There is not any There is not any #include #include instructioninstruction. . Java does not make any Java does not make any discrimination between declaration and definition of variables and discrimination between declaration and definition of variables and methods (header files do not exist).methods (header files do not exist).

Java provides a new declaration:Java provides a new declaration: import classes; import classes; import java.util.Vector;import java.util.Vector; import java.io.*;import java.io.*;

Page 7: Welcome to Athens Learning Java Software Engineering Lab.

Primitive data typesPrimitive data typesT y p e C o n t a i n s D e f a u l t S i z e

b o o l e a n t r u e / f a l s e f a l s e 1 b i t

c h a r U n i c o d e c h a r a c t e r \ u 0 0 0 0 1 6 b i t s

b y t e s i g n e d i n t e g e r 0 8 b i t s

s h o r t s i g n e d i n t e g e r 0 1 6 b i t s

i n t s i g n e d i n t e g e r 0 3 2 b i t s

l o n g s i g n e d i n t e g e r 0 6 4 b i t s

f l o a t I E E E 7 5 4f l o a t i n g - p o i n t

0 . 0 3 2 b i t s

d o u b l e I E E E 7 5 4f l o a t i n g - p o i n t

0 . 0 6 4 b i t s

• Conversion between boolean and integer values is not allowed• There isn’t any keyword unsigned or declarations like long int, short int e.t.c.• A long constant can be distinguished by appending the characters L or l.• Similarly, for float and double constants we use the characters f or F and d or D.• Floating point arithmetic never causes exceptions, even in case of division by zero.• On the contrary, integer division by 0 (or modulo 0) causes an ArithmeticException

Page 8: Welcome to Athens Learning Java Software Engineering Lab.

Strings and objectsStrings and objects Strings are not primitive data types but instances of the class Strings are not primitive data types but instances of the class StringString String constants are displayed as in C: “This is a string constant” - String constants are displayed as in C: “This is a string constant” -

When they are detected from the compiler, they are transformed to When they are detected from the compiler, they are transformed to String objects.String objects.

Creating objectsCreating objects java.awt.Button b = new java.awt.Button();java.awt.Button b = new java.awt.Button(); String s = “This is an example”; (identical to: String s = new String(“This String s = “This is an example”; (identical to: String s = new String(“This

is an example”);)is an example”);) Accessing objectsAccessing objects

String s;String s;s = “My name is Fanis”;s = “My name is Fanis”;if (s.substring(11).equals(“Fanis”)) System.out,println(“His name is if (s.substring(11).equals(“Fanis”)) System.out,println(“His name is Fanis”);Fanis”);if(String.valueOf(i + 5).equals(“1000”)) System.out.println(“OK”);if(String.valueOf(i + 5).equals(“1000”)) System.out.println(“OK”);

Objects destructionObjects destruction We don’ t care about freeing memory or destroying objectsWe don’ t care about freeing memory or destroying objects When it’s detected that an object is not used anymore, it is destroyed When it’s detected that an object is not used anymore, it is destroyed

(garbage collection)(garbage collection)

Page 9: Welcome to Athens Learning Java Software Engineering Lab.

Comparing and copying ObjectsComparing and copying Objects

Objects are accessed by referenceObjects are accessed by reference TextField ok = new TextField(“Everything is OK”); //A new object is createdTextField ok = new TextField(“Everything is OK”); //A new object is created

TextField no = new TextField(‘’Nothing is OK’’); //A new object is created TextField no = new TextField(‘’Nothing is OK’’); //A new object is created no = ok; // The variables no, ok refer to the same objectno = ok; // The variables no, ok refer to the same object

// The object to which ‘no’ refered is not used anymore // The object to which ‘no’ refered is not used anymore // and it will be freed by the garbage collector // and it will be freed by the garbage collector

no.setText(‘’I don’t know what really happens‘’);no.setText(‘’I don’t know what really happens‘’);System.out.println(ok.getText()); // Prints: I don’t know what really happensSystem.out.println(ok.getText()); // Prints: I don’t know what really happens

String s1 = “Hello”;String s1 = “Hello”;String s2 = “Hello”;String s2 = “Hello”;if(s1==s2) System.out.println(“They are the same object”); //Not printedif(s1==s2) System.out.println(“They are the same object”); //Not printedif(s1.equals(s2) System.out.println(“They have the same values”); // It is if(s1.equals(s2) System.out.println(“They have the same values”); // It is printedprinted

The classes that implement the interfaceThe classes that implement the interface Cloneable Cloneable can be copied by can be copied by using the method using the method clone(): clone():

Vector c, b = new Vector();Vector c, b = new Vector();c = b.clone(); // variable c refers to a clone of b (exactly similar but c = b.clone(); // variable c refers to a clone of b (exactly similar but

// a different object)// a different object)

Page 10: Welcome to Athens Learning Java Software Engineering Lab.

Functions, parameter passing and Functions, parameter passing and pointerspointers

Methods can return values of the primitive data types, arrays or Methods can return values of the primitive data types, arrays or objects. When they don’t return anything, the keyword objects. When they don’t return anything, the keyword void void must must be used.be used.

The primitive data types always pass as parameters in methods by The primitive data types always pass as parameters in methods by value, in contrast to arrays and objects.value, in contrast to arrays and objects.

For every primitive data type there is a corresponding class.For every primitive data type there is a corresponding class. Integer -> int, Float -> float, Char -> char e.t.c.Integer -> int, Float -> float, Char -> char e.t.c. These classes can be used in case we want to pass integer e.t.c values These classes can be used in case we want to pass integer e.t.c values

by reference in a method.by reference in a method. Since objects access is made by reference, the existence of Since objects access is made by reference, the existence of

pointers is useless. THERE ARE NOT POINTERS IN JAVApointers is useless. THERE ARE NOT POINTERS IN JAVA The The nullnull value is the default value for the variables of all the value is the default value for the variables of all the

reference types.reference types. It shows that a variable does not refer to any It shows that a variable does not refer to any object or array.object or array. String s; // It’s nullString s; // It’s null

s = “Hello”; // It’s not nulls = “Hello”; // It’s not nulls = null; // It’s null agains = null; // It’s null again

Page 11: Welcome to Athens Learning Java Software Engineering Lab.

ArraysArrays They can be considered as objectsThey can be considered as objects Arrays creationArrays creation

byte octet_buffer[] = new buffer[1024];byte octet_buffer[] = new buffer[1024]; byte[] octet_buffer = new buffer[1024];byte[] octet_buffer = new buffer[1024]; int values[] = {1, 2, 5, 7};int values[] = {1, 2, 5, 7}; Menu m = createMenu(“File”, new String[] {“Open”, “Save”, “Quit”});Menu m = createMenu(“File”, new String[] {“Open”, “Save”, “Quit”});

Arrays destruction is made automatically, just as with objectsArrays destruction is made automatically, just as with objects The values of an array are initialised with their default values. (e.g. 0 for int, null The values of an array are initialised with their default values. (e.g. 0 for int, null

for objects)for objects) Multidimensional arraysMultidimensional arrays

byte twoDimArray[][] = new byte[256][16];byte twoDimArray[][] = new byte[256][16]; We don’ t need to determine all the dimensionsWe don’ t need to determine all the dimensions

e.g. ie.g. int threeD[][][] = new int[10][][];nt threeD[][][] = new int[10][][];An array of 10 items of the type int[][] is createdAn array of 10 items of the type int[][] is createdErrorError: : double data[][][] = new double[20][][10];double data[][][] = new double[20][][10];

int[][] twoDim = {{1,2}, {3, 4, 5}, {6, 7, 8, 9}};int[][] twoDim = {{1,2}, {3, 4, 5}, {6, 7, 8, 9}}; Arrays accessArrays access

int c[] = new int[10];int c[] = new int[10];for(int i = 0; i< c.length; ++i) c[i] = i;for(int i = 0; i< c.length; ++i) c[i] = i;

Page 12: Welcome to Athens Learning Java Software Engineering Lab.

OperatorsOperators

All the C operators, except for those which are connected to All the C operators, except for those which are connected to the use of pointers (*, ->, &, sizeof)the use of pointers (*, ->, &, sizeof)

Java does not consider ‘.’ (access of fields) and ‘[]’ (access in Java does not consider ‘.’ (access of fields) and ‘[]’ (access in arrays) as operatorsarrays) as operators

The operator + (+=) is used for String values too.The operator + (+=) is used for String values too. Introduction of the new operator Introduction of the new operator instanceofinstanceof to check if an to check if an

object is an instance of a class (or subclass) or it implements object is an instance of a class (or subclass) or it implements an interface.an interface.

e.g.e.g.String s;String s;if(s instanceof String) system.out.println(“This object is a String”);if(s instanceof String) system.out.println(“This object is a String”);

The operators >> and >>> shift the bits of a value to the The operators >> and >>> shift the bits of a value to the right with sign and zero extension respectively.right with sign and zero extension respectively.

Operator overloading is not supported by Java.Operator overloading is not supported by Java.

Page 13: Welcome to Athens Learning Java Software Engineering Lab.

StatementsStatements if/else, while, do/whileif/else, while, do/while,, switch, for switch, for as in C. as in C. introduction of the statements introduction of the statements try/catch/finallytry/catch/finally

try{try{ if(i == 0) return 0; if(i == 0) return 0;}}finally {j = i} // always executedfinally {j = i} // always executedreturn 1;return 1;

The code inThe code in finally finally is executed before the program control is moved to any other point is executed before the program control is moved to any other point (even in case of the presence of the statements (even in case of the presence of the statements return, continue, break return, continue, break oror an exception an exception raising).raising).

use of labels for the statements use of labels for the statements break, continuebreak, continue test: if(check(i)){test: if(check(i)){

for(int j = 0; j<10; ++j){ for(int j = 0; j<10; ++j){ if(j>i) break; if(j>i) break; if(a[i][j] == null) break test; if(a[i][j] == null) break test; } }}}

the statement: the statement: synchronized (expression) statement synchronized (expression) statement is used to declare that is used to declare that statement statement is a critical section and it can not be executed concurrently by more is a critical section and it can not be executed concurrently by more than one threads. The than one threads. The expressionexpression must be reduced to an object or an array. By must be reduced to an object or an array. By means of the statement means of the statement synchronized, synchronized, the thread acquires a unique key for the the thread acquires a unique key for the object (array) of the expression.object (array) of the expression.

Page 14: Welcome to Athens Learning Java Software Engineering Lab.

Exceptions and ErrorsExceptions and Errors Exceptions Exceptions (Exception class) (Exception class) and Errors and Errors (Error(Error class class) ) are subclasses of the class are subclasses of the class ThrowableThrowable Subclasses of Subclasses of ErrorError represent problems related to dynamic loading, memory e.t.c. They must represent problems related to dynamic loading, memory e.t.c. They must

be considered as unrecoverable errors and therefore they must not be caught.be considered as unrecoverable errors and therefore they must not be caught. Subclasses of Subclasses of Exception Exception are considered as errors that can be handled.are considered as errors that can be handled. Any exception Any exception that that is not a subclass of is not a subclass of RuntimeExceptionRuntimeException must be caught. must be caught. Exception handlingException handling

try{try{ // code that can raise an exception // code that can raise an exception}}catch(SomeException e1){catch(SomeException e1){ // Handling of the exception e1 (instance of SomeException or its subclass) // Handling of the exception e1 (instance of SomeException or its subclass)}}catch (AnotherException e2){catch (AnotherException e2){ // e2 the same as before // e2 the same as before}}finally{ // Optionalfinally{ // Optional //Code always executed at the end //Code always executed at the end }}

Page 15: Welcome to Athens Learning Java Software Engineering Lab.

More on exceptionsMore on exceptions In the body of a method, if there is any possibility of an exception raising, we In the body of a method, if there is any possibility of an exception raising, we

must either catch the exception or declare that the above method may throw must either catch the exception or declare that the above method may throw exception.exception.

π.χ.π.χ.public void openFile() throws IOException, MyException{public void openFile() throws IOException, MyException{ //statements which might throw exceptions, instances of java.io.Exception and //statements which might throw exceptions, instances of java.io.Exception and

//MyException or subclasses of them //MyException or subclasses of them}}

Generating an exceptionGenerating an exception throw new MyException(“My exceptional condition occurred”);throw new MyException(“My exceptional condition occurred”); throw e; // e is a caugth exceptionthrow e; // e is a caugth exception when an exception is thrown, the program flow is stopped and the interpreter tries when an exception is thrown, the program flow is stopped and the interpreter tries

to find a to find a catchcatch statement which could handle it. statement which could handle it. I make my own exceptions by subclassing subclasses of I make my own exceptions by subclassing subclasses of ExceptionException I can find the message of an exception by calling the method I can find the message of an exception by calling the method getMessage()getMessage() of of

the superclass the superclass Throwable.Throwable. e.ge.g. System.out.println(e.getMessage()); // e: a . System.out.println(e.getMessage()); // e: a caughtcaught exception exception

We can print a stack trace for an exception on the error output streamWe can print a stack trace for an exception on the error output stream (methods printStackTrace()).(methods printStackTrace()).

Page 16: Welcome to Athens Learning Java Software Engineering Lab.

ModifiersModifiers finalfinal

variablesvariables: their value can not be changed: their value can not be changed methods: methods: they can not be overridenthey can not be overriden classes: classes: they can not be inheritedthey can not be inherited

native : native : declares that a method is implemented in C or in an other declares that a method is implemented in C or in an other platform-dependent language.platform-dependent language.

synchronizedsynchronized static methods:static methods: Before the invocation of a method, Java obtains a Before the invocation of a method, Java obtains a

key in the class so that no more threads can transform this class at key in the class so that no more threads can transform this class at the same time.the same time.

non static methods: non static methods: In this case it’ s a class instance (the object In this case it’ s a class instance (the object that invoked the method) in which the key is obtained.that invoked the method) in which the key is obtained.

transient : transient : refers to object Serialization and applies to non static fields of refers to object Serialization and applies to non static fields of a class in order to declare that they do not get serializable with the objecta class in order to declare that they do not get serializable with the object

volatile : volatile : declares that the field is used by synchronised threads and declares that the field is used by synchronised threads and therefore compiler must not try any optimisation with it.therefore compiler must not try any optimisation with it.

Page 17: Welcome to Athens Learning Java Software Engineering Lab.

Step 2 (β) - Classes and ObjectsStep 2 (β) - Classes and Objects

constructorsconstructors method overloadingmethod overloading thisthis static methods and variablesstatic methods and variables static initialisersstatic initialisers garbage collection - object finalizationgarbage collection - object finalization inheritanceinheritance

subclassing - final classessubclassing - final classes class hierarchy in java - the superclass Objectclass hierarchy in java - the superclass Object constructor use - the word constructor use - the word supersuper shadowed variablesshadowed variables method overriding - final methodsmethod overriding - final methods variable and method scope (public, protected, package, private)variable and method scope (public, protected, package, private) abstract classesabstract classes interfaces and inheritanceinterfaces and inheritance

Page 18: Welcome to Athens Learning Java Software Engineering Lab.

Constructors and method Constructors and method overloadingoverloading

Constructors are public methods with the name of the classConstructors are public methods with the name of the class They are the only methods that they do not return any value and they are not They are the only methods that they do not return any value and they are not

declared declared voidvoid the object the object this this is automatically returnedis automatically returned

ExampleExamplepublic class Circle{public class Circle{ public double x, y, r; public double x, y, r;

public Circle(double x, double y, double r){ public Circle(double x, double y, double r){ this.x = x; this.y = y; this.r = r; this.x = x; this.y = y; this.r = r; } } public Circle(Circle c){ x = c.x; y = c.y; r = r; } public Circle(Circle c){ x = c.x; y = c.y; r = r; } public Circle(){ this(0.0, 0.0, 1.0); } // invokes the first constructor public Circle(){ this(0.0, 0.0, 1.0); } // invokes the first constructor}}

A A Circle Circle object can be created by using any constructorobject can be created by using any constructor Circle c = new Circle(3.2, 5.3, 1.0);Circle c = new Circle(3.2, 5.3, 1.0); Circle c = new Circle();Circle c = new Circle(); Circle c = new Circle(b); // b is an existing CircleCircle c = new Circle(b); // b is an existing Circle Circle c = new Circle(new Circle(0.0, 0.0, 1.5)); Circle c = new Circle(new Circle(0.0, 0.0, 1.5));

Method overloading is allowed like in C++ - Definition of many methods Method overloading is allowed like in C++ - Definition of many methods having the same name but different number of argumentshaving the same name but different number of arguments

Page 19: Welcome to Athens Learning Java Software Engineering Lab.

Static variables and methodsStatic variables and methods They are declared as They are declared as staticstatic

e.g.e.g.public static final int MAX = 1000;public static final int MAX = 1000;puclic static Circle bigger(Circle a, Circle b){ return (a.r>b.r ? a:b); }puclic static Circle bigger(Circle a, Circle b){ return (a.r>b.r ? a:b); }

They don’t refer to a class instance but to all the classThey don’t refer to a class instance but to all the class A static method can use only static members of the class (it can not A static method can use only static members of the class (it can not

use use thisthis)) They are called with the name of the class to which they belongThey are called with the name of the class to which they belong

π.χ.π.χ.Circle c = Circle.bigger(new Circle(), new Circle(0.0, 0.0, 2.0));Circle c = Circle.bigger(new Circle(), new Circle(0.0, 0.0, 2.0));System.out.println(“Hello World”);System.out.println(“Hello World”);

static initializersstatic initializers public class Test{public class Test{

static private int array[] = new int[100]; static private int array[] = new int[100]; static{ static{ for(int i = 0; i<100; ++ i) array[i] = -1; for(int i = 0; i<100; ++ i) array[i] = -1; } }}}

They are invoked when the class is loaded for the first timeThey are invoked when the class is loaded for the first time

Page 20: Welcome to Athens Learning Java Software Engineering Lab.

Object destructionObject destruction

There are not object destructors like in C++, because Java There are not object destructors like in C++, because Java takes care of their destruction when they are not used any takes care of their destruction when they are not used any more.more.

Java provides Java provides finalizers finalizers which are rarely usedwhich are rarely used The garbage collector can not free some resources like The garbage collector can not free some resources like sockets sockets or or

file descriptors.file descriptors. In this case we have to define a method named In this case we have to define a method named finalize() finalize() that will accomplish this task.that will accomplish this task.

e.g.e.g.protectedprotected void finalize() throws IOException{void finalize() throws IOException{ if(fd != null) close(); if(fd != null) close(); }}

No argument, no return valueNo argument, no return value the finalizer is called before the garbage collector frees the objectthe finalizer is called before the garbage collector frees the object Java interpreter can terminate before that, so the resources can be Java interpreter can terminate before that, so the resources can be

released by the operating systemreleased by the operating system If an exception thrown in the finalizer’s body is not caught, the If an exception thrown in the finalizer’s body is not caught, the

system ignores it.system ignores it.

Page 21: Welcome to Athens Learning Java Software Engineering Lab.

InheritanceInheritance

A class can inherit only one classA class can inherit only one class public class FixedCircle extends Circle{public class FixedCircle extends Circle{

public FixedCircle(double r){ public FixedCircle(double r){ x = 0.0; y = 0.0; this.r = r; x = 0.0; y = 0.0; this.r = r; } }}}

A class is declared A class is declared finalfinal so that it can’t be subclassed. so that it can’t be subclassed. When a class does not determines that extends an other class, it really When a class does not determines that extends an other class, it really

extends the extends the java.lang.Object java.lang.Object classclass.. ObjectObject is the superclass of all the Java classes and therefore all its methods can be is the superclass of all the Java classes and therefore all its methods can be

invoked by any class.invoked by any class. invoking a constructor of the superclassinvoking a constructor of the superclass

super(argument1, argument2, ... );super(argument1, argument2, ... ); It must be the first statement in the constructorIt must be the first statement in the constructor when omitted, the constructor calls when omitted, the constructor calls super().super(). If there is not a corresponding If there is not a corresponding

constructor a compilation error is causedconstructor a compilation error is caused When the constructor of a class calls an other constructor of this class by using When the constructor of a class calls an other constructor of this class by using thisthis, then it’s , then it’s

the second constructor that is called by the constructors of the subclasses when the second constructor that is called by the constructors of the subclasses when super() super() is is omitted.omitted.

When a class does not define any constructor, Java defines an empty constructor, When a class does not define any constructor, Java defines an empty constructor, without any argument, which simply calls without any argument, which simply calls supper().supper().

Page 22: Welcome to Athens Learning Java Software Engineering Lab.

Shadowed variables - method Shadowed variables - method overridingoverriding

public class B extends A{public class B extends A{ int r; // variable r already exists in A int r; // variable r already exists in A public int get_r_ofB(){ return r; } // or return this.r public int get_r_ofB(){ return r; } // or return this.r public int get_r_ofA(){ return super.r; } // or return ((A) this).r public int get_r_ofA(){ return super.r; } // or return ((A) this).r}}

If a class C extends B and defines a new variable r, the calls:If a class C extends B and defines a new variable r, the calls: r, this.r : refer to Cr, this.r : refer to C super.r, ((B) this).r : refer to Βsuper.r, ((B) this).r : refer to Β ((Α) this).r : refers to Α - call super.super.r is fault((Α) this).r : refers to Α - call super.super.r is fault

class A {class A { int i =1; int i =1; int f() { return i; } int f() { return i; }}}class B extends A{class B extends A{ int i = 2; int i = 2; int f() { return -i;} int f() { return -i;} void g() { System.out.println(super.f()); } //prints 1 (Α.f()) void g() { System.out.println(super.f()); } //prints 1 (Α.f()) }}.... B b = new B(); System.out.println(b.f()); // prints -1 (Β.f()).... B b = new B(); System.out.println(b.f()); // prints -1 (Β.f()) A a = (A) b; System.out.println(a.f()); // prints -1 (Β.f()) Why? A a = (A) b; System.out.println(a.f()); // prints -1 (Β.f()) Why?

Page 23: Welcome to Athens Learning Java Software Engineering Lab.

Class, variable and method scopeClass, variable and method scope

S c o p e p u b l i c p r o t e c t e d p a c k a g e p r i v a t e

S a m e c l a s s Y e s Y e s Y e s Y e s

S a m e p a c k a g e Y e s Y e s Y e s N o

S u b c l a s s i nd i f f e r e n tp a c k a g e

Y e s Y e s N o N o

D i f e r r e n tp a c k a g e

Y e s N o N o N o

If there is not any characterization (public, protected και private) for a field or class,the third case is implied (package).

Page 24: Welcome to Athens Learning Java Software Engineering Lab.

Abstract classesAbstract classes

A class can declare a method without implementing it. This A class can declare a method without implementing it. This method and all the class must be declared as method and all the class must be declared as abstract. abstract.

public abstract class Shape{public abstract class Shape{ public abstarct double area(); public abstarct double area(); public abstarct double circumference(); public abstarct double circumference();}}

Page 25: Welcome to Athens Learning Java Software Engineering Lab.

InterfacesInterfaces

InterfacesInterfaces are abstract classes, whose methods are all abstract. are abstract classes, whose methods are all abstract. They are declared as They are declared as interfaceinterface and their methods may not declared and their methods may not declared

as as absabsttrract act (It is implied)(It is implied).. public interface Drawable {public interface Drawable {

public void setColor(Color c); public void setColor(Color c); public void setPosition(double x, double y); public void setPosition(double x, double y); public void draw(DrawWindow dw); public void draw(DrawWindow dw);}}

All the variables declared in an interface must be All the variables declared in an interface must be staticstatic and and final final (constants).(constants).

A class can implement A class can implement more than onemore than one interfaces. interfaces. public class Circle extends Shape, implements Drawable, Serializable public class Circle extends Shape, implements Drawable, Serializable

{… }{… } The class must implement all the methods of the interfaces it implements The class must implement all the methods of the interfaces it implements

and it inherits their constants.and it inherits their constants. An interface can extend an other, just like an ordinary class.An interface can extend an other, just like an ordinary class.