27
Java Training Session 3: More on Object Oriented Programming

Java Training

  • Upload
    strom

  • View
    44

  • Download
    0

Embed Size (px)

DESCRIPTION

Java Training. Session 3: More on Object Oriented Programming. static Methods, static Fields. static Methods Also called “class methods” Can be called without using any object (provided access is permitted) Calling syntax: ClassName.methodName([ parameters ]); - PowerPoint PPT Presentation

Citation preview

Page 1: Java Training

Java Training

Session 3: More on Object Oriented Programming

Page 2: Java Training

static Methods, static Fields• static Methods

– Also called “class methods”– Can be called without using any object (provided access is permitted)– Calling syntax: ClassName.methodName([parameters]);– Can also be called using a reference to an object of the same class

• ref.methodName([parameters]);– Can access only other static members of its class directly– Can be accessed by both static and non-static methods of the same class– For calling non-static methods of its class, must use an object of the same class– Is not associated with any object when called; hence does not have any “this”

reference– Example: StaticTest.java, ObjectCount.java

Page 3: Java Training

static Methods, static Fields (contd.)• static Fields

– Also called “class member variables”– Can be accessed without using any object (provided access is permitted)– Is not associated with any object; only a single copy exists which is shared by

all the objects of the class– Access syntax: ClassName.variableName– Can also be accessed using a reference to an object of the same class

• ref.variableName– Can be accessed by both static and non-static methods of the same class– When its value is changed, the change visible to all current and future objects

of the class– Example: ObjectCount.java

Page 4: Java Training

static Methods, static Fields (contd.)

• static methods are used to write those general purpose methods for which object creation is not necessary

• They are intended to provide the flavor of global functions in Java

• For example, all the methods of class Math (java.lang.Math) are static– Math.sqrt(900.0);– Math.pow(5, 2);

Page 5: Java Training

static Methods, static Fields (contd.)• static member variables are used to perform some class level calculations

– private static intobjCount = 0;– Example: ObjectCount.java

• They are also used to define variables intended to hold constant values that should not be changed but can be easily used by others– public static final double EARTH_G = 9.8;– Math.E, Math.PI etc.– They give the flavor of #define style activities in Java– In this type of use, the convention is to capitalize every letter of the identifier

and separate words with underscores– Example: PublicStaticFinal.java

Page 6: Java Training

Static Exampleclass SomeConstant {

public static final double EARTH_G = 9.8;

}

public class PublicStaticFinal {

public static void main(Stringargs[]) {System.out.println("EarthGravitaional const: " + SomeConstant.EARTH_G);

// output = 9.8 //SomeConstant.EARTH_G = 10.0; // compiler error

System.out.println("Value of PI is: " + Math.PI); // output = 3.141592653589793System.out.println("Value of E is: " + Math.E); // output = 2.718281828459045 }}

Page 7: Java Training

Let’s Try!!• Say Prime Bank is planning to start a new type

of Account. And they are planning to give some rewards for the starting account holders.

• For simplicity we consider some money rewards.

Account Number Prize Amount1 100002 50003 2000Others (No Award money)

Page 8: Java Training

Design

• Write 2 classes. • Account– Fields

• One static field for keeping track of number of accounts.• One field for name of the account• One field for awarded amount.

– Methods• Constructor with account name parameter.• Getters for account name and reward amount• And a print() method which will print the account name and award

amount

• and AccountTest with a public main method.

Page 9: Java Training

AccountTestpublic class AccountTest {

public static void main(String[] args) { Account a1 = new Account("Shakib Al Hasan"); Account a2 = new Account("TamimIqbal"); Account a3 = new Account("Shafiul Islam"); Account a4 = new

Account("MohammadAshraful"); Account a5 = new Account("AlokKapali");

a1.print(); a2.print(); a3.print(); a4.print(); a5.print(); }}

Account Name: "Shakib Al Hasan", Rewared Amount: 10000

Account Name: "TamimIqbal", Rewared Amount: 5000

Account Name: "Shafiul Islam", Rewared Amount: 2000

Account Name: "Mohammad Ashraful", Rewared Amount: 0

Account Name: "AlokKapali", Rewared Amount: 0

Page 10: Java Training

Package

• Group of classes• Physically a folder having some classes.• Ensures hierarchy and easy reusability.• In a package all the class starts with package term.

Ex. package com.primebank.sme;• If a class is not included in a package then it is in

default package.• Class from default package can’t be imported

from other project or package. So not reusable!!

Page 11: Java Training

Package Naming Convention• Usually package names are in all small letter.• Ex: java.net, java.sql, java.io, com.mysql.jdbc.• Another common practice is to have a hierarchy like

– com.mysql.jdbc– org.springframework.jdbc

• First part indicates nature of project. Type like TLD (Top Level Domain)– com for commercial project– org for organizational project– edu for educational project.

• Second part indicates name of the corporation or organization.• Third part is the name of the project.

Page 12: Java Training

MySql provided Classes

Page 13: Java Training

Core Concepts of OOP

Encapsulation

Polymorphism

Inheritance

Page 14: Java Training

Inheritance

• Inheritance in oop is similar to real life inheritance.

• Receiving something from ancestors.• One class can reuse fields and methods

previously declared in other class.• This increases reusability and reduce

reinventing the while.

Page 15: Java Training

Extends

• In Java a class inherits other class by extends key word.

public classScienceStudentextends Student

SubClass

SuperClass

Page 16: Java Training

Example

• Student, ScienceStudent and CommerceStudent example.

• Let’s try – Extend ScienceStudent class to create BiologyStudent and ComputerStudent.

• BiologyStudent have one more field naming biology.

• ComputerStudent have one more field naming computer.

Page 17: Java Training

protected Members

• Inherited by subclasses just like public members

• Can be accessed by subclasses • For non-subclasses, they act as private

members of the class

Page 18: Java Training

Constructors in Subclasses• Every constructor of a class calls its superclass

constructor explicitly or implicitly• A class’s constructor can call its superclass’s

constructor explicitly using the “super” keyword– Its must be the first statement of the constructor– Can supply arguments to call specific versions of superclass

constructors• If a class’s constructor does not explicitly call its

superclass’s constructor, then “javac” implicitly tries to call the no-argument constructor of the superclass– If the superclass does not have a no-argument constructor,

then “javac” reports a compiler error

Page 19: Java Training

Superclasses and Subclasses• Superclassesrepresent a general category• Subclasses are built upon the superclasses to handle

specific details• Subclasses have a “IS-A” relation with superclasses• Example:– class A { }– class B extends A { }, class C extends A { }– B “is-a” A, C “is-a” A, but B “is not a” C– A, B, C all “are” Object. (who is this Object :-?)

Page 20: Java Training

Object!!• Object is a very special class in Java.• Object is super class for all classes in java. • Any class is a sub class of Object.

Page 21: Java Training

Object Class Methods• Object class don’t have any members. But it has the following methods.

• booleanequals(Objectobj)• String toString()

• protected Object clone()• protected void finalize()• Class<?>getClass()• inthashCode()

• void notify()• voidnotifyAll()

• void wait()• voidwait(long timeout)• voidwait(long timeout, intnanos)

Page 22: Java Training

Polymorphism

• One name, many methods (tasks)• Program in the general, rather than program

in the specific• We already have used that !!• The print() method in our student class is a

very good example of polymorphism.

Page 23: Java Training

Polymorphism

• Another type of polymorphism is also possible. Called Method Overloading.

• Same method having same name but different number of parameters.

• Let’s revisit the Triangle we wrote in previous class.

• Example: – Triangle.compare(Triangle t1, Triangle t2)– t1.compare(Triangle t2)

Page 24: Java Training

Method Overriding

• When a subclass defines a method whose signature is identical to a method present in the superclass then the new method overrides the method present in the superclass.

• If the signatures differ in the parameter types or parameter counts, then it simply becomes a overloaded method.

Page 25: Java Training

Logical Operators

• Conditional Operators– Conditional AND (&&)– Conditional OR (||)– Perform Short-Circuit evaluation

• Short-Circuit Evaluation– The parts of an expression are evaluated only until it is

known whether the condition is true or false• Example: LogicalTest.java

Page 26: Java Training

Logical Operators (contd.)

• Boolean Logical Operators– Boolean Logical AND (&)– Boolean Logical Inclusive OR (|)– Boolean Logical Exclusive OR [XOR] (^)– Do not perform Short-Circuit evaluation; always

evaluate both of their operands• Example: LogicalTest.java

Page 27: Java Training

Logical Operators (contd.)

• Logical Negation Operator (!)– Also called logical NOT or logical complement– Reverses the meaning of a condition– boolean b = !true; // b = false