Preklapanje (overriding) metoda u Javi

Ako podklasa (klasa-dete) ima isti metod kakav je deklarisan u roditeljskoj klasi, to je poznato kao preklapanje (overriding) metoda u javi.
Drugim rečima, ako podklasa obezbeđuje specifičnu implementaciju metode koju je obezbedila jedna od roditeljskih klasa, to je poznato kao preklapanje metoda.
Upotreba preklapanja metoda:

  • Preklapanje metoda se koristi da obezbedi specifičnu implementaciju metode koja je već obezbeđena preko svoje superklase.
  • Preklapanje metoda se koristi za polimorfizam u vremenu izvršavanja.

Pravila za preklapanje metoda

  1. metoda mora imati isto ime kao u roditeljskoj klasi.
  2. metoda mora imati isti parametar kao u roditeljskoj klasi.
  3. mora biti IS-A relacija (nasleđivanje).

Bez preklapanja metoda

Problem koji se javlja bez preklapanja metoda Razmotrimo problem koji se javlja u programu ako ne koristimo preklapanje metode.

1
2
3
4
5
6
7
8
9
10
11
12
13
class Vehicle{
  void run(){System.out.println("Vehicle is running");}
}
class Bike extends Vehicle{
  
  public static void main(String args[]){
  Bike obj = new Bike();
  obj.run();
  }
}
Ispis na ekranu:
Vehicle is running

Problem je u tome da moramo obezbediti specifičnu implementaciju metode run() u podklasi, te stoga koristimo preklapanje metoda.

Preklapanje metoda

Primer 1 preklapanja metoda U ovom primeru, definisaćemo metodu run u podklasi onako kako je definisana u roditeljskoj klasi ali će imati neku specifičnu implementaciju. Ime i parametar metode su isti i postoji IS-A relacija između klasa, tako da postoji preklapanje metoda.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Vehicle{ 
void run(){System.out.println("Vehicle is running");} 

class Bike2 extends Vehicle{ 
  void run(){System.out.println("Bike is running safely");} 
  public static void main(String args[]){ 
  Bike2 obj = new Bike2(); 
  obj.run(); 
  }
}
Ispis na ekranu:
Bike is running safely

Primer 2 preklapanja metoda Razmotrimo sledeći scenario: Bank je klasa koja obezbeđuje funkcionalnost izračunavanja kamatne stope. Ali, kamatna stopa varira u zavisnosti od banke. Na primer, banke FIRST, SECOND i THIRD mogu obezbediti 8%, 7% i 9% kamatne stope. 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Bank{ 
  int getRateOfInterest(){return 0;} 

  
class FIRST extends Bank{ 
  int getRateOfInterest(){return 8;} 

  
class SECOND extends Bank{ 
  int getRateOfInterest(){return 7;} 

class THIRD extends Bank{ 
  int getRateOfInterest(){return 9;} 

  
class Test2{
  public static void main(String args[]){ 
    FIRST s=new FIRST(); 
    SECOND i=new SECOND(); 
    THIRD a=new THIRD(); 
    System.out.println("FIRST Rate of Interest: "+s.getRateOfInterest()); 
    System.out.println("SECOND Rate of Interest: "+i.getRateOfInterest()); 
    System.out.println("THIRD Rate of Interest: "+a.getRateOfInterest()); 
  
}
Ispis na ekranu:
FIRST Rate of Interest: 8
SECOND Rate of Interest: 7
THIRD Rate of Interest: 9

Može li se preklopiti statička metoda? Ne, statička metoda se ne može preklopiti. O ovome će biti reči kasnije, u delu koji se odnosi na polimorfizam u vremenu izvršavanja. Zašto se statička metoda ne može preklopiti? Zato što je statička metoda vezana za klasu, dok je instancna metoda vezana za objekat. Može li se preklopiti java main metoda? Ne, zato što je main statička metoda. Razlika između preopterećenja metode i preklapanja metode u Javi Postoje tri osnovne razlike između preopterećenja metode i preklapanja metode. To su:

Preopterećenje metode Preklapanje metode
Preopterećenje metode se koristi da poboljša čitljivost programa Preklapanje metode se koristi da obezbijedi specifičnu implementaciju metode koju je već obezbedila njena superklasa
Preopterećenje metode se izvodi unutar klase Preklapanje metode se javlja u dve klase koje imaju IS-A relaciju
U slučaju preopterećenja metode parametar mora biti različit U slučaju preklapanja metode parametar mora biti isti

Kolekcije u Javi

Pre Java 2, Java je obezbedila ad hoc klase kakve su Dictionary, Vector, Stack i Properties za čuvanje i manipulaciju grupama objekata.

Iako su ove klase bile prilično korisne, nedostajala im je neka centralna, jedinstvena tema. Stoga, način na koji smo koristili Vector se razlikovao od načina na koji smo koristili Properties.

Framework (radni okvir) kolekcija je dizajniran da zadovolji nekoliko ciljeva, kao što su −

  • Framework (radni okvir) mora imati visoki učinak. Implementacije za fundamentalne kolekcije (dynamic arrays, linked lists, trees, and hashtables) moraju biti visoko efikasne.
  • Framework mora omogućiti raličitim vrstama kolekcija da rade na sličan način i sa visokim stepenom međusobne operabilnosti.
  • Framework mora lako proširiti i/ili prilagoditi kolekciju.

U cilju zadovoljenja postavljenih ciljeva, čitav framework kolekcija je dizajniran oko skupa standardnih interfejsa. Ovi interfejsi obezbeđuju nekoliko standardnih implementacija, kao što su LinkedList, HashSet i TreeSet. Mogu se koristiti u datom obliku, ili se može implementirati sopstvena kolekcija.

Framework kolekcija jeste jedinstvena arhitektura za prikazivanje i manipulaciju kolekcijama. Svi frameworksi kolekcija sadrže sledeće −

  • Interfejse − Ovo su apstraktni tipovi podataka koji predstavljaju kolekcije. Interfejsi omogućavaju da se kolekcijama rukuje  nezavisno od detalja reprezentacije tih kolekcija. U objektno orijentisanim jezicima, interfejsi generalno formiraju hijerarhiju.
  • Implementacije, npr Klase − Ovo su konkretne implementacije interfejsa kolekcija. Suštinski gledano, ovo su ponovno upotrebljive strukture podataka.
  • Algoritme − Ovo su metode koje vrše korisna računanja, kakva su pretrage i sortiranja, na objektima koji implementiraju interfejse kolekcija. Za ove algoritme se kaže da su polimorfni: to znači da ista metoda može biti korišćena na mnogo različitih implementacija odgovarajućeg interfejsa kolekcija.

Pored kolekcija, framework definiše nekoliko klasa i interfejsa mapa. Mape čuvaju parove ključ/vrednost. I pored toga što mape nisu kolekcije u doslovnom smislu reči, one su u potpunosti integrisane sa kolekcijama.

The Collection Interfaces

Sr.No.Interfejs  i opis
1The Collection Interface   Omogućava rad sa grupama objekata; na vrhu je hijerarhije kolekcija.
2The List Interface   Nadgrađuje  Kolekciju, instanca Liste pohranjuje uređenu kolekciju elemenata.
3The SetThis extends Collection to handle sets, which must contain unique elements.
4The SortedSetThis extends Set to handle sorted sets.
5The Map   Mapira jedinstvene ključeve prema vrednostima.
6The Map.EntryThis describes an element (a key/value pair) in a map. This is an inner class of Map.
7The SortedMap   Nadgrađuje Mapu tako da su ključevi uređeni u rastućem poretku.
8The EnumerationThis is legacy interface defines the methods by which you can enumerate (obtain one at a time) the elements in a collection of objects. This legacy interface has been superceded by Iterator.

The Collection Classes

Java provides a set of standard collection classes that implement Collection interfaces. Some of the classes provide full implementations that can be used as-is and others are abstract class, providing skeletal implementations that are used as starting points for creating concrete collections.

The standard collection classes are summarized in the following table −

Sr.No.Class & Description
1AbstractCollectionImplements most of the Collection interface.
2AbstractListExtends AbstractCollection and implements most of the List interface.
3AbstractSequentialListExtends AbstractList for use by a collection that uses sequential rather than random access of its elements.
4LinkedListImplements a linked list by extending AbstractSequentialList.
5ArrayListImplements a dynamic array by extending AbstractList.
6AbstractSetExtends AbstractCollection and implements most of the Set interface.
7HashSetExtends AbstractSet for use with a hash table.
8LinkedHashSetExtends HashSet to allow insertion-order iterations.
9TreeSetImplements a set stored in a tree. Extends AbstractSet.
10AbstractMapImplements most of the Map interface.
11HashMapExtends AbstractMap to use a hash table.
12TreeMapExtends AbstractMap to use a tree.
13WeakHashMapExtends AbstractMap to use a hash table with weak keys.
14LinkedHashMapExtends HashMap to allow insertion-order iterations.
15IdentityHashMapExtends AbstractMap and uses reference equality when comparing documents.

The AbstractCollection, AbstractSet, AbstractList, AbstractSequentialList and AbstractMap classes provide skeletal implementations of the core collection interfaces, to minimize the effort required to implement them.

The following legacy classes defined by java.util have been discussed in the previous chapter −

Sr.No.Class & Description
1VectorThis implements a dynamic array. It is similar to ArrayList, but with some differences.
2StackStack is a subclass of Vector that implements a standard last-in, first-out stack.
3DictionaryDictionary is an abstract class that represents a key/value storage repository and operates much like Map.
4HashtableHashtable was part of the original java.util and is a concrete implementation of a Dictionary.
5PropertiesProperties is a subclass of Hashtable. It is used to maintain lists of values in which the key is a String and the value is also a String.
6BitSetA BitSet class creates a special type of array that holds bit values. This array can increase in size as needed.

The Collection Algorithms

The collections framework defines several algorithms that can be applied to collections and maps. These algorithms are defined as static methods within the Collections class.

Several of the methods can throw a ClassCastException, which occurs when an attempt is made to compare incompatible types, or an UnsupportedOperationException, which occurs when an attempt is made to modify an unmodifiable collection.

Collections define three static variables: EMPTY_SET, EMPTY_LIST, and EMPTY_MAP. All are immutable.

Sr.No.Algorithm & Description
1The Collection AlgorithmsHere is a list of all the algorithm implementation.

How to Use an Iterator ?

Often, you will want to cycle through the elements in a collection. For example, you might want to display each element.

The easiest way to do this is to employ an iterator, which is an object that implements either the Iterator or the ListIterator interface.

Iterator enables you to cycle through a collection, obtaining or removing elements. ListIterator extends Iterator to allow bidirectional traversal of a list and the modification of elements.

Sr.No.Iterator Method & Description
1Using Java IteratorHere is a list of all the methods with examples provided by Iterator and ListIterator interfaces.

How to Use a Comparator ?

Both TreeSet and TreeMap store elements in a sorted order. However, it is the comparator that defines precisely what sorted order means.

This interface lets us sort a given collection any number of different ways. Also this interface can be used to sort any instances of any class (even classes we cannot modify).

Sr.No.Iterator Method & Description
1Using Java ComparatorHere is a list of all the methods with examples provided by Comparator Interface.

Summary

The Java collections framework gives the programmer access to prepackaged data structures as well as to algorithms for manipulating them.

A collection is an object that can hold references to other objects. The collection interfaces declare the operations that can be performed on each type of collection.

The classes and interfaces of the collections framework are in package java.util.

Kolekcije u Javi

Prior to Java 2, Java provided ad hoc classes such as Dictionary, Vector, Stack, and Properties to store and manipulate groups of objects. Although these classes were quite useful, they lacked a central, unifying theme. Thus, the way that you used Vector was different from the way that you used Properties.

The collections framework was designed to meet several goals, such as −

  • The framework had to be high-performance. The implementations for the fundamental collections (dynamic arrays, linked lists, trees, and hashtables) were to be highly efficient.
  • The framework had to allow different types of collections to work in a similar manner and with a high degree of interoperability.
  • The framework had to extend and/or adapt a collection easily.

Towards this end, the entire collections framework is designed around a set of standard interfaces. Several standard implementations such as LinkedList, HashSet, and TreeSet, of these interfaces are provided that you may use as-is and you may also implement your own collection, if you choose.

A collections framework is a unified architecture for representing and manipulating collections. All collections frameworks contain the following −

  • Interfaces − These are abstract data types that represent collections. Interfaces allow collections to be manipulated independently of the details of their representation. In object-oriented languages, interfaces generally form a hierarchy.
  • Implementations, i.e., Classes − These are the concrete implementations of the collection interfaces. In essence, they are reusable data structures.
  • Algorithms − These are the methods that perform useful computations, such as searching and sorting, on objects that implement collection interfaces. The algorithms are said to be polymorphic: that is, the same method can be used on many different implementations of the appropriate collection interface.

In addition to collections, the framework defines several map interfaces and classes. Maps store key/value pairs. Although maps are not collections in the proper use of the term, but they are fully integrated with collections.

The Collection Interfaces

The collections framework defines several interfaces. This section provides an overview of each interface −

Sr.No. Interface & Description
1 The Collection InterfaceThis enables you to work with groups of objects; it is at the top of the collections hierarchy.
2 The List InterfaceThis extends Collection and an instance of List stores an ordered collection of elements.
3 The SetThis extends Collection to handle sets, which must contain unique elements.
4 The SortedSetThis extends Set to handle sorted sets.
5 The MapThis maps unique keys to values.
6 The Map.EntryThis describes an element (a key/value pair) in a map. This is an inner class of Map.
7 The SortedMapThis extends Map so that the keys are maintained in an ascending order.
8 The EnumerationThis is legacy interface defines the methods by which you can enumerate (obtain one at a time) the elements in a collection of objects. This legacy interface has been superceded by Iterator.

The Collection Classes

Java provides a set of standard collection classes that implement Collection interfaces. Some of the classes provide full implementations that can be used as-is and others are abstract class, providing skeletal implementations that are used as starting points for creating concrete collections.

The standard collection classes are summarized in the following table −

Sr.No. Class & Description
1 AbstractCollection

Implements most of the Collection interface.

2 AbstractList

Extends AbstractCollection and implements most of the List interface.

3 AbstractSequentialList

Extends AbstractList for use by a collection that uses sequential rather than random access of its elements.

4 LinkedListImplements a linked list by extending AbstractSequentialList.
5 ArrayListImplements a dynamic array by extending AbstractList.
6 AbstractSet

Extends AbstractCollection and implements most of the Set interface.

7 HashSetExtends AbstractSet for use with a hash table.
8 LinkedHashSetExtends HashSet to allow insertion-order iterations.
9 TreeSetImplements a set stored in a tree. Extends AbstractSet.
10 AbstractMap

Implements most of the Map interface.

11 HashMapExtends AbstractMap to use a hash table.
12 TreeMapExtends AbstractMap to use a tree.
13 WeakHashMapExtends AbstractMap to use a hash table with weak keys.
14 LinkedHashMapExtends HashMap to allow insertion-order iterations.
15 IdentityHashMapExtends AbstractMap and uses reference equality when comparing documents.

The AbstractCollection, AbstractSet, AbstractList, AbstractSequentialList and AbstractMap classes provide skeletal implementations of the core collection interfaces, to minimize the effort required to implement them.

The following legacy classes defined by java.util have been discussed in the previous chapter −

Sr.No. Class & Description
1 VectorThis implements a dynamic array. It is similar to ArrayList, but with some differences.
2 StackStack is a subclass of Vector that implements a standard last-in, first-out stack.
3 DictionaryDictionary is an abstract class that represents a key/value storage repository and operates much like Map.
4 HashtableHashtable was part of the original java.util and is a concrete implementation of a Dictionary.
5 PropertiesProperties is a subclass of Hashtable. It is used to maintain lists of values in which the key is a String and the value is also a String.
6 BitSetA BitSet class creates a special type of array that holds bit values. This array can increase in size as needed.

The Collection Algorithms

The collections framework defines several algorithms that can be applied to collections and maps. These algorithms are defined as static methods within the Collections class.

Several of the methods can throw a ClassCastException, which occurs when an attempt is made to compare incompatible types, or an UnsupportedOperationException, which occurs when an attempt is made to modify an unmodifiable collection.

Collections define three static variables: EMPTY_SET, EMPTY_LIST, and EMPTY_MAP. All are immutable.

Sr.No. Algorithm & Description
1 The Collection AlgorithmsHere is a list of all the algorithm implementation.

How to Use an Iterator ?

Often, you will want to cycle through the elements in a collection. For example, you might want to display each element.

The easiest way to do this is to employ an iterator, which is an object that implements either the Iterator or the ListIterator interface.

Iterator enables you to cycle through a collection, obtaining or removing elements. ListIterator extends Iterator to allow bidirectional traversal of a list and the modification of elements.

Sr.No. Iterator Method & Description
1 Using Java IteratorHere is a list of all the methods with examples provided by Iterator and ListIterator interfaces.

How to Use a Comparator ?

Both TreeSet and TreeMap store elements in a sorted order. However, it is the comparator that defines precisely what sorted order means.

This interface lets us sort a given collection any number of different ways. Also this interface can be used to sort any instances of any class (even classes we cannot modify).

Sr.No. Iterator Method & Description
1 Using Java ComparatorHere is a list of all the methods with examples provided by Comparator Interface.

Summary

The Java collections framework gives the programmer access to prepackaged data structures as well as to algorithms for manipulating them.

A collection is an object that can hold references to other objects. The collection interfaces declare the operations that can be performed on each type of collection.

The classes and interfaces of the collections framework are in package java.util.

Klasa Scanner u Javi

Postoje razni načini za učitavanje ulaza sa tastature, java.util.Scanner klasa je jedan od njih. Java Scanner klasa deli ulaz u tokene koristeći ograničavač (delimiter) koji je po defaultu blank. Ona obezbeđuje mnoge metode za čitanje i parsiranje različitih primitivnih vrednosti. Java Scanner klasa se mnogo koristi za parsiranje teksta za string i primitivne tipove pomoću regularnih izraza. Java Scanner klasa nasleđuje Object klasu i implementira Iterator i Closeable interfejse. Često korišćeni metodi Scanner klase Ovo je lista često korišćenih metoda klase Scanner:
Metod

Opis

public String next() vraća sledeći token iz scanner-a.
public String nextLine() pomjera poziciju scanner-a na sljedeći red i vraća vrednost kao string.
public byte nextByte() skenira sledeći token kao byte.
public short nextShort() skenira sledeći token kao short vrednost.
public int nextInt() skenira sledeći token kao int vrednost.
public long nextLong() skenira sledeći token kao long vrednost.
public float nextFloat() skenira sledeći token kao float vrednost.
public double nextDouble() skenira sledeći token kao double vrednost.
Primer Java Scanner-a za dobijanje ulaza sa konzole Pogledajmo jednostavan primer Java Scanner klase koja čita int, string i double vrednost kao ulaz:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import java.util.Scanner; 
class ScannerTest{ 
 public static void main(String args[]){ 
   Scanner sc=new Scanner(System.in); 
     
   System.out.println("Enter your rollno"); 
   int rollno=sc.nextInt(); 
   System.out.println("Enter your name"); 
   String name=sc.next(); 
   System.out.println("Enter your fee"); 
   double fee=sc.nextDouble(); 
   System.out.println("Rollno:"+rollno+" name:"+name+" fee:"+fee); 
   sc.close(); 
 
}
Ispis na ekranu:
Enter your rollno
111
Enter your name
Petar
Enter your fee
450000
Rollno:111 name: Petar fee: 450000
Primer Java Scanner-a sa delimiterom
Pogledajmo primer Scanner klase sa delimiterom. “\s” predstavlja blank.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import java.util.*; 
public class ScannerTest2{ 
public static void main(String args[]){ 
     String input = "10 tea 20 coffee 30 tea biscuits"
     Scanner s = new Scanner(input).useDelimiter("\\s"); 
     System.out.println(s.nextInt()); 
     System.out.println(s.next()); 
     System.out.println(s.nextInt()); 
     System.out.println(s.next()); 
     s.close();  
 
}
Ispis na ekranu:
10
tea
20
coffee

Metod toString() u Javi

Ako želimo predstaviti bilo koji objekat kao string, toString() metod je veoma pogodan.
Metod toString() vraća string reprezentaciju objekta.
Ako ispisujemo neki objekat, Java kompajler interno poziva toString() metod za taj objekat. Tako preklapanje toString() metoda vraća željeni izlaz, a to može biti stanje nekog objekta i sl., zavisno od naše implementacije.
Prednosti Java toString() metoda
Preklapanjem toString() metoda klase Object možemo vratiti vrednosti objekta, tako da nije potrebno pisati mnogo koda.
Razumevanje problema bez toString() metoda
Pogledajmo jednostavan kod koji ispisuje referencu.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Student{ 
 int rollno; 
 String name; 
 String city; 
  
 Student(int rollno, String name, String city){ 
 this.rollno=rollno; 
 this.name=name; 
 this.city=city; 
 
  
 public static void main(String args[]){ 
   Student s1=new Student(101,"Petar","Beograd"); 
   Student s2=new Student(102,"Marko","Banjaluka"); 
     
   System.out.println(s1);  //kompajler ovdje piše s1.toString() 
   System.out.println(s2);  // kompajler ovdje piše s2.toString() 
 
}
Ispis na ekranu:
Student@1fee6fc
Student@1eed786
 
Kao što se može videti u ovom primeru, ispis s1 i s2 ispisuje hashcode vrednosti objekata, a mi želimo da ispisuje vrednosti ovih objekata. Pošto Java kompajler interno poziva toString() metod, preklapanje ovog metoda će vratiti specifikovane vrednosti. Razmotrimo to u sledećem primeru:
Primer Java toString() metoda
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Student{ 
 int rollno; 
 String name; 
 String city; 
  
 Student(int rollno, String name, String city){ 
 this.rollno=rollno; 
 this.name=name; 
 this.city=city; 
 
   
 public String toString(){  //preklapanje toString() metoda 
  return rollno+" "+name+" "+city; 
 
 public static void main(String args[]){ 
   Student s1=new Student(101,"Petar","Beograd"); 
   Student s2=new Student(102,"Marko","Novi Sad"); 
     
   System.out.println(s1);  //kompajler ovde piše s1.toString() 
   System.out.println(s2);  // kompajler ovde piše s2.toString() 
 
}
Ispis na ekranu:
101 Petar Beograd
102 Novi Sad

Razlika između preopterećenja metoda i preklapanja metoda u Javi

Postoje mnoge razlike između preopterećenja metoda i preklapanja metoda u Javi. Lista tih razlika je data u sledećoj tabeli:

Br.

Preopterećenje metoda

Preklapanje metoda

1)Preopterećenje metoda se koristi da poboljša čitljivost programa.Preklapanje metoda se koristi da obezbedi specifičnu implementaciju metoda koji je već obezbeđen od njegove superklase.
2)Preopterećenje metoda se izvodi unutar klase.Preklapanje metoda se javlja u dve klase koje imaju IS-A (nasleđivanje) relaciju.
3)U slučaju preopterećenja metoda, parametar mora biti različit.U slučaju preklapanja metoda, parametar mora biti isti.
4)Preopterećenje metoda je primer compile time polimorfizma.Preklapanje metoda je primer run time polimorfizma.
5)U Javi, preopterećenje metoda se ne može izvesti samo promenom return tipa metoda. Return tip može biti isti ili različit u preopterećenju metoda. Ali neophodno je promeniti parametar.Return tip mora biti isti ili kovarijantan u preklapanju metoda.

Primer preopterećenja metoda u Javi

1
2
3
4
class OverloadingExample{ 
static int add(int a,int b){return a+b;} 
static int add(int a,int b,int c){return a+b+c;} 
}

Primer preklapanja metoda u Javi

1
2
3
4
5
6
class Animal{ 
void eat(){System.out.println("eating...");} 
class Dog extends Animal{ 
void eat(){System.out.println("eating bone...");} 
}

Razlika između objekta i klase

Postoje mnoge razlike između objekta i klase. Lista tih razlika je data u sledećoj tabeli:

Br.

Objekt

Klasa

1) Objekat je instanca klase. Klasa je nacrt ili šablon iz kojeg se objekti kreiraju.
2) Objekat je entitet iz realnog sveta kao što je olovka, laptop, mobilni telefon, krevet, tastatura, miš, stolica itd. Klasa je grupa sličnih objekata.
3) Objekat je fizički entitet. Klasa je logički entitet.
4) Objekat se uglavnom kreira pomoću new ključne reči npr. Student s1=new Student(); Klasa je deklarisana pomoću class ključne reči npr. class Student{}
5) Objekat se kreira mnogo puta po potrebi. Klasa se deklariše jednom.
6) Objekat alocira memoriju kada je kreiran. Klasa ne alocira memoriju kada je kreirana.
7) Postoje mnogi načini za kreiranje objekta u Javi kao što su new ključna reč, newInstance() metod, clone() metod, factory metod i deserijalizacija. Postoji samo jedan način za definisanje klase u Javi pomoću ključne reči class.

Argumenti komandne linije u Javi

Argument komandne linije u javi je argument prosleđen u vreme izvršavanja Java programa. Argumenti prosleđeni iz konzole mogu biti primljeni u Java program i mogu biti korišćeni kao ulaz. Dakle, ovo obezbeđuje pogodan način za proveravanje ponašanja programa za različite vrednosti. Možemo proslediti N (1,2,3 itd.) argumenata iz komandnog prompta. Jednostavan primer argumenta komandne linije u Javi U ovom primeru, primamo samo jedan argument i ispisujemo ga. Da pokrenemo ovaj Java program, moramo proslediti najmanje jedan argument iz komandnog prompta.
1
2
3
4
5
6
7
8
9
10
class CommandLineExample{ 
public static void main(String args[]){ 
System.out.println("Prvi argument je: "+args[0]); 
}
compile by > javac CommandLineExample.java 
run by > java CommandLineExample Petar
Ispis na ekranu:
Prvi argument je: Petar
Primjer argumenta komandne linije koji ispisuje sve vrednosti U ovom primeru, ispisujemo sve argumente prosleđene iz komandne linije. Za ovu svrhu, prolazimo niz pomoću for petlje.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class A{ 
public static void main(String args[]){ 
  
for(int i=0;i < args.length;i++) 
System.out.println(args[i]); 
}
compile by > javac A.java 
run by > java A Petar Marko 1 3 abc
Ispis na ekranu:
Petar
Marko
1
3
abc

Kreiranje API dokumenta

Moguće je kreirati API dokument u Javi uz pomoć javadoc alata. U java fajlu, moramo koristiti dokumentacioni komentar /**… */ da postavimo informaciju o klasi, metodu, konstruktoru, poljima itd. Pogledajmo jednostavnu klasu koja sadrži dokumentacioni komentar.
1
2
3
4
5
6
7
package com.abc; 
/** Ova klasa je korisnički definisana klasa koja sadrži metod cube.*/
public class M{ 
  
/** Metod cube ispisuje kub datog broja */
public static void  cube(int n){System.out.println(n*n*n);} 
}
Da bi se kreirao dokument API, potrebno je koristiti javadoc alat praćen imenom java fajla. Nema potrebe kompajlirati java fajl. U komandnom promptu, treba napisati:
1
javadoc M.java
da bi se generisao dokument API. Biće kreiran određen broj html fajlova. Treba otvoriti index.html fajl da bi se dobile informacije o klasama.

Ključna reč strictfp

Moguće je kreirati API dokument u Javi uz pomoć javadoc alata. U Java fajlu, moramo koristiti dokumentacioni komentar /**… */ da postavimo informaciju o klasi, metodu, konstruktoru, poljima itd. Pogledajmo jednostavnu klasu koja sadrži dokumentacioni komentar.
1
2
3
4
5
6
7
package com.abc; 
/** Ova klasa je korisnički definisana klasa koja sadrži metod cube.*/
public class M{ 
  
/** Metod cube ispisuje kub datog broja */
public static void  cube(int n){System.out.println(n*n*n);} 
}
Da bi se kreirao dokument API, potrebno je koristiti javadoc alat praćen imenom java fajla. Nema potrebe kompajlirati java fajl. U komandnom promptu, treba napisati: javadoc M.java da bi se generisao dokument API. Biće kreiran određen broj html fajlova. Treba otvoriti index.html fajl da bi se dobile informacije o klasama.