300 likes | 390 Views
Advanced Java Programming. Lecture 1 Object-Oriented Programming. dr inż. Wojciech Bieniecki wbieniec@kis.p.lodz.pl 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.
E N D
AdvancedJava Programming Lecture 1Object-Oriented Programming dr inż. Wojciech Bieniecki wbieniec@kis.p.lodz.pl 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 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,
The concepts of OOP Abstract 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 needtowriteimplementationsforallmethods. Inner class – a class created inside another class. It is a variantofcomposition,isalsousedtohidetheimplementation. 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.
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();
Class reuse – inheritence class 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();
Inheritence The sequence of building of a derived class object • derived class constructor is called • if the first statement is super (args), the base class constructor with the arguments args is invoked, • if there is no super (...), the default base class constructor is invoked, • Further instructions of the constructor are carried out Note: Java does not supportmultipleinheritence The main differences between composition and inheritance : • 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.
Use of keyword super • Calling the superclass constructor • Referring to the members of the superclass
Usage of the polymorphism class 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..."; } }
Usage of the polymorphism class Main { publicstaticvoid 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); } staticvoid Dialog(Animal z1, Animal z2){ z1.speak(); z2.speak(); System.out.println("---------------"); } } The result of the program will be Any 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!
Virtual methods All methodsinjavaarevirtual • Except for: • staticmetods, • finalmetods, • privatemethods Dynamic binding (Late binding) – a mechanism to detect the object for which thereferencepointsanduse of the appropriate method.
Abstract methods and classes The abstract method has no implementation (body) and should be declared with the abstract specifier.Class, in which thereisany method declared abstract is an abstract class and must be accompanied by the qualifier abstract. abstractclass SomeClass { int n; abstractint getSomething(); void say() { System.out.println("Something"); } } Abstract class means that you cannot directly, for examplecreate itsinstancesusing"new".
Interfaces The interface class - it's like a poorer version of the classes deprived of fields. Itis a set of methods and replaces multi-inheritence. A class can have multiple interfaces. 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 finalstatic) Implementation of interface in the class is to define in this class all the interface methods. Implementation of abstract methods is seen on the outside as private.Implementationshouldbeprecededbythemodifierpublic
Interfaces interface 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... "; elsereturn"hau... hau..."; } publicvoid startMoving() { System.out.println("Dog " + name +"is running"); } publicvoid stopMoving() { System.out.println("Dog " + name +"has stopped"); } }
Interfaces Dog 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(), newCar(), new Cat(), new Bike() } );
Narrowing conversions • require the use of explicit conversion operator, • are safe: Java during the execution of the program detects an error in the conversion to the wrong type • 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.
Narrowing conversions Suppose the Dog class has one more method : void wags() { System.out.println("wags its tail"); } You can write a method using the instruction instanceof: staticvoid 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(); } }
Adapters interface R2D2 { String show(); int calculate(int a, int b); float create(); double average(); } 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;} }
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(); } }
Inner classes import java.util.*; public classInternal { classFirst { private int i = 10; public int getI() { return i; } } classSecond { private String text; Druga(String x) { text = x; } public String toString() { return text; } } publicSecondcreateSecond(String s) { return newSecond(s); }
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"); //ErrorSecond d1 = x.createSecond("Betty"); public String toString(){return d1.toString();} }
Inner classes and encapsulation public interface InterFirst {String getText(); } public interface InterSecond { public int getInt(); } publicclass Inner { protectedclass FromFirst implements InterFirst { private String text; FromFirst(String x){text = x;} public String getText() { return text; } } privateclass FromSecond implements InterSecond { privateint k = 100; publicint getInt(){return k;} } public InterFirst getFirst(String s){ returnnew FromFirst (s);} public InterSecond getSecond(){ returnnew FromSecond();} }
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.
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.
Static inner classes interface 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); } }
Anonymous inner classes publicinterface InterSecond{ publicint getInt();} publicclass p53anonim{ public InterSecond getSecond() { returnnew InterSecond() //it means inheritance { privateint k = 100; publicint getInt() { return k;} }; } publicstaticvoid 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.
Anonymous classes - construction If the base class contains a constructor with an argument, the inner class derived from itmust also take it into account. publicabstractclass BaseOne { privatefloat x; BaseOne(float k) //initializing constructor { x = k; } float getK() { return x; } abstract String getText(); }
Anonymous classes - construction publicclass p56anonim { public BaseOne getBase(float x){ // Pass the arg to a constructor of a base class returnnew BaseOne (x) //inheritance in action { private String text = "Alice"; public String getText() { return tekst; } publicfloat getK(){ returnsuper.getK(); } }; } publicstaticvoid main(String[] args){ p56anonim a = new p56anonim(); BaseOne y = a.getBase(4.5f); System.out.println(y.getText() + " " + y.getK()); } }
Anonymous classes - construction Keep 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. publicclass p57anonim{ //Error //public BaseOne getBase(float x, String y) public BaseOne getBase(float x, final String y) { returnnew BaseOne (x) { private String text = y; public String getText() { return text; } publicfloat getK(){ returnsuper.getK();} }; } publicstaticvoid main(String[] args) { p57anonim a = new p57anonim(); BaseOne y = a.getBase(4.5f, "Tom"); System.out.println(y.getTekst() + " " + y.getK()); } }
Characteristics of inner classes Inner 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.classC$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.
Characteristics of inner classes Each 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.