Module 3 Quick Reference
Module 3 Quick Reference
Class
Class is a blueprint or template or prototype which defines the characteristics of the Object.
Syntax:
class ClassName{
//data
//functionality
The data, or variables, defined within a class are called instance variables. The methods defined
generally work on the data.
Naming Convention:
Class names start with capital letter, subsequent words in the class start with capital letter. Ex:
SavingsAcccount
Data / variables start with lowercase and words in the class start with capital letter. If the
variable is single word lowercases are used. Ex: number, name, numberOfStudents
Methods always start with verbs and follow the same convention of data. Ex: printDetails(),
deposit(),
Object
Objects (instances) of the class are created using the new operator using the syntax as shown below.
When a new instance is created the new operator dynamically allocates memory for an object. The data
is initialized with the default values. Each object has its own copy of the data.
The variable “account” is also known as “reference” as this refers to the newly created object.
Default Values
Integer types (byte, short, int, long) : 0
Floating types (float, double) : 0.0
boolean : false
char : 'u0000' // Unicode Character 'NULL'
All other objects : null (Means the variable does not refer to any object).
Once an object is created the data and methods can be accessed using the “.” operator.
account.withdraw(10000);
In this case both account and temp refer to the same object in memory. The object can be manipulated
using any one of the references, the same changes can be seen when accessing with other reference.
Constructors
Constructors are special methods which are used for building Objects (Creating Objects). These methods
are automatically invoked by the JVM when a new instance is created.
this
“this” is a keyword which refers to the current instance (object ).
}
“this” can also be used for passing as a parameter to the method or as return type.
Initialization Blocks
Initialization Blocks are added to the classes using syntax
{
//code
}
There can be any number of Initialization blocks in a class
These blocks are executed once for each instance
They are executed when a new instance is created, they are executed before the constructor
If many blocks are there in a class, they are executed in the same sequence as they are present
in the java source file
These blocks are used for initializing the instance data
Like methods they can also be used for calling other instance methods
The data is hidden using the “private” access modifier. The private data can be accessed only with in the
class.
class Account{
private int number;
private String name;
private double balance;
}
Though the private data can be made accessible using any method names, the java follows
specific naming conventions for these methods.
If the naming conventions are followed, they will be considered as proper “Java Beans” and
become easily recognizable by other classes when used in plug in environments.
Get Methods :
Syntax: public dataType getVariableName();
Ex: public int getName(){
return this.name;
}
Set Methods
Syntax: public void setVariableName(dataType var);
Ex: public void setName(String name){
this.name = name;
}
Additional Points
It is not mandatory to provide both getter and setter methods for all the instance data.
Depending on the data both/only getter/only setter/none can be provided.
o In the Account as the number and balance cannot be changed only getter is provided.
Getter methods can also be provided even when there is no specific related data but the value is
calculated like area of a rectangle
Ex: public double getArea(){
return length * breadth;
}
Garbage Collection
Garbage Collection is a process of automatically deleting unused objects and freeing the memory used
by them. JVM has Garbage Collector (a low priority background thread) which checks for unused objects
and frees the memory by deleting them.
An Object is said to be unused when it is not being referenced by any reference variable.
finalize() method
The class Object which is super class of all the objects in java has finalize() method. Before deleting any
object from memory, the Garbage Collector calls the finalize() method. This is equivalent to destructors
in C++. Programmer should write clean up code for releasing resources in this method.
Overloading
Using the same method name with different parameters is known as overloading.
This feature is provided in object oriented languages.
In overloading the method signatures should be unique
o The number / sequence / type of parameters should be different.
o The return type is not considered as part of signature.
If the parameters are same and even if the return type is different the compiler
will through error as it is not proper overloading
Overloading is useful when the functionality is same but will be having different scenarios
(parameters), like adding different types of ints/floats etc, or saving object to a file or database
etc..
When calling an overloaded method, depending on the number / type of parameters passed
respective overloaded method is invoked.
Overloading Constructors
Similar to normal methods constructors also can be overloaded.
return book;
}
}
class MainClass{
public static void main(String args[]){
Library lib = new Library();
Book book1 = new Book(..)
Lib.addBook(book);
static
static is a Java keyword which can be used with data, methods and blocks.
static data
static data is also known as class data.
Syntax :
class Account{
public static int accountNumberCounter;
In case of instance data, every object has its own copy of data. Whereas only one copy of static
data is shared by all the objects.
This data can be accessed directly using the ClassName (if accessible)
int num = Account.accountNumberCounter;
static methods
static methods are also known as class methods
Syntax :
class Account{
public static int accountNumberCounter;
static blocks
These blocks are similar to initialization blocks, but are executed only once when the class is
used (loaded) for the first time.
Syntax:
static{
// code
}
Similar to Initialization blocks, there can be any number of blocks in the class and are executed
in the same sequence they appear in the source file.
These block are similar to static methods and have the same limitations
These blocks are used for initializing the static data (which is common to all the objects) like
database connections etc…
Command-Line Arguments
Command line arguments are passed to the main method as String array
public static void main(String[] args){…}
These arguments can be passed to the main method while executing using the following syntax:
java ClassName arg1 arg2
java Add 10 20
The arguments are separated using spaces
If an argument has space in it, the argument should be enclosed with in double quotes
java ClassName "First Arg" arg2
Varargs: Variable-Length Arguments
Java allows passing variable arguments to a method through varargs
Syntax: varargs are indicated using "…" (three dots)
public returnType methodName(dattype … v){ }
public int add(int… v) {}
Condition: The varargs parameter in a method should be the last parameter
Calling: The methods with varargs can be called using zero or any number of parameters
add();
add(10, 20);
add(10, 20 , 30, 40);
The passed parameters are available as an array and can be read using loops.
public int add( int ...v) {
int sum = 0;
for (int i : v) {
sum += i;
}
return sum;
}
Overloading: The varargs methods can also be overloaded
public void doSomething( int ...v) {}
public void doSomething( boolean ...v) {}
Ambiguity: If we call the above method using parameters there will not be any ambiguity. But If
we call the method without any parameters like
doSomething();
The compiler throws errors as the call is ambiguous and compiler cannot make a decision to call
which method.
Inheritance
Inheritance is the ability of an object to acquire properties from another object.
Inheritance is implemented when there is "IS A" relationship. For example
o Car IS A Vehicle
o SavingsAccount IS A Account
o Developer IS A Employee
Inheritance in Java is implemented using extends keyword
class Employee{
}
class Developer extends Employee{
}
Java allows only Single Inheritance. A class can extend from only one class. C++ allows multiple
Inheritance
Java allows Multilevel inheritance. There can be hierarchy of classes.
class TeamLeader extends Developer{ }
class Manager extends TeamLeader{ }
When a class inherits from another class, It inherits protected, default and public data and
functionality, does not inherit the private data and functionality.
The class Employee is called parent/super class and Developer is called sub class.
Subclasses can add new data and functionality
Subclasses can modify the functionality defined in the parent class by overriding the methods
super
super refers to the parent object
super is used in two scenarios
o Calling parent class constructors // explained later
o Referring super class data or functionality
super.number; // refers to super class data
The super(…) constructor call should be the first statement with in a subclass constructor.
Protected
Protected members can be accessed with in the class and in the sub classes.
Method Overriding
Defining the same method in the sub class as that of the parent class is known as overriding
Through overriding the subclass can change the functionality defined in the parent class.
When overriding the subclass cannot change the method signature or return type
When overriding subclass cannot reduce the visibility of the method, but can increase the
visibility
o If the parent class method is protected sub class can change it to public
o If the parent class method is public sub class cannot change it to protected
Polymorphism
“Poly” means “Many”, “Morph” means “Form” : Many Forms
The ability of an object to behave differently (for the same message) is known as polymorphism.
This is possible because of two key features
o Superclass variables ability to refer to subclasses
o Method overriding
When subclasses have overridden a parent class method and these are referred using the parent
class reference variable and when the overridden method is invoked these method calls will
result in different behavior, this is known as polymorphism.
shape = rec;
shape.draw(); //Draws Rectangle
shape = circle;
shape.draw(); //Draws Circle
}
}
abstract
abstract keyword can be used with methods and classes
abstract methods are methods which have only definition but does not have any
implementation
syntax:
public abstract double getArea(); //they cannot have body
When a super class has no specific implementation for a functionality (like area of a shape) but
wants to ensure that all its subclasses must implement the functionality (all shapes have area)
those methods are declared as abstract
A class containing abstract methods must be declared as abstract, if not the compiler will throw
error
pubic abstract class Shape{
public abstract double getArea();
}
As the abstract class in incomplete, it cannot be instantiated.
Shape shape = new Shape(); // NOT VALID
But abstract class references can be declared. And it can be used to refer to subclass objects.
class Rectangle extends Shape{…}
Shape shape; //VALID
shape = new Rectangle();
shape.draw();
A subclass extending from an abstract class must provide implementation by overriding the
abstract method.
o If the subclass does not provide implementation, compiler throws error
o If the subclass does not want to implement the abstract methods, the class must also be
declared as abstract
It is not mandatory for a abstract class to have abstract methods. A class can be declared as
abstract even if it does not contain any abstract method
final
final keyword is used with data, methods and classes
final data: final data is constant.
private final double MAX_MARKS = 100;
o The final data must be initialized in any one of the following three places
At the time of declaration / In the Initialization Block / In the Constructor
o Naming Convention : uses all capitals with underscores separating the words
final method: final methods cannot be overridden
public final do sin(…){ }
final class: final classes cannot be inherited
public final class Math{…}