30
Lecture 1 Object-Oriented Programming Advanced Java Programming 1 dr inż. Wojciech Bieniecki [email protected] http://wbieniec.kis.p.lodz.pl

Lecture 1 Object-Oriented Programming

Embed Size (px)

DESCRIPTION

Advanced Java Programming. Lecture 1 Object-Oriented Programming. dr inż. Wojciech Bieniecki [email protected] http://wbieniec.kis.p.lodz.pl. The concepts of OOP. Composition – a way of building your own class of other classes as the  the bricks. - PowerPoint PPT Presentation

Citation preview

Page 1: Lecture 1 Object-Oriented Programming

Lecture 1Object-Oriented Programming

Advanced Java Programming

1

dr inż. Wojciech [email protected]://wbieniec.kis.p.lodz.pl

Page 2: Lecture 1 Object-Oriented Programming

The concepts of OOPComposition – a way of building your own class of other classes as the the bricks

Inheritance – creation of a new class based on the definition of another base class. The new class "inherits" all the fields and methods, additionally you can create new ones.

Virtual function. If we create an inherited class and then define a method that was already in the base class it is a virtual function

Polymorphism. Objects created with new operator can be transformed in the run time from a base class object which gives the possibility of using the correct version of the virtual function. We can assign objects of a derived class to references from the base class,

2

Page 3: Lecture 1 Object-Oriented Programming

The concepts of OOPAbstract class – a special class created just to inherit it, like a skeleton. You cannot create object of that class.

Interface – a kind of an abstract class. It contains only declarations of methods without their implementation.

Adapter – a special class that implements all methods of the interface. These methods are mostly empty. Building a class inherit from the adapter does not need to write implementations for all methods.

Inner class – a class created inside another class. It is a variant of composition, is also used to hide the implementation.

Anonymous inner class - an object created by inheriting from the selected class. Immediately after the "new" there is a definition of this class. The scope identical as for the object.Hence the name for the new class is not needed.

3

Page 4: Lecture 1 Object-Oriented Programming

Class reuse – composition �class Pair { int a, b; Pair(int x, int y) { a = x; b - y; } void add(Pair p) { a += p.a; b += p.b; } void show() { System.out.println("("+a+" , "+b+")"); }}

class PairComp { String name; // obiekt String zawarty w obiekcie PairComp Pair p; // obiekt Pair zawarty w obiekcie PairComp PairComp(String s, int x, int y) { // konstruktor name = s; p = new Pair(x,y); // tworzenie obiektu Pair } void add(PairComp pk) { p.add(pk.p); } void show() { System.out.println(name); // wypisz nazwę pary p.show(); //i samą parę }}

PairComp pci = new PairComp("Ac", 10, 20), pc2 = new PairComp("Bc", 11, 21);pc1.show(); pc1.add(pc2);pc1.show(); 4

Page 5: Lecture 1 Object-Oriented Programming

Class reuse – inheritenceclass PairInh extends Pair { String name; PairInh(String s, int x, int y ) { super(x, y); //Jako pierwsza instr. name = s; } void show() { System.out.println(name); super.show(); } String getName() { return name; }} PairInh pi1 = new PairInh("A1", l, 2), pi2 = new PairInh("Bi", 3, 4); pi1.show();pi1.add(pi2);pi1.show();

5

Page 6: Lecture 1 Object-Oriented Programming

Inheritence

1. derived class constructor is called2. if the first statement is super (args), the base class constructor with the

arguments args is invoked,3. if there is no super (...), the default base class constructor is invoked,4. Further instructions of the constructor are carried out

The sequence of building of a derived class object

• Inheritance allows you to use an existing interface to a derived class object, the composition - no,

• Inheritance means that a derived class object can be treated just as an object of type defined by the superclass.

The main differences between composition and inheritance :

Note: Java does not support multiple inheritence

6

Page 7: Lecture 1 Object-Oriented Programming

Use of keyword super

• Calling the superclass constructor• Referring to the members of the superclass

7

Page 8: Lecture 1 Object-Oriented Programming

Usage of the polymorphismclass Animal { String name = "unknown"; Animal() {} Animal(String s) {name = s; } String getTyp() {return "Any Animal";} String getName() {return name;} String getVoice(){return "?";} void speak() { System.out.println( getTyp()+" "+getName()+" says " +getVoice()); }}

class Dog extends Animal { Dog(){} Dog(String s) { super(s); } String getTyp() { return "Dog"; } String getVoice() { return "HAU, HAU!"; }}

class Cat extends Animal { Cat() {} Cat(String s) { super(s); } String getTyp() { return "Cat"; } String getVoice() { return "Miauuuu..."; }}

8

Page 9: Lecture 1 Object-Oriented Programming

Usage of the polymorphismclass Main { public static void main(String[] arg) { Animal z1 = new Animal(), z2 = new Animal(); Dog pies = new Dog(), kuba = new Dog("Kuba"); Dog reksio = new Dog("Reksio"); Cat kot = new Cat(); Dialog(z1, z2); Dialog(kuba, reksio); Dialog(kuba, kot); Dialog(reksio, pies); } static void Dialog(Animal z1, Animal z2){ z1.speak(); z2.speak(); System.out.println("---------------"); }}

The result of the program will beAny Animal unknown says ? Any Animal unbknown says ?Dog Kuba says HAU, HAU! Dog Reksio says HAU, HAU!Dog Kuba says HAU, HAU! Cat unknown says Miauuuu...Dog Reksio says HAU, HAU! Dog unknown says HAU, HAU! 9

Page 10: Lecture 1 Object-Oriented Programming

Virtual methods

All methods in java are virtual

Dynamic binding (Late binding) – a mechanism to detect the object for which the reference points and use of the appropriate method.

Except for:

• static metods,

• final metods,

• private methods

10

Page 11: Lecture 1 Object-Oriented Programming

Abstract methods and classesThe abstract method has no implementation (body)and should be declared with the abstract specifier.

Class, in which there is any method declared abstractis an abstract class and must be accompanied by the qualifier abstract.

abstract class SomeClass { int n; abstract int getSomething(); void say() { System.out.println("Something"); }}

Abstract class means that you cannot directly,for example create its instances using "new".

11

Page 12: Lecture 1 Object-Oriented Programming

Interfaces

Implementation of interface in the class is to define in this class all the interface methods.

Interface (declared using the keyword interface) is:- a set of public abstract methods (default - no need to write abstract)- and possibly static constants (default - no need to write final static)

The interface class - it's like a poorer version of the classes deprived of fields.It is a set of methods and replaces multi-inheritence.

A class can have multiple interfaces.

Implementation of abstract methods is seen on the outside as private. Implementation should be preceded by the modifier public

12

Page 13: Lecture 1 Object-Oriented Programming

Interfacesinterface Speakable{ int QUIET = 0; int LOUD = 1; String getVoice(int voice); }

interface Moveable { void startMoving(); void stopMoving();}

class Dog extends Animal implements Speakable, Moveable{ Dog () {} Dog(String s) { super(s); } String getTyp(){ return "Dog"; } public String getVoice(int voice) { if (voice == LOUD) return "HAU... HAU... HAU... "; else return "hau... hau..."; } public void startMoving() { System.out.println("Dog " + name +"is running"); } public void stopMoving() { System.out.println("Dog " + name +"has stopped"); }} 13

Page 14: Lecture 1 Object-Oriented Programming

InterfacesDog kuba = new Dog("Kuba");kuba.startMoving();System.out.println(kuba.getVoice(Speakable.LOUD));kuba.stopMoving(); void Race(Moveable[] objects){ for (int i =0; i < objects.length; i++) objects[i].startMoving();}Race( new Moveable[] { new Dog(), new Car(), new Cat(), new Bike() } );

14

Page 15: Lecture 1 Object-Oriented Programming

Narrowing conversions1. require the use of explicit conversion operator,2. are safe: Java during the execution of the program detects an error

in the conversion to the wrong type3. The conversion can be used both for classes and the interfaces

YES!

Dog p = new Dog();

Animal z = p;

Dog p1 = (Dog) z;

NEVER!

Animal z;

Bike r = (Bike) z;

// JVM will crash, because Bike does not come from Animal.

15

Page 16: Lecture 1 Object-Oriented Programming

Narrowing conversions

void wags(){ System.out.println("wags its tail"); }

static void info(Animal z){ say(z.getTyp() +z.getName()); if (z instanceof Speakable) { Speakable zs = (Speakable) z; say(zs.getVoice(Speakable.LOUD)); } if (z instanceof Dog) ((Dog) z).wags();

void run(Moveable m) { m.startMoving(); if(m instanceof Dog) { System.out.println(" i " ); ((Dog) m).wags(); }}

Suppose the Dog class has one more method :

You can write a method using the instruction instanceof:

16

Page 17: Lecture 1 Object-Oriented Programming

Adapters

abstract class R2D2Adapter implements R2D2{ public String show(){return "";} public int calculate(int a, int b){return 0;} public float create(){return 0.0f;} public double average(){return 0.0d;}}

interface R2D2{ String show(); int calculate(int a, int b); float create(); double average();}

17

Page 18: Lecture 1 Object-Oriented Programming

Adapters

public class Robot extends R2D2Adapter{ public String show() { String s = "This text is the product of adaptation R2D2"; System.out.println(s); return s; } public static void main(String args[]) { Robot r = new Robot(); r.show(); r.calculate(); }}

18

Page 19: Lecture 1 Object-Oriented Programming

Inner classesimport java.util.*;public class Internal{ class First { private int i = 10; public int getI() { return i; } } class Second { private String text; Druga(String x) { text = x; } public String toString() { return text; } } public Second createSecond(String s) { return new Second(s); } 19

Page 20: Lecture 1 Object-Oriented Programming

Inner classes public static void main(String[] args) { Internal p = new Internal();// Both entries correct only in the outer class methods Internal.Second d1 = p.createSecond("Maria"); Second d2 = p.createSecond("Anna"); System.out.println(d1 + " " + d2); SomeClass a = new SomeClass(); System.out.println(a); }}

class SomeClass{ Internal x = new Internal(); Internal.Second d1 = x.createSecond("Tola");//Error Second d1 = x.createSecond("Betty"); public String toString(){return d1.toString();}} 20

Page 21: Lecture 1 Object-Oriented Programming

Inner classes and encapsulation

public interface InterFirst {String getText(); }public interface InterSecond { public int getInt(); }

public class Inner{ protected class FromFirst implements InterFirst { private String text; FromFirst(String x){text = x;} public String getText() { return text; } } private class FromSecond implements InterSecond { private int k = 100; public int getInt(){return k;} } public InterFirst getFirst(String s){ return new FromFirst (s);} public InterSecond getSecond(){ return new FromSecond();}}

21

Page 22: Lecture 1 Object-Oriented Programming

Inner classes and encapsulation

class Testing{ public static void main(String[] args) { Inner a = new Inner(); InterFirst x = a.getFirst("Anna"); InterSecond y = a.getSecond(); String z = x.getText(); System.out.println(z); Inner.FromFirst w = a.new FromFirst("Betty");// compilation error//Inner.FromSecond = a.new FromSecond(); }}

It is important that you can create objects being interfaces (specifically having interface class) and use the implementation of these interfaces in the inner class.

The class name that implements the interface can be unknown.So this is an effective way of hiding the implementation.It enforces programming independent of a specific type. 22

Page 23: Lecture 1 Object-Oriented Programming

Static inner classes

When the inner class is declared as static you do not need to create an external class object in order to create the

inner class object.

23

Page 24: Lecture 1 Object-Oriented Programming

Static inner classesinterface Lenght{ public String show(); }

public class SwordInfo { public static int d=70; static class Dlg implements Lenght { private int y; public Dlg(int j) { y=j; System.out.println(show()); } public String show() { return (new String("The length of the sword is "+y)); } }//end of static class Dlg public static Lenght info(int i){ return (new Dlg(i));} public static void main(String args[]) { SwordInfo.info(d); }} 24

Page 25: Lecture 1 Object-Oriented Programming

Anonymous inner classespublic interface InterSecond{ public int getInt();}public class p53anonim{ public InterSecond getSecond() { return new InterSecond() //it means inheritance { private int k = 100; public int getInt() { return k;} }; } public static void main(String[] args){ p53anonim a = new p53anonim(); InterSecond y = a.getSecond(); System.out.println(y.getInt()); }}

to build a new object you must use the new operator and a constructor (in this case - default), but to use it you need to build a class that implements

this interface and add the missing semicolon. 25

Page 26: Lecture 1 Object-Oriented Programming

Anonymous classes - constructionIf the base class contains a constructor with an argument,

the inner class derived from itmust also take it into account.

public abstract class BaseOne{ private float x; BaseOne(float k) //initializing constructor { x = k; } float getK() { return x; } abstract String getText();}

26

Page 27: Lecture 1 Object-Oriented Programming

Anonymous classes - construction

public class p56anonim{ public BaseOne getBase(float x){// Pass the arg to a constructor of a base class return new BaseOne (x) //inheritance in action { private String text = "Alice"; public String getText() { return tekst; } public float getK(){ return super.getK(); } }; } public static void main(String[] args){ p56anonim a = new p56anonim(); BaseOne y = a.getBase(4.5f); System.out.println(y.getText() + " " + y.getK()); }}

27

Page 28: Lecture 1 Object-Oriented Programming

Anonymous classes - constructionKeep in mind that the anonymous class can not have a constructor. It has no name.

Initialization can be done only during the definition.The values of the object can be initialized by passing the argument, but the argument

used to initialize the value of anonymous classes should be declared as final.

public class p57anonim{//Error //public BaseOne getBase(float x, String y) public BaseOne getBase(float x, final String y) { return new BaseOne (x) { private String text = y; public String getText() { return text; } public float getK(){ return super.getK();} }; } public static void main(String[] args) { p57anonim a = new p57anonim(); BaseOne y = a.getBase(4.5f, "Tom"); System.out.println(y.getTekst() + " " + y.getK()); }}

28

Page 29: Lecture 1 Object-Oriented Programming

Characteristics of inner classesInner class has access to all members of the surrounding class.This allows implementation of interfaces, inheritance in the inner classes and manipulation of surrounding class fields.The instance of the internal class stores a reference to the surrounding class object - the object that created it.This also applies to multiple nested classes.

You can create static inner classes.Such classes do not have properties listed in a previous section.Can create a static object inside a class without creating an outside class object.

The class C after compilation is saved in a file C.class.If the class C has an inner class called B it is also created a file C$B.class. If the class C contains some anonymous classes, files C$1.class, C$2.class C$3.class ... are created.

Internal class usually inherits from another class or implements an interface. It can perform operations on outer class members, it is a gateway to the outer class.

29

Page 30: Lecture 1 Object-Oriented Programming

Characteristics of inner classesEach inner class can independently inherit the implementation.The outer class can inherit only one. Given the fact that the inner class can work on all members of the outer class, it shows, that you can share many implementations – so it is possible to implement multiple inheritance.

They enable callbacks, i.e. allow later transfer of the information to the object (equivalent of pointers).Inner class stores the reference to the object, which brought it to life (in this way have access to all fields of the surrounding class).

Allow for the construction of fine application framework.Application framework is a class or set of classes designed to solve a selected group of problems. Use an existing application framework bases on inheriting of one or more classes overriding chosen methods, allowing us to adapt the framework to suit your needs.

A special case of the application framework is a controlling framework in which the basic element is the event handler. The Swing GUI library is an example of control framework, in which the inner class are used very intensively.

30