Вы находитесь на странице: 1из 31

Java Basics

Constructors
Constructors are used to initialized objects. Constructors have the same name as the class itself. They do not specify a return type not even void.

Methods Overloading
It is possible to create methods that have the same name, but different parameter lists and different definitions. It is used when objects are required to perform similar tasks but using different input parameters. When we call a method in an object, Java matches up the method name first and then the number and type of parameters to decide which one of the definitions to execute.

Overloaded Methods
Methods of the same class that have the same name but different numbers or types of parameters are called overloaded methods. Use overloaded methods when they public void move (int x, int y) { ... } perform similar tasks: public void move (double x, double y) { ... }
public void move (Point p) { ... }

public Fraction add (int n) { ... } public Fraction add (Fraction other) { ... }
9-4

Overloaded Methods (contd)


The compiler treats overloaded methods as completely different methods. The compiler knows which one to call based on the number and the types of public class Circle the parameters passed to the method. { Circle circle = new Circle(5);
circle.move (50, 100); Point center = new Point(50, 100); circle.move (center); public void move (int x, int y) { ... } public void move (Point p) { ... } ...
9-5

Overloaded Methods (contd)


The return type alone is not sufficient for distinguishing between overloaded methods.
public class Circle { public void move (int x, int y) { ... } Syntax error

public Point move (int x, int y) { ... } ...

9-6

Static Fields
A static field (a.k.a. class field or class variable) is shared by all objects of the class. A non-static field (a.k.a. instance field or instance variable) belongs to an individual object.

9-7

Static Members (class members)


Sometimes we want to define a member that is common to all the objects and accessed without using a particular object. The member belongs to the class as a whole rather than the objects created from the class. E.g. static int count; Static int max(int x, int y);

Java creates only one copy for a static variable which can be used even if the class is never actually instantiated. Restrictions
They can only call other static methods. They can only access static data. They cannot refer to this or super in any way.

Static Fields (contd)


A static field can hold a constant shared by all objects of the class: Reserved
public class RollingDie { private static final double slowDown = 0.97; private static final double speedFactor = 0.04; ... words:

static final

A static field can be used to collect statistics or totals for all objects of the class (for example, total sales for all vending machines)

9-10

Static Fields (contd)


Static fields are stored with the class code, separately from instance variables that describe an individual object. Public static fields, usually global constants, are referred to in other classes using dot notation: double area = Math.PI * r * r; ClassName.constName
setBackground(Color.BLUE); c.add(btn, BorderLayout.NORTH); System.out.println(area);

9-11

Static Fields (contd)


Usually static fields are NOT initialized in constructors (they are initialized either in declarations or in public static methods). If a class has only static fields, there is no point in creating objects of that class (all of them would be identical). Math and System are examples of the above. They have no public constructors and cannot be instantiated.
9-12

Static Methods
Static methods can access and manipulate a classs static fields. Static methods cannot access non-static fields or call non-static methods of the class. Static methods are called using dot double x = Math.random(); notation: ClassName.statMethod(...)
double y = Math.sqrt (x); System.exit();

9-13

Static Methods (contd)


public class MyClass { public static final int statConst; private static int statVar; private int instVar; ... public static int statMethod(...) { statVar = statConst; OK statMethod2(...);

Static method

instVar = ...; instMethod(...);


}

Errors!
9-14

Static Methods (contd)


main is static and therefore cannot access non-static fields or call non-static methods of its class:
public class Hello { private int test () { ... } public static void main (String[ ] args) { System.out.println (test ()); } }
9-15

Error: non-static method test is called from static context (main)

Non-Static Methods
A non-static method is called for a particular object using dot notation:
vendor.addMoney(25); objName.instMethod(...); die1.roll();

Non-static methods can access all fields and call all methods of their class both static and non-static.

9-16

Review:
Are you allowed to define a class with no constructors? Can a class have two different no-args constructors? What is a good style for naming constructors? What is the common Java style for method names?
9-17

Review (contd):
Are parameters of primitive data types passed to methods by value or by reference? Can a method have more than one return statement? Can a method have no return statements? Can a method create a new object and return it to the calling method?
9-18

Review (contd):
When is it appropriate to define overloaded methods? Describe the difference between static and instance variables. What is the syntax for referring to a public static field outside the class?

9-19

Review (contd):
Can non-static methods access static fields? Can static methods access instance variables? Can static methods have local variables?

9-20

Inheritance
The mechanism of deriving a new class from an old one is called inheritance. Old class is known as the base class or super class or parent class and new one is called as the subclass or derived or child class. Inheritance allows subclasses to inherit all the variables and methods of their parent classes. and has its own instance variables and methods. This helps to build classes for complex problems and also avoid the repetition of codes in the new class. Extends keyword is used to create sublcass

Types of inheritance
Single inheritance (Only one super class). Multiple inheritance (several super classes) Hierarchical inheritance (One super class many subclasses) Multilevel inheritance (Derived from derived class)

Subclass Constructor
It is used to construct instance variables of both the subclass and the superclass. Super keyword is used for that. Super is used with following conditions.
Super may only be used within a subclass constructor method. The call to super class constructor must appear the first statement with the subclass constructor. Parameters in the super call must match the order and type of the instance variable declared in the superclass.

Final Classes
Inheritance allows creation of subclasses. Sometimes we may like to prevent a class being further sub classed for security reasons. A class that cannot be subclassed is called a final class. This is achieved in Java using keyword final.
final class Aclass{} final class Bclass extends someclass

An attempt to inherit these classes will cause an error and the compiler will not allow it. Declaring a class final prevents any unwanted extensions to the class.

Final Method & Variables


Methods in a class can be protected from overriding methods in subclasses. Methods declared as final cannot have overriding methods in the subclasses. final variables are constant. You cannot assign any new value to them once you have declared them as final. Final variables must be assigned values while declaring them to be final.

final type variablename = value; final int Pass_Mark = 40; final int MINUTE_VAL = 60; final double Interest_Rate = 12.5;

Finalizer method
Java run time automatically garbage collect objects which are no longer required. But objects may hold other non-object resources such as file descriptors or window system fonts. Garbage collector cannot free these resources. In order to free these resources we must use finalizer method (Similar to destructors)

The finalizer method is simply finalize() and can be added to any class. Java calls that method whenever it is about to reclaim the space for that object. The finalize method should explicitly define the tasks to be performed.

Abstract Classes and Methods


We can indicate that a method must always be redefined in a subclass, thus making overriding compulsory. This can be done using modifier keyword abstract. In inheritance hierarchy when we go up in the hierarchy common properties of classes can be abstracted and defined in a single class.

When a class contains one or more abstract methods, it should be declared abstract. We must satisfy following conditions for abstract classes :
We cannot use abstract classes to instantiate objects directly e.g. Shape s = new Shape() The abstract methods of an abstract class must be defined in its subclass. We cannot declare abstract constructors or abstract static methods.

Вам также может понравиться