JAVA U2
JAVA U2
UNIT II
The class is at the core of Java. It is the logical construct upon which the entire Java language
is built because it defines the shape and nature of an object.
As such, the class forms the basis for object-oriented programming in Java. Any concept you wish
to implement in a Java program must be encapsulated within a class. Because the class is so
fundamental to Java.
Class Fundamentals:
The classes created in the preceding chapters primarily exist simply to encapsulate the
main( )method, which has been used to demonstrate the basics of the Java syntax.
Perhaps the most important thing to understand about a class is that it defines a new data
type, defined, this new type can be used to create objects of that type.
Because an object is an instance of a class, you will often see the two words object and instance
used interchangeably.
When you define a class, you declare its exact form and nature. You do this by specifying the
data that it contains and the code that operates on that data. While very simple classes may
contain only code or only data, most real-world classes contain both. As you will see, a class’
code defines the interface to its data.
A class is declared by use of the class keyword. The classes that have been used up to this
point are actually very limited examples of its complete form. Classes can (and usually do) get
much more complex. Asimplified general form of a class definition is shown here:
class classname {
type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;
type methodname1(parameter-list) {
// body of method
}
JAVA PROGRAMMING
type methodname2(parameter-list) {
// body of method
// ...
type methodnameN(parameter-list) {
// body of method
The data, or variables, defined within a class are called instance variables. The code is
contained within methods. Collectively, the methods and variables defined within a class are
called members of the class. In most classes, the instance variables are acted upon and
accessed by the methods defined for that class. Thus, as a general rule, it is the methods that
determine how a class’ data can be used.
JAVA PROGRAMMING
Variables defined within a class are called instance variables because each instance of the class
(that is, each object of the class) contains its own copy of these variables. Thus, the data for one
object is separate and unique from the data for another.
All methods have the same general form as main( ), which we have been using thus far.
However, most methods will not be specified as static or public.
Notice that the general form of a class does not specify a main( )method. Java classes do not
need to have a main( ) method. You only specify one if that class is the starting point for your
program. Further, applets don’t require a main( ) method at all.
The Bicycle class uses the following lines of code to define its fields:
The fields of Bicycle are named cadence, gear, and speed and are all of data type integer (int).
The public keyword identifies these fields as public members, accessible by any object that can
access the class.
A Simple Class:
Let’s begin our study of the class with a simple example. Here is a class called Box that defines
class Box {
double width;
JAVA PROGRAMMING
double height;
double depth;
class BoxDemo2 {
double vol;
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
instance variables */
JAVA PROGRAMMING
mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;
Volume is 3000.0
Volume is 162.0
JAVA PROGRAMMING
As you can see, mybox1’s data is completely separate from the data contained in mybox2.
As stated, a class defines a new type of data. In this case, the new data type is called Box.
To actually create a Box object, you will use a statement like the following:
After this statement executes, mybox will be an instance of Box. Thus, it will have
“physical” reality. For the moment, don’t worry about the details of this statement.
To access these variables, you will use the dot (.) operator. The dot operator links the
name of the object with the name of an instance variable.
For example, to assign the width variable of mybox the value 100, you would use the following
statement:
mybox.width = 100;
This statement tells the compiler to assign the copy of width that is contained within the mybox
object the value of 100.
In general, you use the dot operator to access both the instance variables and the
methods within an object.
You should call the file that contains this program BoxDemo2.java, because the main()
method is in the class called BoxDemo2, not the class called Box.
JAVA PROGRAMMING
When you compile this program, you will find that two .class files have been created, one
for Box and one for BoxDemo2.
The Java compiler automatically puts each class into its own .class file. It is not necessary
for both the Box and the BoxDemo2 class to actually be in the same source file. You could
put each class in its own file, called Box.java and BoxDemo2.java, respectively.
To run this program, you must execute BoxDemo2.class. When you do, you will see the
following output:
Volume is 3000.0
Volume is 162.0
As stated earlier, each object has its own copies of the instance variables.
This means that if you have two Box objects, each has its own copy of depth, width, and height.
It is important to understand that changes to the instance variables of one object have no effect
on the instance variables of another.
Declaring Objects
An object is an instance of a class. An object is known by a name and every object contains a
state. The state is determined by the values of attributes (variables). The state of an object can
JAVA PROGRAMMING
be changed by calling methods on it. The sequence of state changes represents the behavior of
the object.
An object is a software entity (unit) that combines a set of data with a set of operations to
manipulate that data.
As just explained, when you create a class, you are creating a new data type. You can use
this type to declare objects of that type.
First, you must declare a variable of the class type. This variable does not define an
object. Instead, it is simply a variable that can refer to an object.
Second, you must acquire an actual, physical copy of the object and assign it to that
variable. You can do this using the new operator.
Declaration: The code set in variable declarations that associate a variable name with an
object type.
Instantiation: The new keyword is a Java operator that creates the object.
Initialization: The new operator is followed by a call to a constructor, which initializes the
new object.
JAVA PROGRAMMING
The new operator dynamically allocates (that is, allocates at run time) memory for an object and
returns a reference to it. This reference is, more or less, the address in memory of the object
allocated by new. This reference is then stored in the variable. Thus, in Java, all class objects
must be dynamically allocated. Let’s look at the details of this procedure.
In the preceding sample programs, a line similar to the following is used to declare an object of
type Box:
This statement combines the two steps just described. It can be rewritten like this to show each
step more clearly:
The first line declares mybox as a reference to an object of type Box. After this line executes,
mybox contains the value null, which indicates that it does not yet point to an actual object.
Any attempt to use mybox at this point will result in a compile-time error. The next line allocates
an actual object and assigns a reference to it to mybox. After the second line executes, you can
use mybox as if it were a Box object. But in reality, mybox simply holds the memory address of
the actual Box object. The effect of these two lines of code is depicted in Figure.
JAVA PROGRAMMING
Object reference variables act differently than you might expect when an assignment takes
place. For example, what do you think the following fragment does?
Box b2 = b1;
You might think that b2 is being assigned a reference to a copy of the object referred to by b1.
That is, you might think that b1 and b2 refer to separate and distinct objects. However, this
would be wrong. Instead, after this fragment executes, b1 and b2 will both refer to the same
JAVA PROGRAMMING
object. The assignment of b1 to b2 did not allocate any memory or copy any part of the original
object. It simply makes b2 refer to the same object as does b1. Thus, any changes made to the
object through b2 will affect the object to which b1 is referring, since they are the same object.
Although b1 and b2 both refer to the same object, they are not linked in any other way.
For example, a subsequent assignment to b1 will simply unhook b1 from the original object
without affecting the object or affecting b2. For example:
Box b2 = b1;
// ...
b1 = null;
JAVA PROGRAMMING
Here, b1 has been set to null, but b2 still points to the original object.
REMEMBER: When you assign one object reference variable to another object reference variable,
you are not creating a copy of the object, you are only making a copy of the reference.
Access Modifiers:
There are two types of modifiers in java: access modifiers and non-access modifiers.
The access modifiers in java specifies accessibility (scope) of a data member, method,
constructor or class.
1. private
2. default
3. protected
4. public
There are many non-access modifiers such as static, abstract, synchronized, native, volatile,
transient etc.
1.private:
JAVA PROGRAMMING
Methods, Variables and Constructors that are declared private can only be accessed within the
declared class itself.
Private access modifier is the most restrictive access level. Class and interfaces cannot be
private.
Using the private modifier is the main way that an object encapsulates itself and hide data from
the outside world.
2.default:
If you don't use any modifier, it is treated as default bydefault. The default modifier is
accessible only within package.
3.protected:
The protected access modifier is accessible within package and outside the package but
through inheritance only.
The protected access modifier can be applied on the data member, method and constructor. It
can't be applied on the class.
4.public:
JAVA PROGRAMMING
The public access modifier is accessible everywhere. It has the widest scope among all other
modifiers.
Access Modifier within class within package outside package by subclass only outside package
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
Methods :
The only required elements of a method declaration are the method's return type, name, a pair
of parentheses, (), and a body between braces, {}.
1. Modifiers—such as public, private, and others you will learn about later.
2. The return type—the data type of the value returned by the method, or void if the method
does not return a value.
3. The method name—the rules for field names apply to method names as well, but the
convention is a little different.
4. The parameter list in parenthesis—a comma-delimited list of input parameters, preceded
by their data types, enclosed by parentheses, (). If there are no parameters, you must use
empty parentheses.
5. An exception list—to be discussed later.
6. The method body, enclosed between braces—the method's code, including the declaration
of local variables, goes here.
Modifiers, return types, and parameters will be discussed later in this lesson. Exceptions are
discussed in a later lesson.
JAVA PROGRAMMING
Definition: Two of the components of a method declaration comprise the method signature—
the method's name and the parameter types.
Naming a Method
Although a method name can be any legal identifier, code conventions restrict method names.
By convention, method names should be a verb in lowercase or a multi-word name that begins
with a verb in lowercase, followed by adjectives, nouns, etc. In multi-word names, the first letter
of each of the second and following words should be capitalized.
run
runFast
JAVA PROGRAMMING
getBackground
getFinalData
compareTo
setX
isEmpty
Typically, a method has a unique name within its class. However, a method might have the same
name as other methods due to method overloading.
You declare a method's return type in its method declaration. Within the body of the method,
you use the return statement to return the value.
JAVA PROGRAMMING
Any method declared void doesn't return a value. It does not need to contain a return statement,
but it may do so. In such a case, a return statement can be used to branch out of a control flow
block and exit the method and is simply used like this:
return;
If you try to return a value from a method that is declared void, you will get a compiler error.
Any method that is not declared void must contain a return statement with a corresponding
return value, like this:
returnValue;
The data type of the return value must match the method's declared return type; you can't
return an integer value from a method declared to return a boolean.
The getArea() method in the Rectangle Rectangle class that was discussed in the sections on
objects returns an integer:
This method returns the integer that the expression width*height evaluates to.
Parameters:
Parameters refers to the list of variables in a method declaration. Arguments are the actual
values that are passed in when the method is invoked. When you invoke a method, the
arguments used must match the declaration's parameters in type and order.
Parameter Types
You can use any data type for a parameter of a method or a constructor. This includes primitive
data types, such as doubles, floats, and integers.
Parameter Names
When you declare a parameter to a method or a constructor, you provide a name for that
parameter. This name is used within the method body to refer to the passed-in argument.
The name of a parameter must be unique in its scope. It cannot be the same as the name of
another parameter for the same method or constructor, and it cannot be the name of a local
variable within the method or constructor.
JAVA PROGRAMMING
parameter passing:
In general, there are two ways that a computer language can pass an argument to a
subroutine.
The first way is call-by-value. This approach copies the value of an argument into the formal
parameter of the subroutine. Therefore, changes made to the parameter of the subroutine have
no effect on the argument.
As you will see, Java uses both approaches, depending upon what is passed.
In Java, when you pass a primitive type to a method, it is passed by value. Thus, what occurs to
the parameter that receives the argument has no effect outside the method.
class Test {
JAVA PROGRAMMING
i *= 2;
j /= 2;
class CallByValue {
ob.meth(a, b);
As you can see, the operations that occur inside meth( ) have no effect on the values of a and b
used in the call; their values here did not change to 30 and 10.
When you pass an object to a method, the situation changes dramatically, because objects are
passed by what is effectively call-by-reference.
Keep in mind that when you create a variable of a class type, you are only creating a reference
to an object. Thus, when you pass this reference to a method, the parameter that receives it will
refer to the same object as that referred to by the argument. This effectively means that objects
are passed to methods by use of call-by-reference. Changes to the object inside the method do
affect the object used as an argument.
class Test {
int a, b;
Test(int i, int j) {
a = i;
b = j;
// pass an object
void meth(Test o) {
o.a *= 2;
o.b /= 2;
class CallByRef {
ob.meth(ob);
As you can see, in this case, the actions inside meth( ) have affected the object used as an
argument.
JAVA PROGRAMMING
As a point of interest, when an object reference is passed to a method, the reference itself is
passed by use of call-by-value. However, since the value being passed refers to an object, the
copy of that value will still refer to the same object that its corresponding argument does.
Note: When a primitive type is passed to a method, it is done by use of call-by-value. Objects are
implicitly passed by use of call-by-reference.
Overloading Methods
The Java programming language supports overloading methods, and Java can distinguish
between methods with different method signatures. This means that methods within a class can
have the same name if they have different parameter lists (there are some qualifications to this
that will be discussed in the lesson titled "Interfaces and Inheritance").
Suppose that you have a class that can use calligraphy to draw various types of data (strings,
integers, and so on) and that contains a method for drawing each data type. It is cumbersome to
use a new name for each method—for example, drawString, drawInteger, drawFloat, and so on.
In the Java programming language, you can use the same name for all the drawing methods but
pass a different argument list to each method. Thus, the data drawing class might declare four
methods named draw, each of which has a different parameter list.
...
public void draw(String s) {
...
}
public void draw(int i) {
...
}
public void draw(double f) {
...
}
public void draw(int i, double f) {
...
}
}
Overloaded methods are differentiated by the number and the type of the arguments passed
into the method. In the code sample, draw(String s) and draw(int i) are distinct and unique
methods because they require different argument types.
You cannot declare more than one method with the same name and the same number and type
of arguments, because the compiler cannot tell them apart.
JAVA PROGRAMMING
The compiler does not consider return type when differentiating methods, so you cannot declare
two methods with the same signature even if they have a different return type.
Note: Overloaded methods should be used sparingly, as they can make code much less
readable.
Constructors:
It can be tedious to initialize all of the variables in a class each time an instance is created.
Because the requirement for initialization is so common, Java allows objects to initialize
themselves when they are created. This automatic initialization is performed through the use of
a constructor.
A constructor initializes an object immediately upon creation. It has the same name as the class
in which it resides and is syntactically similar to a method. Once defined, the constructor is
automatically called immediately after the object is created, before the new operator completes.
Constructors look a little strange because they have no return type, not even void. This is
because the implicit return type of a class’ constructor is the class type itself.
You can rework the Box example so that the dimensions of a box are automatically initialized
when an object is constructed. To do so, replace setDim( ) with a constructor.
JAVA PROGRAMMING
Let’s begin by defining a simple constructor that simply sets the dimensions of each box to the
same values. This version is shown here:
class Box {
double width;
double height;
double depth;
Box() {
System.out.println("Constructing Box");
width = 10;
height = 10;
JAVA PROGRAMMING
depth = 10;
double volume() {
class BoxDemo6 {
double vol;
vol = mybox1.volume();
vol = mybox2.volume();
Constructing Box
Constructing Box
JAVA PROGRAMMING
Volume is 1000.0
Volume is 1000.0
As you can see, both mybox1 and mybox2 were initialized by the Box( ) constructor when they
were created. Since the constructor gives all boxes the same dimensions, 10 by 10 by 10, both
mybox1 and mybox2 will have the same volume. The println( ) statement inside Box( ) is for the
sake of illustration only.
Parameterized Constructors
While the Box( ) constructor in the preceding example does initialize a Box object, it is not very
useful—all boxes have the same dimensions. What is needed is a way to construct Box objects of
various dimensions. The easy solution is to add parameters to the constructor.
As you can probably guess, this makes them much more useful. For example, the following
version of Box defines a parameterized constructor that sets the dimensions of a box as specified
by those parameters. Pay special attention to how Box objects are created.
class Box {
JAVA PROGRAMMING
double width;
double height;
double depth;
width = w;
height = h;
depth = d;
double volume() {
class BoxDemo7 {
double vol;
vol = mybox1.volume();
vol = mybox2.volume();
Volume is 3000.0
Volume is 162.0
As you can see, each object is initialized as specified in the parameters to its constructor.
the values 10, 20, and 15 are passed to the Box( ) constructor when new creates the object.
Thus, mybox1’s copy of width, height, and depth will contain the values 10, 20, and 15,
respectively.
JAVA PROGRAMMING
Overloading Constructors:
Since Box( ) requires three arguments, it’s an error to call it without them.
What if you simply wanted a box and did not care (or know) what its initial dimensions were? Or,
what if you want to be able to initialize a cube by specifying only one value that would be used
for all three dimensions?
As the Box class is currently written, these other options are not available to you.
Fortunately, the solution to these problems is quite easy: simply overload the Box constructor so
that it handles the situations just described. Here is a program that contains an improved version
of Box that does just that:
*/
class Box {
double width;
JAVA PROGRAMMING
double height;
double depth;
width = w;
height = h;
depth = d;
Box() {
}
JAVA PROGRAMMING
Box(double len) {
double volume() {
class OverloadCons {
double vol;
vol = mybox1.volume();
vol = mybox2.volume();
vol = mycube.volume();
As you can see, the proper overloaded constructor is called based upon the parameters specified
when new is executed.
Recursion:
Java supports recursion. Recursion is the process of defining something in terms of itself. As it
relates to Java programming, recursion is the attribute that allows a method to call itself.
The classic example of recursion is the computation of the factorial of a number. The factorial of
a number N is the product of all the whole numbers between 1 and N.
class Factorial {
JAVA PROGRAMMING
int fact(int n) {
int result;
if(n==1) return 1;
result = fact(n-1) * n;
return result;
class Recursion {
Factorial of 3 is 6
Factorial of 4 is 24
Factorial of 5 is 120
Garbage Collection:
In java, garbage means unreferenced objects.
It is automatically done by the garbage collector so we don't need to make extra efforts.
1) By nulling a reference:
e=null;
3) By annonymous object:
new Employee();
finalize() method:
The finalize() method is invoked each time before the object is garbage collected. This method can be
used to perform cleanup processing. This method is defined in System class as:
Understanding static:
The static keyword in java is used for memory management mainly. We can apply java static
keyword with variables, methods, blocks and nested class. The static keyword belongs to the
class than instance of the class.
3. block
4. nested class
The static variable can be used to refer the common property of all objects (that is not
unique for each object) e.g. company name of employees,college name of students etc.
The static variable gets memory only once in class area at the time of class loading.
If you apply static keyword with any method, it is known as static method.
class Student9{
int rollno;
String name;
college = "BBDIT";
rollno = r;
name = n;
Student9.change();
s1.display();
s2.display();
s3.display();
}
JAVA PROGRAMMING
Test it Now
Output:111 Karan BBDIT
222 Aryan BBDIT
333 Sonoo BBDIT
class A2{
System.out.println("Hello main");
}
JAVA PROGRAMMING
Nested Classes
The Java programming language allows you to define a class within another class. Such a class is
called a nested class and is illustrated here:
class OuterClass {
...
class NestedClass {
...
}
}
Nested classes are divided into two categories: static and non-static. Nested classes that
are declared static are called static nested classes. Non-static nested classes are called inner
classes.
class OuterClass {
JAVA PROGRAMMING
...
static class StaticNestedClass {
...
}
class InnerClass {
...
}
}
As with class methods and variables, a static nested class is associated with its outer class. And
like static class methods, a static nested class cannot refer directly to instance variables or
methods defined in its enclosing class: it can use them only through an object reference.
Non static nested class is also known as inner class. It has access to all variables and methods of
outer class and may refer to them directly. But the reverse is not true, that is outer class cannot
directly access members of inner class. One more thing is an inner class must created and
instantiated within the scope of outer class only.
JAVA PROGRAMMING
Inheritance
Inheritance is the mechanism of deriving new class from old one, old class is knows as
superclass and new class is known as subclass. The subclass inherits all of its instances variables
and methods defined by the superclass and it also adds its own unique elements. Thus we can
say that subclass are specialized version of superclass.
Types of Inheritance:
1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance
5. Hybrid inheritance
6. Multipath inheritance
1.Single inheritance:
A SUPER CLASS A
EXTENDS
SUB CLASS B
B
JAVA PROGRAMMING
2.Multilevel Inheritance:
SUPER-CLASS
A
EXTENDS
SUB-CLASS
B
EXTENDS
C SUB-SUBCLASS
3.Hierarchical Inheritance:
SUPERCLASS
Figure
EXTENDS
4.Multiple Inheritance:
JAVA PROGRAMMING
Deriving one subclass from more than one super classes is called multiple inheritance.
INTERFACE1 INTERFACE2
A B
(Animal) (Bird)
IMPLEMENTS
SUBCLASS
5.Hybrid Inheritance:
A
HIERARCHICAL INHERITANCE
B C
D MULTIPLE INHERITANCE
6.Multipath Inheritance:
B C
JAVA PROGRAMMING
Benefits of Inheritance:
Increased reliability
Software reusability
Code sharing
To create software components
Consistency of interface
Polymorphism
Information hiding
Rapid prototyping
Increased Reliability: If a code is frequently executed then it will have very less amount of bugs,
compared to code that is not frequently executed.(error free code)
Software reusability: properties of a parent class can be inherited by a child class. But, it does
not require to rewrite the code of the inherited property in the child class. In OOPs, methods can
be written once but can be reused.
Code sharing: At one level of code sharing multiple projects or users can use a single class.
JAVA PROGRAMMING
Software components: Programmers can construct software components that are reusable using
inheritance.
Consistency of interfaces: when multiple classes inherit the behavior of a single super class all
those classes will now have the same behavior.
Polymorphism: Oops follows the bottom-up approach. And abstraction is high at top, these are
exhibit the different behaviors based on instances.
Rapid prototyping: By using the same code for different purposes, we can reduce the lengthy
code of the program.
Cost of inheritance:
Program size: If the cost of memory decreases, then the program size does not matter.
Instead of limiting the program sizes, there is a need to produce code rapidly that has high
quality and is also error-free.
Execution speed: The specialized code is much faster than the inherited methods that
manage the random subclasses.
Program complexity: Complexity of a program may be increased if inheritance is overused.
Message-passing: The cost of message passing is very less when execution speed is
considered.
Java provides many levels of protection to allow fine-grained control over the visibility of
variables and methods within classes, subclasses, and packages.
JAVA PROGRAMMING
Classes and packages are both means of encapsulating and containing the name space and
scope of variables and methods. Packages act as containers for classes and other subordinate
packages.
The class is Java’s smallest unit of abstraction. Because of the interplay between classes and
packages.
We can protect the data from unauthorized access. To do this ,we are using access specifiers.
An access specifier is a keyword that is used to specify how to access a member of a class or the
class itself. There are four access specifiers in java:
private: private members of a class are not available outside the class.
public: public members of a class are available anywhere outside the class.
protected: If you want to allow an element to be seen outside your current package, but only to
classes that subclass your class directly, then declare that element protected.
JAVA PROGRAMMING
default: if no access specifier is used then default specifier is used by java compiler.
Default members are available outside the class. Specification, it is visible to subclasses as well
as to other classes in the same package. This is the default access.
Super Uses:
Whenever a subclass needs to refer to its immediate super class, it can do so by the use of the
keyword super.
Use: Overriden methods allow Java to support Run-time polymorphism. This leads to Robustness
by Reusability.
super can be used to refer super class constructor as: super (values)
super can be used to refer super class constructor as: super (values)
JAVA PROGRAMMING
class Figure
double dim1;
double dim2;
Figure(double a,double b)
dim1=a;
dim2=b;
double area()
return 0;
}
JAVA PROGRAMMING
Rectangle(double a,double b)
super(a,b);
double area()
return dim1*dim2;
Triangle(double a,double b)
JAVA PROGRAMMING
super(a,b);
double area()
return dim1*dim2/2;
class FindAreas
Figure figref;
figref=r;
System.out.println("area is"+figref.area());
figref=t;
System.out.println("area is"+figref.area());
figref=f;
System.out.println("area is"+figref.area());
OUTPUT:
area is 45
area is 40
area is 0
JAVA PROGRAMMING
The second form of super acts somewhat like this, except that it always refers to the superclass
of the subclass in which it is used. This usage has the following general form:
super.member;
Here, member can be either a method or an instance variable. This second form of super is most
applicable to situations in which member names of a subclass hide members by the same name
in the superclass. Consider this simple class hierarchy:
class A {
int i;
class B extends A {
B(int a, int b) {
super.i = a; // i in A
JAVA PROGRAMMING
i = b; // i in B
void show() {
class UseSuper {
subOb.show();
i in superclass: 1
i in subclass: 2
JAVA PROGRAMMING
Although the instance variable i in B hides the i in A, super allows access to the i defined in the
superclass. As you will see, super can also be used to call methods that are hidden by a subclass.
import java.io.*;
class A
void display()
System.out.println("hi");
class B extends A
super.display();
JAVA PROGRAMMING
System.out.println("hello");
B b=new B();
b.display();
Output: hi
Hello
Hierarchical Abstraction
JAVA PROGRAMMING
Class Hierarchy
• A child class of one parent can be the parent of another child, forming class
hierarchies
Animal
Class Hierarchy
• Good class design puts all common features as high in the hierarchy as reasonable
• The class hierarchy determines how methods are executed
• inheritance is transitive
– An instance of class Parrot is also an instance of Bird, an instance of Animal, …, and an instance of
class Object
JAVA PROGRAMMING
• If no parent class is specified explicitly, the base class Object is implicitly inherited.
• All classes defined in Java, is a child of Object class, which provides minimal functionality guaranteed to
e common to all objects.
JAVA PROGRAMMING
1.equals(Object obj) Determine whether the argument object is the same as the
receiver.
3.hashCode() Returns a hash value for this object. Should be overridden when the equals method is
changed.
4.toString() Converts object into a string value. This method is also often overridden.
JAVA PROGRAMMING
Base class
extends
{ {
} }
JAVA PROGRAMMING
• super class object baseobj can be used to refer its sub class objects.
• For example, Two subobj=new Two;
• Baseobj=subobj // now its pointing to sub class