What's the difference between importing and
extending a class?
Those are two very different things.
Importing a class, is making it so you can use that class without needing to qualify the full name
in the current class you are writing.
import java.util.Scanner
// now you can use the Scanner class in your code like so:
Scanner stdin = new Scanner(System.in);
// instead of having to do
java.util.Scanner stdin = new java.util.Scanner(System.in);
Extending a class is creating a new class that is a subclass of some other class. This will allow
you to add or change functionality of the class you are extending.
// this is a very contrived example
public class EmptyList extends ArrayList {
@Override
public boolean add(Object o){
return false; // will not add things to a list
}
}
//////// Another One//
Import doesn't change your program, it just allows you to write the short form of declaring a
class. In your own class you can use any other class from any package within the Java library.
Lets say you want to use the Scanner class to take input from the keyboard. Instead of writing
java.util.Scanner sc = new java.util.Scanner(System.in);, you can simply write
Scanner sc = new Scanner(System.in);.
If you import the package or a package followed by the class name at the top of your class which
is import java.util.*; or import java.util.Scanner;
Extending a class is not as simple as importing a class. When you extend a class you are adding
all instances (fields) and methods of the extended class into your own class. In other words, you
have access to all of the fields and methods of the extended class.
Import refers to Has a relationship. With keyword new.
Extend refers to IS a relationship. With keyword extends
Overriding Rules
 The argument list must exactly same that of the overridden method. If they don't match, you
can end up with an overloaded method.
 The return type must be the same as, or a subtype of, the return type declared in the original
overridden method in the superclass (also called covariant return type).
 Instance methods can be overridden only if they are inherited by the subclass.
 A subclass within the same package as the instance's superclass can override any superclass
method that is not marked private or final. A subclass in a different package can override only
those non-final methods marked public or protected (since protected methods are inherited by
the subclass).
 The overriding method can throw any unchecked (runtime) exception, regardless of whether
the overridden method declares the exception.
 The overriding method must not throw checked exceptions that are new or broader than those
declared by the overridden method. For example, a method that declares a
FileNotFoundException cannot be overridden by a method that declares a SQLException,
Exception, or any other non-runtime exception unless it's a subclass of FileNotFoundException.
 You cannot override a method marked final.
 You cannot override a method marked static.
 If a class is not inherited, you cannot override its methods.
Overloading Rules
 You can overload a method by changing its signature. method signature is made of number of
arguments, type of arguments and order of arguments.
 Return type is not a part of method signature, so changing method return type means no
overloading unless you change argument with return type.
 A method can be overloaded in the same class or in a subclass. if class A defines a show(int i)
method, the subclass B could define a show(String s) method without overriding the superclass
version that takes an int. So two methods with the same name but in different classes can still
be considered overloaded, if the subclass inherits one version of the method and then declares
another overloaded version in its class definition.
Difference Between Overloading And Overriding
Overloading Overriding
Overloaded methods let you reuse the same method
name in a class, but with different arguments and
optionally, a different return type
Any time you have a class that inherits a
method from a superclass, you have the
opportunity to override the method
Overloaded methods must change the argument list. The argument list must be same.
Overloaded methods can change the return type.
The return type must be same in jdk 1.4 but in
jdk 1.5 it should be co-varient returns.
Overloaded methods can change the access modifier.
The access level can't be less restrictive in
overridden method.
Overloaded methods can declare new or broader
checked exceptions.
Can throw any unchecked exception by
overriding.
The overridden method can throw any sub
type or same type exception of overriding
method.
A method can be overloaded in the same class or in a
subclass.
Without inheritance no overriding.
Can overload final and static methods.
You cannot override a method marked final
and static.
Access Modifiers:
Private access modifier is the most restrictive access level. Class and interfaces cannot be
private.
Variables that are declared private can be accessed outside the class if public getter methods are
present in the class.
Using the private modifier is the main way that an object encapsulates itself and hide data from
the outside world.
The following rules for inherited methods are enforced:
 Methods declared public in a superclass also must be public in all subclasses.
 Methods declared protected in a superclass must either be protected or public in
subclasses; they cannot be private.
 Methods declared without access control (no modifier was used) can be declared more
private in subclasses.
 Methods declared private are not inherited at all, so there is no rule for them.
Access Control Modifiers:
Java provides a number of access modifiers to set access levels for classes, variables, methods
and constructors. The four access levels are:
 Visible to the package, the default. No modifiers are needed.
 Visible to the class only (private).
 Visible to the world (public).
 Visible to the package and all subclasses (protected).
Non Access Modifiers:
Java provides a number of non-access modifiers to achieve many other functionality.
 The static modifier for creating class methods and variables
 The final modifier for finalizing the implementations of classes, methods, and variables.
 The abstract modifier for creating abstract classes and methods.
 The synchronized and volatile modifiers, which are used for threads.
NOTES:--
a) static variable, by default JVM intializes the static variables to default value as per
the data type.
b) The most common example of a static member is main(). main() is declared as static
because it must be called before any objects exist.
c) Methods declared as static have several restrictions:
 They can only call other static methods.
 They must only access static data.
 They cannot refer to this or super in any way.
 Static methods can not be override by subclass, This doesn't mean they can't be redefined
in a subclass, But redefining and overriding aren't the same thing.
d) Static Block
 Static block is guaranteed to be executed only once by the JVM at the time of loading that
particular class.
 Remember, You can access only static members from static block.
Use of Static Block
 Static block are very useful when you want to perform some initialization or loading
something before the actual program execution started.
 For example, You can use static block to load the Database Driver or To load the
network based resource etc..
 You can not execute the static block more than once, Its guaranteed by JVM that when
Its belonging class loaded, It would execute the static block first (you don't need & You
can't invoke the static block by yourself from code).
 You can define multiple static blocks in same class, JVM won't mind it :)
e) What is final variable - Use of final variable
 When you precede variable declaration with final means that once the value assigned to that
variable, It cann't be changed.
 In other words, final variable behaves as constant through out your application.
Best practices - Use of final variables
 Its always best if you make your method arguments as final which makes your program more
readable and less error prone and easy to debug.
 final variables are best to use in multi threading application as its immutable (It can't
be changed after initialized it once), Less error prone code.
 Moreover, final variables are accessible inside inner class also.
What is final method - Using final to prevent overriding
 The final keyword prevents a method from being overridden in a subclass, and is often used
to enforce the API functionality of a method.
 For example, the Thread class has a method called isAlive() that checks whether a thread is still
active.
 If you extend the Thread class, though, there is really no way that you can correctly implement
this method yourself (it uses native code, for one thing), so the designers have made it final.
 Just as you can't subclass the String class (because we need to be able to trust in the behavior
of a String object), you can't override many of the methods in the core class libraries.
 This can't-be-overridden restriction provides for safety and security, but you should use it with
great caution.
 Preventing a subclass from overriding a method stifles many of the benefits of OO including
extensibility through polymorphism.
What is final class - Using final to prevent inheritance
 Sometimes you will want to prevent a class from being inherited. To do this, precede the class
declaration with final.
 Declaring a class as final implicitly declares all of its methods as final, too.
 As you might expect, it is illegal to declare a class as both abstract and final since an abstract
class is incomplete by itself and relies upon its subclasses to provide complete
implementations.
Why would you ever mark a class final?
 You should make a final class only if you need an absolute guarantee that none of the
methods in that class will ever be overridden.
 If you are deeply dependent on the implementations of certain methods, then using final gives
you the security that nobody can change the implementation out from under you.
 You'll notice many classes in the Java core libraries are final.
 For example, the String class cannot be subclassed.
 So use final for safety, but only when you are certain that your final class has indeed said all
that ever needs to be said in its methods.
 Marking a class final means your class can not ever be improved upon or even specialized by
another programmer.
f) We can’t declare a constructor final as it can’t be inherited.
g) We can initialize a blank final variable in constructor only. And we can initialize a static
blank final variable in static block only.
Important points about Abstract Class
 You can not create instance of abstract class.
 Abstract class can have both abstract and non-abstract methods.
 Abstract class with no abstract method is also valid.
 You can't mark a class as both abstract and final because they have nearly opposite meanings.
An abstract class must be subclassed, whereas a final class must not be subclassed.
 If you see this combination of abstract and final modifiers, used for a class or method
declaration, the code will not compile.
 Abstract class promotes Generalization and Interface promotes Realization.
 Be careful for when to use Abstract class and When to use Interface.
 By putting nonabstract methods in an abstract class, you ultimately make all concrete (non
abstract) subclasses to inherit functionality, and need to implement only the methods that
define subclass specific behavior

Core java by amit

  • 1.
    What's the differencebetween importing and extending a class? Those are two very different things. Importing a class, is making it so you can use that class without needing to qualify the full name in the current class you are writing. import java.util.Scanner // now you can use the Scanner class in your code like so: Scanner stdin = new Scanner(System.in); // instead of having to do java.util.Scanner stdin = new java.util.Scanner(System.in); Extending a class is creating a new class that is a subclass of some other class. This will allow you to add or change functionality of the class you are extending. // this is a very contrived example public class EmptyList extends ArrayList { @Override public boolean add(Object o){ return false; // will not add things to a list } } //////// Another One// Import doesn't change your program, it just allows you to write the short form of declaring a class. In your own class you can use any other class from any package within the Java library. Lets say you want to use the Scanner class to take input from the keyboard. Instead of writing java.util.Scanner sc = new java.util.Scanner(System.in);, you can simply write Scanner sc = new Scanner(System.in);. If you import the package or a package followed by the class name at the top of your class which is import java.util.*; or import java.util.Scanner; Extending a class is not as simple as importing a class. When you extend a class you are adding all instances (fields) and methods of the extended class into your own class. In other words, you have access to all of the fields and methods of the extended class. Import refers to Has a relationship. With keyword new. Extend refers to IS a relationship. With keyword extends
  • 2.
    Overriding Rules  Theargument list must exactly same that of the overridden method. If they don't match, you can end up with an overloaded method.  The return type must be the same as, or a subtype of, the return type declared in the original overridden method in the superclass (also called covariant return type).  Instance methods can be overridden only if they are inherited by the subclass.  A subclass within the same package as the instance's superclass can override any superclass method that is not marked private or final. A subclass in a different package can override only those non-final methods marked public or protected (since protected methods are inherited by the subclass).  The overriding method can throw any unchecked (runtime) exception, regardless of whether the overridden method declares the exception.  The overriding method must not throw checked exceptions that are new or broader than those declared by the overridden method. For example, a method that declares a FileNotFoundException cannot be overridden by a method that declares a SQLException, Exception, or any other non-runtime exception unless it's a subclass of FileNotFoundException.  You cannot override a method marked final.  You cannot override a method marked static.  If a class is not inherited, you cannot override its methods. Overloading Rules  You can overload a method by changing its signature. method signature is made of number of arguments, type of arguments and order of arguments.  Return type is not a part of method signature, so changing method return type means no overloading unless you change argument with return type.  A method can be overloaded in the same class or in a subclass. if class A defines a show(int i) method, the subclass B could define a show(String s) method without overriding the superclass version that takes an int. So two methods with the same name but in different classes can still be considered overloaded, if the subclass inherits one version of the method and then declares another overloaded version in its class definition. Difference Between Overloading And Overriding Overloading Overriding Overloaded methods let you reuse the same method name in a class, but with different arguments and optionally, a different return type Any time you have a class that inherits a method from a superclass, you have the opportunity to override the method Overloaded methods must change the argument list. The argument list must be same. Overloaded methods can change the return type. The return type must be same in jdk 1.4 but in jdk 1.5 it should be co-varient returns.
  • 3.
    Overloaded methods canchange the access modifier. The access level can't be less restrictive in overridden method. Overloaded methods can declare new or broader checked exceptions. Can throw any unchecked exception by overriding. The overridden method can throw any sub type or same type exception of overriding method. A method can be overloaded in the same class or in a subclass. Without inheritance no overriding. Can overload final and static methods. You cannot override a method marked final and static. Access Modifiers: Private access modifier is the most restrictive access level. Class and interfaces cannot be private. Variables that are declared private can be accessed outside the class if public getter methods are present in the class. Using the private modifier is the main way that an object encapsulates itself and hide data from the outside world. The following rules for inherited methods are enforced:  Methods declared public in a superclass also must be public in all subclasses.  Methods declared protected in a superclass must either be protected or public in subclasses; they cannot be private.  Methods declared without access control (no modifier was used) can be declared more private in subclasses.  Methods declared private are not inherited at all, so there is no rule for them. Access Control Modifiers:
  • 4.
    Java provides anumber of access modifiers to set access levels for classes, variables, methods and constructors. The four access levels are:  Visible to the package, the default. No modifiers are needed.  Visible to the class only (private).  Visible to the world (public).  Visible to the package and all subclasses (protected). Non Access Modifiers: Java provides a number of non-access modifiers to achieve many other functionality.  The static modifier for creating class methods and variables  The final modifier for finalizing the implementations of classes, methods, and variables.  The abstract modifier for creating abstract classes and methods.  The synchronized and volatile modifiers, which are used for threads. NOTES:-- a) static variable, by default JVM intializes the static variables to default value as per the data type. b) The most common example of a static member is main(). main() is declared as static because it must be called before any objects exist. c) Methods declared as static have several restrictions:  They can only call other static methods.  They must only access static data.  They cannot refer to this or super in any way.  Static methods can not be override by subclass, This doesn't mean they can't be redefined in a subclass, But redefining and overriding aren't the same thing. d) Static Block  Static block is guaranteed to be executed only once by the JVM at the time of loading that particular class.  Remember, You can access only static members from static block. Use of Static Block  Static block are very useful when you want to perform some initialization or loading
  • 5.
    something before theactual program execution started.  For example, You can use static block to load the Database Driver or To load the network based resource etc..  You can not execute the static block more than once, Its guaranteed by JVM that when Its belonging class loaded, It would execute the static block first (you don't need & You can't invoke the static block by yourself from code).  You can define multiple static blocks in same class, JVM won't mind it :) e) What is final variable - Use of final variable  When you precede variable declaration with final means that once the value assigned to that variable, It cann't be changed.  In other words, final variable behaves as constant through out your application. Best practices - Use of final variables  Its always best if you make your method arguments as final which makes your program more readable and less error prone and easy to debug.  final variables are best to use in multi threading application as its immutable (It can't be changed after initialized it once), Less error prone code.  Moreover, final variables are accessible inside inner class also. What is final method - Using final to prevent overriding  The final keyword prevents a method from being overridden in a subclass, and is often used to enforce the API functionality of a method.  For example, the Thread class has a method called isAlive() that checks whether a thread is still active.  If you extend the Thread class, though, there is really no way that you can correctly implement this method yourself (it uses native code, for one thing), so the designers have made it final.  Just as you can't subclass the String class (because we need to be able to trust in the behavior of a String object), you can't override many of the methods in the core class libraries.  This can't-be-overridden restriction provides for safety and security, but you should use it with great caution.  Preventing a subclass from overriding a method stifles many of the benefits of OO including extensibility through polymorphism. What is final class - Using final to prevent inheritance  Sometimes you will want to prevent a class from being inherited. To do this, precede the class declaration with final.  Declaring a class as final implicitly declares all of its methods as final, too.  As you might expect, it is illegal to declare a class as both abstract and final since an abstract class is incomplete by itself and relies upon its subclasses to provide complete implementations.
  • 6.
    Why would youever mark a class final?  You should make a final class only if you need an absolute guarantee that none of the methods in that class will ever be overridden.  If you are deeply dependent on the implementations of certain methods, then using final gives you the security that nobody can change the implementation out from under you.  You'll notice many classes in the Java core libraries are final.  For example, the String class cannot be subclassed.  So use final for safety, but only when you are certain that your final class has indeed said all that ever needs to be said in its methods.  Marking a class final means your class can not ever be improved upon or even specialized by another programmer. f) We can’t declare a constructor final as it can’t be inherited. g) We can initialize a blank final variable in constructor only. And we can initialize a static blank final variable in static block only. Important points about Abstract Class  You can not create instance of abstract class.  Abstract class can have both abstract and non-abstract methods.  Abstract class with no abstract method is also valid.  You can't mark a class as both abstract and final because they have nearly opposite meanings. An abstract class must be subclassed, whereas a final class must not be subclassed.  If you see this combination of abstract and final modifiers, used for a class or method declaration, the code will not compile.  Abstract class promotes Generalization and Interface promotes Realization.  Be careful for when to use Abstract class and When to use Interface.  By putting nonabstract methods in an abstract class, you ultimately make all concrete (non abstract) subclasses to inherit functionality, and need to implement only the methods that define subclass specific behavior