dnes bude

26
Dnes bude... • triedy, objekty, metódy … • viditeľnosť • dedenie • polymorfizmus • ...

Upload: marah-madden

Post on 03-Jan-2016

68 views

Category:

Documents


6 download

DESCRIPTION

Dnes bude. triedy, o bjekty, met ódy …  v idite ľnosť dedenie polymorfizmus. Objekt. V šetko je objekt, Program je hŕba objektov posielajúcich si správy, Objekt zaberá pamäť, Objekt má typ, t.j. je inštanciou nejakej triedy, Triedy tvoria hierarchiu, Objekt má interface - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Dnes bude

Dnes bude...

• triedy, objekty, metódy … • viditeľnosť• dedenie• polymorfizmus• ...

Page 2: Dnes bude

Objekt• Všetko je objekt,

• Program je hŕba objektov posielajúcich si správy,

• Objekt zaberá pamäť,

• Objekt má typ, t.j. je inštanciou nejakej triedy,

• Triedy tvoria hierarchiu,

• Objekt má interface

Light lt = new Light();

lt.on();

Page 3: Dnes bude

Trieda

Page 4: Dnes bude

Deklarácia triedyclass NameOfClass { ClassBody}

• [public] trieda je voľne prístupná, inak je prístupná len v danom package

• [abstract] trieda nemôže byť inštanciovaná, neexistuje objekt danej triedy

• [final] trieda nemôže mať podtriedy, „potomkov“• [extends Super] trieda je podtriedou inej triedy,

dedičnosť• [implements Interfaces{,}*] Interfaces sú implementované

v tejto triede

Page 5: Dnes bude

Deklarácia metódy

• [static] triedna metóda, existuje nezávisle od objektov triedy • [abstract] metóda, ktorá nie je implementovaná,bude v podtriede• [final] metóda, ktorá nemôže byť predefinovaná, bezpečnosť• [native] metóda definovaná v inom jazyku, „prilinkovaná“• [synchronized] metóda synchronizujúca konkurentný prístup

bežiacich threadov, neskôr...• [throws] exceptions metóda produkujúca výnimky

Page 6: Dnes bude

Deklarácia premennej

• [static] triedna premenná, nie je viazaná na inštanciu triedy

• [final] konštanta

Page 7: Dnes bude

ViditeľnosťClass Pack Subcl World

• private Y N N N • nič Y Y N N • protected Y Y Y N • public Y Y Y Y

Page 8: Dnes bude

Prístup na úrovni triedy package One;

public class Alpha { private int iamprivate = 1; int iampackage = 2; protected int iamprotected = 3; public int iampublic = 4;

private void privateMethod() { } void packageMethod() { } protected void protectedMethod() { } public void publicMethod() { }

public static void main(String[] args) { Alpha a = new Alpha();

a.privateMethod(); a.packageMethod(); a.protectedMethod(); a.publicMethod(); int r =

a.iamprivate+ a.iampackage+a.iamprotected+ a.iampublic;

}}

Page 9: Dnes bude

Prístup na úrovni packagepackage One;

public class DeltaOne {

public static void main (String[] args) { Alpha a = new Alpha();

//a.privateMethod(); a.packageMethod(); a.protectedMethod(); a.publicMethod();

int r = // a.iamprivate +

a.iampackage +a.iamprotected +a.iampublic;

}}

Page 10: Dnes bude

Prístup z podtriedypackage two;import One.*;

public class AlphaTwo extends Alpha { public static void main(String[] args) { Alpha a = new Alpha(); //a.privateMethod(); //a.packageMethod(); //a.protectedMethod(); a.publicMethod()

int r = // a.iamprivate + // a.iampackage + // a.iamprotected + a.iampublic;

AlphaTwo a2 = new AlphaTwo(); a2.protectedMethod(); System.out.println(a2.iamprotected); }}

Page 11: Dnes bude

Prístup z okolitého svetapackage Two;

import One.*;

public class DeltaTwo { public static void main(String[] args) {

Alpha alpha = new Alpha();

//alpha.privateMethod(); //alpha.packageMethod(); //alpha.protectedMethod();

alpha.publicMethod();

int r = // a.iamprivate +// a.iampackage +// a.iamprotected +a.iampublic;

}}

Page 12: Dnes bude

Ukrytie implementácie - enkapsulácia

metóda:• public – použiteľná pre každého• private – použiteľná pre nikoho, len vo vnútri def.triedy• protected – len vo vnútri triedy a v zdedených triedach

static – nemusí existovať žiadna inštancia triedy !!!Ale !!! nestatickú metódu nemožno volať zo statického kontextu

public long MaxNumb(String S) { . . . . . } public static void main (String[] args) { System.out.println(MaxNumb("jdskoe8i22130,s-m3.2-wsll3-3344")); }non-static method MaxNumb(java.lang.String) cannot be referenced from a static

context

Page 13: Dnes bude

SumárDeklarácia triedy

[ modifikátory ] class meno triedy [extends rodič] [implements rozhrania ] { // telo triedy }

• public/private – verejná,

• abstract - nesmie byť nikdy instancovaná,

• final - nemôže mať potomkov.

Deklarácia metódy

[ práva ] [static] [abstract] [final] [native] [synchronized] Typ menoMetódy ( parametre ) [throws výnimky ]

• public/private/protected,

• static – nemusí existovať žiadna inštancia triedy,

Deklarácia premennej

[ práva ] [static] [transient] [final] [volatile] typ menoPremennej

• static - existuje len v jednom exemplári,

• final – konštanta.

Page 14: Dnes bude

Inštančné vs. triednepublic class AClass {

public int instanceInteger = 0; public int instanceMethod() { return instanceInteger; } public static int classInteger = 0; public static int classMethod() { return classInteger; }

public static void main(String[] args) { AClass anInstance = new AClass(); AClass anotherInstance = new AClass();

anInstance.instanceInteger = 1; anotherInstance.instanceInteger = 2; System.out.println(

anInstance.instanceMethod()); System.out.println( anotherInstance.instanceMethod());

//System.out.println(instanceMethod()); //System.out.println(instanceInteger);

AClass.classInteger = 7; System.out.println(classMethod()); System.out.println(anInstance.classMethod());

anInstance.classInteger = 9; System.out.println(anInstance.classMethod()); System.out.println( anotherInstance.classMethod()); }}127799

Page 15: Dnes bude

Konvencie• 80% životného cyklu software spotrebuje jeho údržba,• málokedy je software celý cyklus udržiavaný jedným programátorom, autorom...• konvencie kódovania majú uľahčiť čitateľnosť kódu iným, či aj mne po rokoch

preto: http://java.sun.com/docs/codeconv/html/CodeConvTOC.doc.html

Triedy,napr.: class Raster; class ImageSprite; Meno triedy je podstatné meno, každé podslovo začína veľkým písmenkom (mixed case), celé

meno začína veľkým písmenom. Meno je jednoduché a dobre popisujúce.

Metódy, napr.: run(); runFast(); getBackground(); Mená metód sú slovesá, začínajú malým písmenom.

Premenné, napr. int i; char c; float myWidth; Začínajú malým písmenom, mixed case, nezačínajú _ resp. $ Jednopísmenkové mená sú na

dočasné premenné.

Konštanty, napr. static final int MIN_WIDTH = 4; static final int MAX_WIDTH = 999; static final int GET_THE_CPU = 1;

Veľkými, slová oddelené ("_").

Page 16: Dnes bude

thispublic class Rectangle {

private int x, y; private int width, height;

public Rectangle() { this(0, 0, 0, 0); } public Rectangle(int width, int height) { this(0, 0, width, height); } public Rectangle( int x,

int y, int width, int height) {

this.x = x; this.y = y; this.width = width; this.height = height; } ...}

public class HSBColor { private int hue, saturation, brightness;

public HSBColor ( int hue, int saturation,

int brightness) { this.hue = hue; this.saturation = saturation; this.brightness = brightness; }}

Page 17: Dnes bude

Dedičnosť - 1• class A extends B ...• pridanie novej funkcionality, premenných a metód• predefinovanie existujúcich funkcii predka, override• vzťah is-a vs. is-like-a• dynamic binding = polymofizmus

void doStuff(Shape s) {

s.erase();

// ...

s.draw();

}

Circle c = new Circle();

Triangle t = new Triangle();

Line l = new Line();

doStuff(c);

doStuff(t);

doStuff(l);

Page 18: Dnes bude

Dedičnosť - 2class Cleanser {

private String s = new String("Cleanser");

public void append(String a) { s += a; }

public void apply() { append(" apply()"); }

public void scrub() { append(" scrub()"); }

public void print() { System.out.println(s); }

public static void main(String[] args) {

Cleanser x = new Cleanser();

x.apply();

x.scrub();

x.print();

}

}

public class Detergent extends Cleanser {

public void scrub() { // Change a method:

append(" Detergent.scrub()");

super.scrub(); // Call base-class version

}

// Add methods to the interface:

public void foam() { append(" foam()"); }

// Test the new class:

public static void main(String[] args) {

Detergent x = new Detergent();

x.apply();

x.scrub();

x.foam();

x.print();

System.out.println("Testing base class:");

Cleanser.main(args);

}

}

Page 19: Dnes bude

Dedičnosť - 3class Art {

Art() {

System.out.println("Art constructor");

}

}

class Drawing extends Art {

Drawing() {

System.out.println("Drawing constructor");

}

}

public class Cartoon extends Drawing {

Cartoon() {

System.out.println("Cartoon constructor");

}

public static void main(String[] args) {

Cartoon x = new Cartoon();

}

}

Art constructor

Drawing constructor

Cartoon constructor

class Game { Game(int i) { System.out.println("Game constructor"); }}

class BoardGame extends Game { BoardGame(int i) { super(i); System.out.println("BoardGame constructor"); }}

public class Chess extends BoardGame { Chess() { super(11); System.out.println("Chess constructor"); } public static void main(String[] args) { Chess x = new Chess(); }}

Page 20: Dnes bude

Dedičnosť - 4class Plate {

Plate(int i) {

System.out.println("Plate constructor");

}

}

class DinnerPlate extends Plate {

DinnerPlate(int i) {

super(i);

System.out.println(

"DinnerPlate constructor");

}

}

class Utensil {

Utensil(int i) {

System.out.println("Utensil constructor");

}

}

class Spoon extends Utensil {

Spoon(int i) {

super(i);

System.out.println("Spoon constructor");

}

}

class Fork extends Utensil {

Fork(int i) {

super(i);

System.out.println("Fork constructor");

}

}

class Knife extends Utensil { Knife(int i) { super(i); System.out.println("Knife constructor"); }}

// A cultural way of doing something:class Custom { Custom(int i) { System.out.println("Custom constructor"); }}public class PlaceSetting extends Custom { Spoon sp; Fork frk; Knife kn; DinnerPlate pl; PlaceSetting(int i) { super(i + 1); sp = new Spoon(i + 2); frk = new Fork(i + 3); kn = new Knife(i + 4); pl = new DinnerPlate(i + 5); System.out.println( "PlaceSetting constructor"); } public static void main(String[] args) { PlaceSetting x = new PlaceSetting(9); }}

Page 21: Dnes bude

superpublic class Superclass { public boolean aVariable;

public void aMethod() { aVariable = true; }}

public class Subclass extends Superclass { public boolean aVariable; //hides aVariable in Superclass

public void aMethod() { //overrides aMethod in Superclass aVariable = false; super.aMethod(); System.out.println(aVariable); System.out.println(super.aVariable); }}false true

Page 22: Dnes bude

super - 2class AnimationThread extends Thread {

int framesPerSecond; int numImages; Image[] images;

AnimationThread(int fps, int num) {

super("AnimationThread"); this.framesPerSecond = fps; this.numImages = num; this.images = new Image[numImages];

for (int i = 0; i <= numImages; i++) { ... // Load all the images. ... } } ...}

Page 23: Dnes bude

Metódy abstract abstract class GraphicObject { int x, y; ... void moveTo(int newX, int newY) { ... } abstract void draw();}

class Circle extends GraphicObject { void draw() { ... }}class Rectangle extends GraphicObject { void draw() { ... }}

Page 24: Dnes bude

Triedy a metódy finalneexistuje inštancia, resp. nemožno overridovať,dôvody, napr.:• bezpečnosť, ...• softwarový návrh, ...

final class ChessAlgorithm { ...}

class ChessAlgorithm { ... final void nextMove (ChessPiece pieceMoved, BoardLocation newLocation) { ... } ...}

Page 25: Dnes bude

Vnorené triedy - 1class EnclosingClass {

...

class ANestedClass {

...

}

}

class EnclosingClass {

...

static class StaticNestedClass {

...

}

class InnerClass {

...

}

}

Page 26: Dnes bude

Vnorené triedy - 2public class Stack { private Object[] items;

public Iterator iterator() { return new StackIterator(); }

class StackIterator implements Iterator { int currentItem = items.size() - 1;

public boolean hasNext() { ... } public Object next() { ... } public void remove() { ... } }}

public class Stack {

private Object[] items;

public Iterator iterator() {

return new Iterator() {

int currentItem = items.size() - 1;

public boolean hasNext() {

...

}

public Object next() {

...

}

public void remove() {

...

}

}

}

}