Sie sind auf Seite 1von 14

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.

ClassName variable = new ClassName();

Account account; // Creates a reference account and at present refers to “null”


account = new Account(); // refers to the newly created object

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);

Assigning Object Reference Variables


An Object can be accessed using many references.

Account account = new Account();


Account temp = account;

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.

To remove the reference of an object, it can be set to null.


temp = null;

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.

Constructor Method Rules


 Constructors have the same name as that of the class
 Constructors do not have any return type
class Account{
public Account(){ //Default Constructor
}

Public Account(int number, String name, float initialDeposit){ //parameterized constructor


}
}
Constructor Points
 Default constructor
o Constructor without any parameters is known as default constructor
o When a class do not provide any constructor the compiler adds the default constructor
to the class
o If any other constructor (parameterized) is provided, the compiler does not add the
default constructor
 If default constructor is needed it should be explicitly added by the programmer
 Constructors are automatically invoked by the JVM, when creating new instances. They cannot
be called explicitly from other methods
 Constructors can be invoked from other constructors using this(…) constructor call
 If a return type is specified for a constructor, It is treated like a normal method
 Constructors can be overloaded
o When constructors are overloaded, depending on the number of parameters passed
while creating instance, the respective constructor is invoked by the JVM.
 Constructor can call other methods like normal methods

this
“this” is a keyword which refers to the current instance (object ).

this has following two important uses

1. Accessing instance variable


 It is possible to declare instance variables and local variable with the same name. In
such cases “this.” Is used to refer to the instance data.
2. Calling Constructors from other constructors (this constructor call)
 One constructor can be invoked from other constructors using this(…) constructor call.
This approach is used to move the important logic like storing / reading objects to files /
database to single constructor so that it is easier to maintain/ modify code.
 Rule: this(…) constructor call should be the first statement with in a constructor
class Account{

public Account( String name) {


this(name,0);
}
public Account(String name, double balance) {
this.name = name;
this.balance = balance;
}

}
“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

Instance Variable Hiding


In general the data in the objects is hidden, so that the data is not modified with unwanted / invalid
values.

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;
}

Getter and Setter Methods


When the data is made private, it cannot be accessed from outside. But still It may be required to
access from outside classes, In such cases the data is made available by using the Getter and Setter
methods. They are also known as accessors and mutators.

Getter and Setter Methods Naming Conventions:

 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;
}

 The return type is same as that of the datatype


 The method name always starts with get, followed by the variable name, but the first character
of the variable is converted to capital case.
 Boolean Get Method : In case of boolean datatypes the name starts with “is”.
o public boolean isEligible(){ … }

Set Methods
 Syntax: public void setVariableName(dataType var);
Ex: public void setName(String name){
this.name = name;
}

 The return type is always void


 The method name always starts with set, followed by the variable name, but the first character
of the variable is converted to capital case.

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.

Objects as Parameters and Return types


Similar to primitive datatypes, the objects can also be used as parameters to a method and can also be
used as return type.

public class Book{


// data & functionality & Constructors
}

public class Library{


//data

// Adds book to library


public void addBook(Book book){
//Code for adding book to collection
}

//returns book object from Library


public Book getBook(String authorName){
//loops through the collection and returns the book if found

return book;
}
}

class MainClass{
public static void main(String args[]){
Library lib = new Library();
Book book1 = new Book(..)
Lib.addBook(book);

Book temp = lib.getBook(“…”);


}
}

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;

public static void printNextAccountNumber(){


System.out.println("Next Account number: " + accountNumberCounter);;
}
}
 static methods can be accessed directly using the ClassName
Account.printNextAccountNumber();
 Limitations: static methods can access only other static data and methods. They cannot access
instance data or methods.
 Instance methods can access static methods and data

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

Object as Super Class of All Classes


 When a class is not defined as extending from any other class, it automatically extends from a
class java.lang.Object
o This is done by the compiler by adding “extends Object” statement to all the classes
which are not extending from other classes
 Because of this Object becomes super class of all classes in Java

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

public void printDetails(){


super.printDetails(); // calls super class printdetails method
}

Objects are built top down / Calling parent constructors


 When an instance of sub class is created, it automatically calls the parent class constructor
 This is accomplished because the compiler adds “super()” constructor call in all the sub class
constructors
class Developer(){
public Developer(){ // Default Constructor
super(); //compiler adds this statement
}

public Developer(String name, double salary, String platform){ //Overloaded Constructor


super(); //compiler adds this statement
this.name = name;
this.salary = salary;
this.platform = platform;
}
}
 If the parent class does not have default constructor, the compiler throws error. The
programmer must explicitly call the parent class constructor with arguments.
class Employee{
public Employee(String name, double salary){
this.name = name;
this.salary = salary;
}
}
class Developer(){
public Developer(String name, double salary, String platform){ //Overloaded Constructor
super(name, salary);
this.platform = platform;
}
}

 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

Super Class variable referring Subclass Objects


 A super class variable can be used to refer to subclass objects (as we can refer to cars/ two
wheelers as using their parent reference vehicle)
class Employee{}
class Developer extends Employee{}
In this example a developer can also be called as an employee.

Employee employee = new Employee;


Developer developer = new Developer();
Employee emp;
emp = developer; // VALID
 But subclass variable cannot refer to superclass object ( as all vehicles cannot be cars)
Developer dev;
dev = employee; // NOT VALID
 Limitation:
o When referring subclass objects with super class references only the methods defined in
the super class and its parent classed are accessible.
o The new methods defined in the sub class are not accessible
 Overriding method Behavior :
o Even when referring using super class variable, if a overridden method (overridden in
the subclass) is called using the super class reference will invoke (call) the subclass
method.

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.

public class Shape {


public void draw(){...}
}

public class Rectangle extends Shape{


public abstract void draw(...){} //Overridden
}

public class Circle extends Shape{


public abstract void draw(...){} //Overridden
}

public class Main {


public static void main(String[] args) {
// TODO Auto-generated method stub
Shape shape;
Rectangle rec = new Rectangle(10, 20);
Circle circle = new Circle(10);

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{…}

Das könnte Ihnen auch gefallen