- Basic unit of Object-Oriented Programming paradigm(pattern),
- Ex:
Animalis a class andtigeris an object ofAnimalclass,
<<modifiers>> class <<class name>> {
// Body of the class goes here
}- Modifiers:
Keywordsthat associatespecial meaningsto the class declaration,- May have
zero or more modifiers,
- Class name:
User definedclass name,- Follows
Pascal Casenaming convention,
- Body of the class:
- Contains
fields,methods,
- Contains
- Ex: (
Hooman.java)public class Hooman { // ... }
- has
publicmodifier, - class name is
Hooman, - body contains
field,constructor& somemethods,
- has
-
A class in Java may consist of
5components: -
- Represent properties or
attributesof objects of that class, 2types offieldsfor a class:-
Non-staticvariables,- Every object contains
separate copyof these variables, - Must be
accessed using objectof the class, - Can be accessed using dot(
.), - Ex:
obj.name;,
-
Staticvariables,- Declared using the
static keywordas a modifier, - Every object uses
same copyof these variables, Shared among all objectsof this class,- Can be
called using class name, - Can be accessed using dot(
.) on bothobjectandclass, - Ex:
MyClass.count,
-
staticas well asnon-staticfields are initialized to a default value,- A
numericfield (int,long, ...) is initialized tozero(0), - A
booleanfield is initialized tofalse, - A
referencetype field is initialized tonull,
- A
- Represent properties or
-
- Represent
behavior of objectsof the class, - More info is discussed below,
- Represent
-
- Used to
create objectsof the class, - More info is discussed below,
- Used to
-
- For
initializing static variableswhich need somecalculation,
- For
-
- For
initializing variableswhich need somecalculation,
- For
thisrefers tocurrent instance. More details is discussed next section,- See
Hooman.java,public class Hooman { // Field - 2 Class variables public static final String SPECIES; private static int objectCounter = 0; // Field - 3 instance variables private String name; private int age; private boolean isAdult; //static initializers - 1 static { // normally more calculation is performed as per need SPECIES = "Homo Sapiens"; } //instance initializers - 1 { isAdult = false; // by default false though } //constructor - 1 public Hooman() { objectCounter++; } //constructor - 2 public Hooman(String name, int age) { this.name = name; this.age = age; isAdult = age >= 18; objectCounter++; } // methods - 6 methods public String getName() {...} public void setName(String name) {...} public int getAge() {...} ... }
- Represent
behaviorof objects of the class, - Is a named
block of code, - Structure:
<<modifiers>> <<return type>> <<method name>> (<<parameters list>>) <<throws clause>> { // Body of the method goes here }
Formal parametersof a method are treated as local variables,throwsis optional,- Ex:
public void setAge(int age) { if(age < 0 || age < this.age) return; this.age = age; isAdult = (age>=18); }
return-typecan be any data type,voidmeans doesn't return any value,- Follows
camelCasenaming convention, - Method signature:
- Combination of
- method
name, and - its parameters
number,types,order,
- method
Modifiers,return-type, andparameter namesaren't part of thesignature,- Ex:
public int add(int num1, int num2){ return num1+num2; }
- Signature is:
add(int, int);
- Signature is:
- Combination of
- Not allowed to have more than one method in a class with the same signature,
- A class can have
two types of methodlike variables:Instant methodandClass method,
Non-staticmethod,- Used to implement
behavior of the objectsof the class, - Must be
called using object, - Ex: See
showSpecificCharacter()inHooman.java,Accessing like thispublic void showSpecificCharacter(){ System.out.println("Name is => "+name); }
Hooman anik = new Hooman("Anik",22); anik.showSpecificCharacter(); // Name is => Anik
staticmethod,- Used to implement the
behavior of the classitself, - Can be called using both
objectorClass name(Recommended) itself, - Can't access instant variables here, guess why?
- Ex: See
showSomeCharacter()inHooman.java,Calling like thispublic static void showSomeCharacter(){ System.out.println("General characteristics"); //System.out.println(name);//can't access instant variable here }
Hooman anik = new Hooman("Anik",22); anik.showSomeCharacter(); // General characteristics -------(a) Hooman.showSomeCharacter(); // General characteristics -----(b)(a)is ok butnot recommended,(b)best practice,
- Special method having
public,static,void, method namemainand having aString arrayas parameter,public static void main(String[] args) { // entry point of execution }
JVM invokes this method. If not found, then JVM does not know where to start the application. So, it throws an error stating that no main() method was found,- You can have as many as
main()method in a class having different signature. But JVM will call only the above one, - You don't need to write main method in a class if you don't want it to start from here,
- You can also call
main()method just like other method, - Ex: See
Test.java,public class Test { public static void main(String[] args) { ... } ... }
Instancemethod is invoked on aninstance of the classusing dot(.) notation,Class methodis invoked onClass nameusing dot(.) notation,- Ex: See
main()inTest.java,Hooman anik = new Hooman("Anik",22); anik.showSpecificCharacter(); // instance Hooman.showSomeCharacter(); // static
- Used to
initialize an objectof a class, - Constructor name is the same as the simple name of the class,
- Doesn't have return type,
- Basic Structure(can have
throwsclause also):<<Modifiers>> <<Constructor Name>>(<<parameters list>>){ // Body of constructor goes here }
- Overloading of constructor is possible,
- If a class has multiple constructors, all of them must differ from the others in the
number,order, ortypeof parameters, - One constructor can call other constructor,
Access modifiersare same as others,- By default,
JVMadds adefault constructoras long as there is no constructor. default constructordoesn't accept any parameter and does nothing,default constructoronly satisfies logic so that we can create object,- You can't declare a constructor
static. Rememberstaticis part of class not object, - Ex: See
Bird.java,Creating object like this: Seepublic class Bird { ... // constructor - 1 public Bird() { this.name = "Unknown"; this.species = "Not found"; this.canFly = false; } // constructor - 2 public Bird(boolean canFly) { this("unknown","Not found",canFly); // calling other constructor. Remember `this`. must be first line } // constructor - 3 public Bird(String name, String species, boolean canFly) { this.name = name; this.species = species; this.canFly = canFly; } // constructor - 4 . Copy constructor public Bird(Bird bird){ this.name = bird.name; this.species = bird.species; this.canFly = bird.canFly; } ... }
birdTest()inTest.java:private static void birdTest(){ Bird deadBird = new Bird(); // 1 deadBird.printDetails(); // Unknown -> Not found -> false Bird unknownBird = new Bird(true); // 2 unknownBird.printDetails(); // unknown -> Not found -> true Bird eagle = new Bird("Eagle", "Eagle", true); // 3 eagle.printDetails(); // Eagle -> Eagle -> true Bird secondEagle = new Bird(eagle); // 4 secondEagle.printDetails(); // Eagle -> Eagle -> true }
- Object can be created by calling its constructor.
- Ex:
new Hooman();, This object will be automatically deleted, since we are not assigning it in any variable. - When you create an object using
newkeyword, it allocates memory for eachinstance fieldof the class, - Java runtime takes care of memory allocation, you don't need it,
- Creating object and calling method:
Hooman saeed = new Hooman("Saeed",21); System.out.println(saeed.isAdult()); // true
THERE IS NO SHORTCUT OTHER THAN PRACTICING