0% found this document useful (0 votes)
17 views17 pages

OBJECT CLASS, abstract class,final notes

Uploaded by

Praveen Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views17 pages

OBJECT CLASS, abstract class,final notes

Uploaded by

Praveen Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 17

THE OBJECT CLASS

The Object class is the parent class of all the classes in java by default (directly or indi-
rectly). The java.lang.Object class is the root of the class hierarchy. Some of the Object
class are Boolean, Math, Number, String etc.
Object

Boolean Character Number Math String StringBuffer

Byte Short Integer Long Float Double


Some of the important methods defined in Object class are listed below.
Object class Methods Description
boolean equals(Object) Returns true if two references point to the same object.
String toString() Converts object to String
void notify()
void notifyAll() Used in synchronizing threads
void wait()
void finalize() Called just before an object is garbage collected
Returns a new object that are exactly the same as the current
Object clone()
object
int hashCode() Returns a hash code value for the object.
Example:
public class Test
{
public static void main(String[] args)
{
/*hashcode is the unique number generated by JVM*/
Test t = new Test();
System.out.println(t);
System.out.println(t.toString()); // provides String representation of an Object
System.out.println(t.hashCode());
t = null; /*calling garbage collector explicitly to dispose system resources, perform
System.gc(); clean-up activities and minimize memory leaks*/

System.out.println(“end”);
}
protected void finalize() // finalize() is called just once on an object
{
System.out.println(“finalize method called”);
}
}
Sample Output:
Test@2a139a55
Test@2a139a55
705927765
end
finalize method called
In the above program, the default toString() method for class Object returns a string con-
sisting of the name of the class Test of which the object is an instance, the at-sign character
`@’, and the unsigned hexadecimal representation of the hash code of the object.
ABSTRACT CLASSES AND METHODS
Abstract class
A class that is declared as abstract is known as abstract class. It can have abstract and
non-abstract methods (method with body). It needs to be extended and its method imple-
mented. It cannot be instantiated.
Syntax:
abstract class classname
{
}
Abstract method
A method that is declared as abstract and does not have implementation is known as ab-
stract method. The method body will be defined by its subclass.
Abstract method can never be final and static. Any class that extends an abstract class
must implement all the abstract methods declared by the super class.
Note:
A normal class (non-abstract class) cannot have abstract methods.
Syntax:
abstract returntype functionname (); //No definition
Syntax for abstract class and method:
modifier abstract class className
{
//declare fields
//declare methods
abstract dataType methodName();
}
modifier class childClass extends className
{
dataType methodName()
{
}
}
Why do we need an abstract class?
Consider a class Animal that has a method sound() and the subclasses of it like Dog
Lion, Horse Cat etc. Since the animal sound differs from one animal to another, there is no
point to implement this method in parent class. This is because every child class must
override this method to give its own implementation details, like Lion class will say
“Roar” in this method and Horse class will say “Neigh”.
So when we know that all the animal child classes will and should override this method,
then there is no point to implement this method in parent class. Thus, making this method
abstract would be the good choice. This makes this method abstract and all the subclasses
to implement this method. We need not give any implementation to this method in parent
class.
Since the Animal class has an abstract method, it must be declared as abstract.
Now each animal must have a sound, by making this method abstract we made it
compul- sory to the child class to give implementation details to this method. This way we
ensure that every animal has a sound.
Rules
1. Abstract classes are not Interfaces.
2. An abstract class may have concrete (complete) methods.
3. An abstract class may or may not have an abstract method. But if any class has one or
more abstract methods, it must be compulsorily labeled abstract.
4. Abstract classes can have Constructors, Member variables and Normal methods.
5. Abstract classes are never instantiated.
6. For design purpose, a class can be declared abstract even if it does not contain any
abstract methods.
7. Reference of an abstract class can point to objects of its sub-classes thereby achieving
run-time polymorphism Ex: Shape obj = new Rectangle();
8. A class derived from the abstract class must implement all those methods that are
declared as abstract in the parent class.
9. If a child does not implement all the abstract methods of abstract parent class, then
the child class must need to be declared abstract as well.
Example 1
//abstract parent class
abstract class Animal
{
//abstract method
public abstract void sound();
}
//Lion class extends Animal
class public class Lion extends
Animal
{
public void sound()
{
System.out.println(“Roars”);
}
public static void main(String args[])
{
Animal obj = new Lion();
obj.sound();
}
}

Output:
Roars
In the above code, Animal is an abstract class and Lion is a concrete class.
Example 2
abstract class Bank
{
abstract int getRateOfInterest();
}
class SBI extends Bank
{
int getRateOfInterest()
{
return 7;
}
}
class PNB extends Bank
{
int getRateOfInterest()
{
return 8;
}
}
public class TestBank
{
public static void main(String args[])
{
Bank b=new SBI();//if object is PNB, method of PNB will be invoked
int interest=b.getRateOfInterest();
System.out.println(“Rate of Interest is: “+interest+” %”);
b=new PNB();
System.out.println(“Rate of Interest is: “+b.getRateOfInterest()+” %”);
}
}
Inheritance and Interfaces  2.19

Output:
Rate of Interest is: 7 %
Rate of Interest is: 8 %
Abstract class with concrete (normal) method
Abstract classes can also have normal methods with definitions, along with abstract
methods.
Sample Code:
abstract class A
{
abstract void callme();
public void normal()
{
System.out.println(“this is a normal (concrete) method.”);
}
}
public class B extends A
{
void callme()
{
System.out.println(“this is an callme (abstract) method.”);
}
public static void main(String[] args)
{
B b = new B();
b.callme();
b.normal();
}
}
Output:
this is an callme (abstract) method.
this is a normal (concrete) method.
Observations about abstract classes in Java
1. An instance of an abstract class cannot be created; But, we can have
references of abstract class type though.
Sample Code:
abstract class Base
{
abstract void fun();
}
class Derived extends Base
{
void fun()
{
System.out.println(“Derived fun() called”);
}
}
public class Main
{
public static void main(String args[])
{
// Base b = new Base(); Will lead to error
// We can have references of Base type.
Base b = new Derived();
b.fun();
}
}
Output:
Derived fun() called
2. An abstract class can contain constructors in Java. And a constructor of
ab- stract class is called when an instance of a inherited class is created.
Sample Code:
abstract class Base
{
Base()
{
System.out.println(“Within Base Constructor”);
}
abstract void fun();
}
class Derived extends Base
{
Derived()
{
System.out.println(“Within Derived Constructor”);
}
void fun()
{
System.out.println(“ Within Derived fun()”);
}
}
public class Main
{
public static void main(String args[])
{
Derived d = new Derived();
}
}
Output:
Within Base Constructor
Within Derived
Constructor
3. We can have an abstract class without any abstract method. This allows us to
create classes that cannot be instantiated, but can only be inherited.
Sample Code:
abstract class Base
{
void fun()
{
System.out.println(“Within Base fun()”);
}
}
class Derived extends Base
{
}
public class Main
{
public static void main(String args[])
{
Derived d = new Derived();
d.fun();
}
}
Output:
Within Base fun()
4. Abstract classes can also have final methods (methods that cannot be
overridden).
Sample Code:
abstract class Base
{
final void fun()
{
System.out.println(“Within Derived fun()”);
}
}
class Derived extends Base
{
}
public class Main
{
public static void main(String args[])
{
Base b = new Derived();
b.fun();
}
}
Output:
Within Derived fun()
FINAL METHODS AND CLASSES
The final keyword in java is used to restrict the user. The java final keyword can be ap-
plied to:
 variable
 method
 class

Java final variable - To prevent constant variables


Java final method - To prevent method overriding
Java final class - To prevent inheritance
Figure: Uses of final in java

Java final variable


The final keyword can be applied with the variables, a final variable that have no value
it is called blank final variable or uninitialized final variable. It can be initialized in the con-
structor only. The blank final variable can be static also which will be initialized in the
static block only.
Sample Code:
A final variable speedlimit is defined within a class Vehicle. When we try to change the
value of this variable, we get an error. This is due to the fact that the value of final variable
cannot be changed, once a value is assigned to it.
public class Vehicle
{
final int speedlimit=60;//final variable
void run()
{
speedlimit=400;
}
public static void main(String args[])
{
Vehicle obj=new
Vehicle(); obj.run();
}
}
Output:
/Vehicle.java:6: error: cannot assign a value to final variable speedlimit
speedlimit=400;
^
1 error
Blank final variable
A final variable that is not initialized at the time of declaration is known as blank final
variable. We must initialize the blank final variable in constructor of the class otherwise it will
throw a compilation error.
Sample Code:
public class Vehicle
{
final int speedlimit; //blank final variable
void run()
{
}
public static void main(String args[])
{
Vehicle obj=new
Vehicle(); obj.run();
}
}
Output:
/Vehicle.java:3: error: variable speedlimit not initialized in the default
constructor final int speedlimit; //blank final variable
^
1 error
Java Final Method
A Java method with the final keyword is called a final method and it cannot be overridden
in the subclass.
In general, final methods are faster than non-final methods because they are not required
to be resolved during run-time and they are bonded at compile time.
Sample Code:
class XYZ
{
final void demo()
{
System.out.println(“XYZ Class Method”);
}
}
public class ABC extends XYZ
{
void demo()
{
System.out.println(“ABC Class Method”);
}
public static void main(String args[])
{
ABC obj= new
ABC(); obj.demo();
}
}
Output:
/ABC.java:11: error: demo() in ABC cannot override demo() in
XYZ void demo()
^
overridden method is final
1 error
The following code will run fine as the final method demo() is not overridden. This
shows that final methods are inherited but they cannot be overridden.
Sample Code:
class XYZ
{
final void demo()
{
System.out.println(“XYZ Class Method”);
}
}
public class ABC extends XYZ
{
public static void main(String args[])
{
ABC obj= new
ABC(); obj.demo();
}
}
Output:
XYZ Class Method
Points to be remembered while using final methods:
 Private methods of the superclass are automatically considered to be final.
 Since the compiler knows that final methods cannot be overridden by a subclass, so
these methods can sometimes provide performance enhancement by removing calls
to final methods and replacing them with the expanded code of their declarations at
each method call location.
 Methods made inline should be small and contain only few lines of code. If it grows
in size, the execution time benefits become a very costly affair.
 A final’s method declaration can never change, so all subclasses use the same method
implementation and call to one can be resolved at compile time. This is known
as static binding.
Java Final Class
 Final class is a class that cannot be extended i.e. it cannot be inherited.
 A final class can be a subclass but not a superclass.
 Declaring a class as final implicitly declares all of its methods as final.
 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.
 Several classes in Java are final e.g. String, Integer, and other wrapper classes.
 The final keyword can be placed either before or after the access specifier.
Syntax:
final public class A public final class A

{ {
OR
//code //code

} }
Sample Code:
final class XYZ
{
}

public class ABC extends XYZ


{
void demo()
{
System.out.println(“My Method”);
}
public static void main(String args[])
{
ABC obj= new
ABC(); obj.demo();
}
}
Output:
/ABC.java:5: error: cannot inherit from final
XYZ public class ABC extends XYZ
^
1 error
Important points on final in Java
 Final keyword can be applied to a member variable, local variable, method or class
in Java.
 Final member variable must be initialized at the time of declaration or inside the
constructor, failure to do so will result in compilation error.
 We cannot reassign value to a final variable in Java.
 The local final variable must be initialized during declaration.
 A final method cannot be overridden in Java.
 A final class cannot be inheritable in Java.
 Final is a different than finally keyword which is used to Exception handling in
Java.
 Final should not be confused with finalize() method which is declared in Object class
and called before an object is a garbage collected by JVM.
 All variable declared inside Java interface are implicitly final.
 Final and abstract are two opposite keyword and a final class cannot be abstract in
Java.
 Final methods are bonded during compile time also called static binding.
 Final variables which are not initialized during declaration are called blank final
variable and must be initialized in all constructor either explicitly or by calling
this(). Failure to do so compiler will complain as “final variable (name) might not be
initialized”.
 Making a class, method or variable final in Java helps to improve performance because JVM
gets an opportunity to make assumption and optimization.

You might also like