0% found this document useful (0 votes)
11 views23 pages

Sybcs Java Unit-3

The document provides an overview of classes and objects in Java, explaining that a class serves as a blueprint for creating objects, which are instances of classes with state and behavior. It details the components of a class, including data members, methods, and constructors, as well as access specifiers that control visibility. Additionally, it discusses the use of the 'this' keyword, method parameters, and the concept of constructors for object initialization.

Uploaded by

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

Sybcs Java Unit-3

The document provides an overview of classes and objects in Java, explaining that a class serves as a blueprint for creating objects, which are instances of classes with state and behavior. It details the components of a class, including data members, methods, and constructors, as well as access specifiers that control visibility. Additionally, it discusses the use of the 'this' keyword, method parameters, and the concept of constructors for object initialization.

Uploaded by

eagleab8005
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Core Java By Kadam R.

R
UNIT-III Classes, Objects and In Java variables or data members are called
fields and functions are called methods.
Methods Class creates objects and objects used methods
Introduction: Object is the physical as well as
to access data members.
logical entity where as class is the only logical
The keyword “class” is used to define a class. A
entity.
class is a user defined data type. Following is the
Class: Class is a blue print which is containing syntax of defining a class.
only list of variables and method and no memory is Syntax:
allocated for them. A class is a group of objects that
has common properties.
A class in java contains:
1. Data Member
2. Method
3. Constructor
4. Block
5. Class and Interface
Object: Object is a instance of class, object has
state and behaviors.
An Object in java has three characteristics: There is no semicolon at the end of the class.
State The definition of class creates only the new abstract
Behavior datatype.
Identity <ClassName> and <SuperClassName> are any
State: Represents data (value) of an object. valid java identifier. The keyword extends indicates
Behavior: Represents the behavior that the properties of the super class are extended to
(functionality) of an object such as deposit, the current class.
withdraw etc. E.g.
Identity: Object identity is typically
implemented via a unique ID. The value of the ID is
not visible to the external user. But, it is used
internally by the JVM to identify each object
uniquely.
Class is also can be used to achieve user defined
data types.
In real world many examples of object and class
like dog, cat, and cow are belong to animal’s class.
Each object has state and behaviors. For example a
dog has state – color, name, height, age as well as
behaviors – barking, eating, and sleeping.

Car, bike, truck these all are belongs to


vehicle class. These Objects have also different
states and behaviors. For Example car has state -
color, name, model, speed, Mileage. as we;; as
behaviors - distance travel Fields/Variables Declaration
Data is encapsulated in a class by placing data
Simple example of class and object related to girls fields inside the body of the class definition.
and boy's.

1. Defining a class
Java is a true object oriented programming
language therefore each variable and method must be
defined within a class. Methods and variables inside
the class are known as members.

-1-
Core Java By Kadam R.R
The class body must contain one or more
methods.

2. Creating objects
Once a class has been defined we can
create variables of that type known as objects. In
Java objects are created by using new operator.
The new operator allocates the memory at
runtime and support the dynamic nature of Java.
The following is the syntax of creating an object.
The variables inside the class are known as
instance variables because they are created whenever
an object of the class is instantiated. There is no
storage space is created for class in the memory.

Methods/functions Declaration
A class only data fields has no life. The objects
created by such a class can not respond to messages. Syntax:
We must therefore add methods that are necessary for
manipulating the data contained in the class. To E.g.
accessthe instance variables we have to include
methods in the class.
The general form of a method declaration is:

 It is important to understand that each


object has its own copy of instance
variables.
 A TestStudent class contains two variables
i.e. rollNo and name. The s1,s2 and s3
objects maintain separate copies of this
two variables as shown in following fig.

 This means that any changes to the variables of

Method declaration have four basic parts:


1. The name of the method.
2. The type of the value the method returns.
3. A list of parameters
4. The body of the method
If the method doesn’t return a value then void
is mention at the place of return type.
one object have no effect on the variables of
The parameter list always encloses within
another.
parenthesis, these parameters are separated by
commas.
The body of the method describes the The following is the example of Class and
operations to be performed. object.
class TestStudent
-2-
Core Java By Kadam R.R
{ {
int rollNo=101; Addition a=new Addition();
String name="Raj"; Subtraction s=new Subtraction();
void display() [Link]();
[Link]();
{
}
[Link]("Roll No: "+rollNo); }
[Link]("Name: "+name); O/P
} Addition : 30
public static void main(String[] args) Subtraction : 10
{
TestStudent s1=new TestStudent();
[Link]();
}
}
4. Access Specifiers /Access Modifiers
O/P However it may be necessary in some
situations to restrict the access to certain variables
Roll No: 101
and methods from outside the class. Java provides
Name: Raj
the visibility modifiers to the instance variables and
methods.
3. Multiple classes in a single program. Access specifiers make us to understand
A Java program may contain any number of classes but where to access the feature and where not to access
at most one class can be declared as public. the features. Access specifiers provides features
If there is a public class then the name of a accessing controlling mechanism among the classes
program and name of public class must be the same. If and interfaces.
there is no public class then we can use any name of Access specifiers are those which are applied
the program. before data members or methods of a class. In java
If a Java program contains more than one class programming we have four access specifiers they
then program name must be the same of a class which are:
contains main() method. 1. private
The following program shows how to create and 2. protected
use multiple classes in a single program. 3. public
class Addition 4. default (not a keyword)
{
int x=10; 1. private
int y=20; The private is an access modifier applicable
void add() for variables and methods only but not for
{ classes.
[Link]("Addition : "+(x+y)); Private Fields/variables and methods have
} the highest degree of protection.
} Private fields and methods are accessible
class Subtraction only within class. They can not be inherited by
{ subclass and therefore not accessible in
int x=20; subclasses.
int y=10; By mistake if we try to access private fields
void sub() outside the class then it gives compile time error.
{ Simple example of private modifier.
[Link]("Substraction : "+(x-y)); class TestA
} {
} private int data=40;
class MultiClassTest private void message()
{ {
public static void main(String[] args) [Link]("Hello Java");
-3-
Core Java By Kadam R.R
} public static void main(String[] args)
} {
public class TestB TestB obj=new TestB();
{ [Link]();
public static void main(String[] args) }
{ }
TestA obj=new TestA(); javac -d . [Link]
[Link]([Link]);//CE javac -d . [Link]
[Link]();//CE java [Link]
}
} O/P
In above example we try to access private variable Hello Java
and method of TestA class into TestB class, it gives
the compile time error.
javac [Link]
CE: data has private access in TestA 3. public
CE: message() has private access in TestA The public is a access specifier applicable
2. protected for variables, methods, constructors and classes.
The protected is a access specifiers applicable The public access modifier is accessible
for data members, methods and constructor but everywhere there is no restrictions. It has the
not for classes. widest scope among all other modifiers.
The protected access modifier is accessible The following example shows the use of
within package and outside the package but public modifier with variable, method and class.
through inheritance only. [Link]
Simple example of protected access modifier. package packTestX;
In this example, we have created the two public class TestX
packages mypack1 and mypack2. The TestA class of {
mypack1 package is public, so can be accessed from public int count=10;
outside the package. But message() method of this public void showMessage()
package is declared as protected, so it can be {
accessed from outside the class only through [Link]("In showMessage() of TestX");
inheritance. }
[Link] }
package mypack1; [Link]
public class TestA package packTestY;
{ import packTestX.*;
protected int data=40; class TestY
protected TestA() {
{ public static void main(String[] args)
} {
TestX t=new TestX();
protected void message() [Link]("[Link] : "+[Link]);
{ [Link]();
[Link]("Hello Java"); }
} }
} javac -d . [Link]
[Link] javac -d . [Link]
package mypack2; java [Link]
import mypack1.*; O/P
class TestB extends TestA [Link] : 10
{ In showMessage() of TestX
TestB() In the above example we have declared public
{ variable, public method and public class and
} accessing these from outside the package.
-4-
Core Java By Kadam R.R
public static void main(String[] args)
5. Use of ‘this’ Keyword {
“this” is a reference variable that refers to the Student s1=new Student(101,"Raj");
current object. It is a keyword in java language Student s2=new Student(102,"Ram");
represents current class object. [Link]();
this keyword can be used to refer current class [Link]();
instance variable. }
this keyword can be used to invoke current }
class method (implicitly). O/P
Why use this keyword ? Employee ID : 101
The main purpose of using this keyword is to Employee Name : Raj
differentiate the formal parameter and data members Employee ID : 102
of class, whenever the formal parameter and data Employee Name : Ram
members of the class are similar then JVM get
ambiguity (no clarity between formal parameter and The second use of “this” keyword is to invoke
member of the class) the current class method.
To differentiate between formal parameter You may invoke the method of the current class
and data member of the class, the data member of the by using the this keyword. If you don't use the this
class must be preceded by "this". keyword, compiler automatically adds this keyword
If local variables(formal arguments) and while invoking the method.
instance variables are different, there is no need to Syntax
use this keyword. [Link]();
E.g.
[Link]();
[Link]();

this() can be used to invoked current class


constructor.
The this() constructor call can be used to
invoke the current class constructor (constructor
chaining).
This approach is better if you have many
constructors in the class and want to reuse that
constructor.
Note: If any variable is preceded by "this" JVM The following program shows the use of this()
treated that variable as class variable. method
Following example shows the use of “this” keyword class Student13
class Student {
{ int id;
int emp_id; String name;
String emp_name; Student13()
Student(int emp_id, String emp_name) {
{ [Link]("default constructor is invoked");
this.emp_id=emp_id; }
this.emp_name=emp_name; Student13(int id,String name)
} {
void display() this ();
{ [Link] = id;
[Link]("Emp ID : "+emp_id); [Link] = name;
[Link]("Emp Name : "+emp_name); }
} void display()
} {
class TestThis [Link](id+" "+name);
{ }
-5-
Core Java By Kadam R.R
public static void main(String args[]) parameter. The situation is different for object
{ reference parameters. You can easily implement a
Student13 e1 = new Student13(111,"karan"); method that triples the salary of an employee.
Student13 e2 = new Student13(222,"Aryan"); public static void tripleSalary(Employee x)
[Link](); {
[Link](); [Link](200);
} }
} When you call
O/P raj=new Employee(…);
default constructor is invoked tripleSalary(harry);
default constructor is invoked
111 karan Then the following happens
222 Aryan 1. x initialized with a copy of the value of harry,
that is, an object reference.
6. Method Parameters 2. The raiseSalary() method applied to that object
The term call by value means that the method reference. The Employee object to which both x
gets just the value that caller provides. In contrast, call and harry refer gets its salary raised by 200.
by reference means that the method gets the location 3. The method ends , and the parameter variable
of the variable that the caller provides. Thus a method x is no longer in use. Of course, the object
can modify the value stored in a variable that is passed reference variable harry continuous to refer to
by reference but not in one that passed by the value. the object whose salary was tripled.
The Java language always uses call by value.
That means, the method gets a copy of all parameter 4. Constructor and Overloading Constructors
values. In particular, the method can not modify the A constructor is a special member method
contents of any parameter variables that are passed to which will be called implicitly (automatically) by the
it. For example consider the following call. JVM whenever an object is created.
Double percent=10; The purpose of constructor is to initialize an
[Link](percent); object called object initialization. Constructors are
In above example no matter how the method is mainly create for initializing the object. Initialization is
implemented, we know that after the method call, the a process of assigning user defined values at the time
value of percent is still 10. of allocation of memory space.
Let us look a little more closely at this situation. The following is the syntax of defining
Suppose a method tried to triple the value of a method constructor.
parameter.
public static void tripleValue(double x)
{
x=3*x;
}
Let’s call this method:
double percent=10;
tripleValue(percent);
However, this does not work. After the method call, the
value of percent is still 10. Here is what happens:
1. x is initialized with a copy of the value of percent
i.e. 10.
2. x is tripled- it is now 30. But percent is still 10.
3. The method ends, and the parameter variable x is E.g.
no longer in use.

There are two kinds of parameters:


1. Primitive method parameters
2. Object reference
In above example we have seen that it is
impossible for a method to change a primitive type
-6-
Core Java By Kadam R.R

Advantages of constructors:
 A constructor eliminates placing the default
values.
 A constructor eliminates calling the normal or
ordinary method implicitly.
Rules or properties of a constructor
 Constructor will be called automatically when Method Constructor
the object is created. 1 Method can be any user Constructor must be
 Constructor name must be similar to name of defined name class name
the class. 2 Method should have It should not have any
 Constructor should not return any value even return type return type (even void)
void also. Because basic aim is to place the 3 Method should be It will be called
value in the object. (if we write the return type called explicitly either automatically whenever
for the constructor then that constructor will with object reference object is created
be treated as ordinary method). or class reference
 Constructor definitions should not be static. 1 Method is not provided The java compiler
Because constructors will be called each and by compiler in any case. provides a default
every time, whenever an object is creating. constructor if we do not
 Constructor should not be private provided an have any constructor.
object of one class is created in another class
(Constructor can be private provided an 7. Types of constructors
object of one class created in the same class). Based on creating objects in Java constructor are
 Constructors will not be inherited from one classified in two types. They are
class to another class (Because every class I. Default or no argument Constructor
constructor is create for initializing its own II. Parameterized constructor.
data members). Default Constructor
 The access specifier of the constructor may or A constructor is said to be default constructor
may not be private. if and only if it never take any parameters.
1. If the access specifier of the constructor is If any class does not contain at least one user
defined constructor than the system will create a
private then an object of corresponding class
default constructor at the time of compilation it is
can be created in the context of the same class
known as system defined default constructor.
but not in the context of some other classes.
Syntax:
2. If the access specifier of the constructor is not
private then an object of corresponding class
can be created both in the same class context
and in other class context.

-7-
Core Java By Kadam R.R
Purpose of default constructor?
Default constructor provides the default
values to the object like 0, 0.0, null etc. depending
on their type (for integer 0, for string null).
class Student
{
int roll;
float marks;
String name;
void show()
{
[Link]("Roll: "+roll);
[Link]("Marks: "+marks);
[Link]("Name: "+name);
}
}
class TestDemo
Note: System defined default constructor is {
created by java compiler and does not have any public static void main(String [] args)
statement in the body part. This constructor will be {
executed every time whenever an object is created Student s1=new Student();
if that class does not contain any user defined [Link]();
constructor. }
Example of default constructor. }
In below example, we are creating the no Output
argument constructor in the Test class. It will be Roll: 0
invoked at the time of object creation. Marks: 0.0
Example Name: null
//[Link] Explanation: In the above class, we are not
class Test creating any constructor so compiler provides a
{ default constructor. Here 0, 0.0 and null values are
int a, b; provided by default constructor.
Test ()
{
[Link]("I am from default Constructor...");
a=10; Parameterized constructor
b=20; Def1: If any constructor contain list of variable in
[Link]("Value of a: "+a); its signature is known as paremetrized constructor.
[Link]("Value of b: "+b); Def2: A constructor that have parameters is known
} as parameterized constructor.
}; A parameterized constructor is one which
class TestDemo takes some parameters.
{ Why use parameterized constructor?
public static void main(String [] args) Parameterized constructor is used to provide
{ different values to the distinct objects.
Test t1=new Test (); Syntax:
}
};
Output
Output:
I am from default Constructor...
Value of a: 10
Value of b: 20

-8-
Core Java By Kadam R.R
constructor and default constructor, It must be
define both the constructors.
 In any class maximum one default constructor
but 'n' number of parameterized constructors.

8. Constructor Overloading
Constructor overloading is a technique in Java
in which a class can have any number of constructors
that differ in parameter lists.
The compiler differentiates these constructors
by taking the number of parameters, and their type.
In other words whenever same constructor is
existing multiple times in the same class with different
number of parameters or order of parameters or type
of parameters is known as Constructor overloading.
In general constructor overloading can be used
Syntax to call parametrized constructor to initialized same or different objects with different
values.
Syntax

Example of Parametrized Constructor

class Test
{
int a, b;
Test(int n1, int n2)
{
[Link]("I am from Parameterized
Constructor...");
a=n1;
b=n2;
[Link]("Value of a = "+a);
[Link]("Value of b = "+b);
}
};
class TestDemo1
{
public static void main(String k [])
{
Test t1=new Test(10, 20); Why overriding is not possible at constructor level.
} The scope of constructor is within the class so
}; that it is not possible to achieved overriding at
constructor level.
Important points Related to Parameterized
Constructor 9. Static Fields/variables and methods
 Whenever we create an object using Static Fields/variables
parameterized constructor, it must be define The static keyword is used in java mainly for
parameterized constructor otherwise we will memory management. Static keyword are used with
get compile time error. Whenever we define the variables, methods. If you declare any variable as
objects with respect to both parameterized static, it is known static variable.

-9-
Core Java By Kadam R.R
If the value of a variable is not varied from Student1 s1=new Student1(101,"Karan");
object to object we should declare those variables at Student1 s2=new Student1(102,"Arjun");
the class level by using static modifier. [Link]();
In the case of instance variables for every [Link]();
object a separate copy will be created but in the case of }
static variables at the class level a single copy will be }
created and shared that copy by all objects of that O/P
class. 101 Karan MGM
Static variables can be created at the time of 102 Arjun MGM
class loading and destroyed at the time of class Non-static variable Static variable
unloading hence the scope of static variables is exactly
same as the scope of .class file. 1 These variable
We can access static variables either by using should not be These variables are
object reference or by using class name but usage of preceded by any preceded by static
class name is recommended. static keyword keyword. Example:
Within the same class it is not required to use Example: class A
class name also we can access static variables directly. class A {
When and why we use static variable { static int b;
Suppose we want to store record of all int a; }
employee of any company, in this case employee id }
is unique for every employee but company name is
common for all. 2 Memory is allocated
Memory is allocated for
When we create a static variable as a for these variable
these variable at the time
company name then only once memory is allocated whenever an object is
of loading of the class.
otherwise it allocates a memory space each time for created
every employee. The following is the syntax of
3 Memory is allocated
declaring static variables. Memory is allocated for
multiple time
Syntax: these variable only once
whenever a new
in the program.
object is created.
4 Non-static variable
E.g
also known as Memory is allocated at
instance variable the time of loading of
while because class so that these are
memory is allocated also known as class
The following example shows the use of static
whenever instance is variable.
variables:
created.
class Student1
{ 5 Non-static variable Static variable are
int seatNo; are specific to an common for every object
String name; object that means there memory
static String collegeName="MGM"; location can be sharable
Student1(int seatNo, String name) by every object reference
{ or same class.
[Link]=seatNo;
[Link]=name; 6 Non-static variable
Static variable can access
} can access with
with class reference.
void display() object reference.
Syntax:
{ Syntax
class_name.variable_name
[Link](seatNo+" "+name+" obj_ref.variable_name
"+collegeName);
} 10. Static Methods
public static void main(String[] args) If you apply static keyword with any method,
{ it is known as static method.
- 10 -
Core Java By Kadam R.R
In case of non static method memory is Student2 s3 = new Student2 (333,"Devilal");
allocated multiple times whenever method is [Link]();
calling. But in case of static method memory is [Link]();
allocated only once at the time of class loading. [Link]();
A static method can be invoked without the }
need for creating an instance of a class. }
A static method can access static data
member and can change the value of it. O/P
Syntax for declare static method: 111 Karan MGM
222 Arjun MGM
333 Devilal MGM

The garbage collector can not free these resources. In


order to free these resources we must use finalize()
method. This is similar to destructors in C++.
11. The finalize() method
Sometimes an object will need to perform some
E.g. action when it is destroyed. For example, if an object
is holding some non-java resources such as a file
handles or character font, then you might want to
make sure these resources are freed before an object
is destroyed. To handle such situations java provides
a mechanism called finalization. By using
finalization, you can define specific actions that will
occur when an object is just about to be reclaimed by
the garbage collector.
To add a finalizer to a class you simply define
The following example demonstrate the static the finalise method. The Java calls that method
method. whenever it is about to recycle an object of that class.
class Student2 Inside the finalize() method, you will specify those
{ actions that must be performed before an object is
int rollno; destroyed.
String name; There are two ways for requesting JVM to run
static String college = "ITM"; garbage collector.
static void change() 1. By System class.
{ 2. By Runtime class
college = "MGM"; - System class contain a static method to call a
} garbage collector.
Student2(int r, String n) E.g.
{ [Link]();
rollno = r; - We can also call the garbage collector using
name = n; Runtime class by creating object of Runtime class.
} E.g.
void display () Runtime r1=[Link]();
{ Once we get runtime object then we can call the
[Link](rollno+" "+name+" "+college); following method on that object.
} 1. freeMemory();
public static void main(String args[]) 2. totalMemory();
{ 3. gc();
[Link]();
class FinalizeDemo
Student2 s1 = new Student2 (111,"Karan"); {
Student2 s2 = new Student2 (222,"Arjun"); public static void main(String[] args)
- 11 -
Core Java By Kadam R.R
{ If we develop any application using concept
FinalizeDemo fd=new FinalizeDemo(); of Inheritance than that application have following
fd=null; advantages,
[Link]();  Application development time is less.
[Link](fd);  Application takes less memory.
[Link]("End of main() method");  Application execution time is less.
}  Application performance is enhance
public void finalize() (improved).
{  Redundancy (repetition) of the code is
[Link]("finalize() method called"); reduced or minimized so that we get
} consistence results and less storage cost.
} The “extends” keyword:
O/P  Suppose we are having the one already
javac [Link] existing class, we call it as “Super class”.
java FinalizeDemo Suppose we need to create another class
null having exactly same attributes to that of the
finalize() method called parent class and some extra attributes then
End of main() method we use extends keyword to extend the
class.
Inheritance Basics:- The process of accessing the  We can extend the class by using extends
data members and methods from one class to keyword in a class declaration after the
another class is known as inheritance. It is one of class name and before the parent class.
the fundamental features of object-oriented  The keyword extends indicates that you are
programming. making a new class that derives from an existing
The idea behind inheritance in java is that class.
you can create new classes that are built upon The following is the syntax of creating a new class
existing classes. from existing one.
 In the inheritance the class which is give Syntax:
data members and methods is known as
base or super or parent class.
 The class which is taking the data members
and methods is known as sub or derived or
child class.
 The data members and methods of a class
are known as features.
 The concept of inheritance is also known as
re-usability or extendable classes or sub
classing or derivation. E.g.

Imp: When you inherit from an existing class, you


can reuse non private methods and non private
fields of parent class, and you can add new
methods and fields also.

Why use Inheritance?


 For Method Overriding (used for Runtime
Polymorphism).
 It's main uses are to enable polymorphism
and to be able to reuse code for different
classes by putting it in a common super
class
 For code Re-usability
The following is the example of inheritance.
Advantage of inheritance
- 12 -
Core Java By Kadam R.R
class Employee
{
float salary=20000;
void empSalary()
{
[Link]("Salary of Employee:
"+salary);
}}
class Programmer extends Employee
{
float bonus=10000;
float totalSalary=salary+bonus;
void progSalary()
{
[Link]("Total Salary of Programmer: E.g.
"+totalSalary);
}
public static void main(String[] args)
{
Programmer p=new Programmer();
[Link]();
[Link]();
}}
O/P
javac [Link]
java Programmer
Salary of Employee: 20000.0
Total Salary of Programmer: 30000.0
The following is the example of single inheritance
Types of Inheritance class Parent
Based on number of ways inheriting the feature of {
base class into derived class we have five Inheritance int x=10;
types they are: int y=20;
1. Single inheritance void getP()
2. Multiple inheritance {
3. Hierarchical inheritance [Link]("In Parent class");
4. Multilevel inheritance [Link]("x="+x);
5. Hybrid inheritance [Link]("y="+y);
}
1. Single Inheritance }
When a sub-class is derived simply from it’s class Child extends Parent
super-class then this mechanism is known as {
Single inheritance. void getC()
In case of single inheritance there is only a {
sub-class and its super-class. It is also called as [Link]("In Child class");
one-level inheritance. [Link]("x="+x);
The following is the syntax of single [Link]("y="+y);
inheritance: }
Syntax: public static void main(String[] args)
{
Child p=new Child();
[Link]();
[Link]();
}
- 13 -
Core Java By Kadam R.R
}
O/P
javac [Link]
java Child
In Child class
x=10
y=20
In Parent class
x=10
y=20
- In the above example we have declared two
classes i.e. Parent and Child.
- In Parent class we have declared two variables If we try to compile the above program we will get
and assigned a values to that variables i.e. x and CE saying:
y. [Link][Link] '{' expected
- According to inheritance Child class can access class C extends A,B
the non private data members of Parent class.
- If we declare x and y as a private then child class 3. Hierarchical inheritance
can not access x and y variables. The mechanism of inheriting the features of
- If we try to access x and y variables in Child one super-class into more thanone sub-class
class then it gives CE saying: is known as hierarchical inheritance.
x has private access in Parent
y has private access in Parent

2. Multiple inheritance
The mechanism of inheriting the
features of more than one base class into a
single class is known as multiple
inheritance.
Java doesn’t support multiple
inheritance through classes but it can be Fig. Hierarchical Inheritance
achieved by using the interfaces. Syntax:

Fig. Multiple inheritance

E.g.
E.g.
- 14 -
Core Java By Kadam R.R
class Test
{
public static void main(String[] args)
{
B b1=new B();
C b2=new C();
D b3=new D();
[Link]();
[Link]();
[Link]();
}
}

O/P
javac [Link]
java Test
In showB()
a=10
1. W.a.p to demonstrate the hierarchical b=20
inheritance. In showC()
class A a=10
{ b=30
int a=10; In showD()
} a=10
class B extends A b=40
{
int b=20;
void showB()
{ class Faculty
[Link]("In showB()"); {
[Link]("a="+a); float salary=50000.00f;
[Link]("b="+b); }
} class Science extends Faculty
} {
class C extends A float bonus=20000.00f;
{ void displaySalary()
int c=30; {
void showC() [Link]("Faculty : Science");
{ [Link]("Salary: "+salary);
[Link]("In showC()"); [Link]("Bonus: "+bonus);
[Link]("a="+a); }
[Link]("b="+c); }
} class Commerce extends Faculty
} {
class D extends A float bonus=15000.00f;
{ void displaySalary()
int d=40; {
void showD() [Link]("Faculty : Commerce");
{ [Link]("Salary: "+salary);
[Link]("In showD()"); [Link]("Bonus: "+bonus);
[Link]("a="+a); }
[Link]("b="+d); }
} class Art extends Faculty
} {
float bonus=10000.00f;
- 15 -
Core Java By Kadam R.R
void displaySalary()
{
[Link]("Faculty : Art");
[Link]("Salary: "+salary);
[Link]("Bonus: "+bonus);
}
}
class SalaryDetails
{
public static void main(String[] args)
{
Science s=new Science();
Commerce c=new Commerce();
Art a=new Art();
[Link]();
[Link]();
[Link]();
}}
javac [Link]
java SalaryDetails
O/P Fig. Multilevel Inheritance
Faculty : Science When a sub-class is derived from a derived
Salary: 50000.0 class then this mechanism is called as multilevel
Bonus: 20000.0 inheritance. Multilevel inheritance can go up to
Faculty : Commerce any number of levels.
Salary: 50000.0 E.g.
Bonus: 15000.0
Faculty : Art
Salary: 50000.0
Bonus: 10000.0

4. Multilevel inheritance
In Multilevel inheritances there exists single
base class, single derived class and multiple
intermediate base classes.
Single base class + single derived class +
multiple intermediate base classes.

1. The following program demonstrates the


simple example of multilevel inheritance:
class A
{
int a=10;
}
class B extends A
{
int b=20;
void showB()
{
[Link]("In showB()");

- 16 -
Core Java By Kadam R.R
[Link]("a="+a); public void showStudent()
[Link]("b="+b); {
} [Link]("Roll No : "+rollNo);
} [Link]("Name : "+name);
class C extends B }
{ }
int c=30; class Marks extends Student
void showC() {
{ int s1,s2,s3,s4;
[Link]("In showC()"); public void setMarks(int s1, int s2, int s3, int s4)
[Link]("a="+a); {
[Link]("c="+c); this.s1=s1;
} this.s2=s2;
} this.s3=s3;
class D extends C this.s4=s4;
{ }
int d=40; public void showMarks()
void showD() {
{ [Link]("S1 : "+s1);
[Link]("In showD()"); [Link]("S2 : "+s2);
[Link]("a="+a); [Link]("S3 : "+s3);
[Link]("d="+d); [Link]("S4 : "+s4);
} }
public static void main(String[] args) }
{ class Result extends Marks
D d1=new D(); {
[Link](); int total;
[Link](); float percentage;
[Link](); public void calculate()
} {
} total=s1+s2+s3+s4;
javac [Link] percentage=total/4;
java D }
O/P public void showResult()
In showB() {
a=10 [Link]("Total Marks : "+total);
b=20 [Link]("Percentage : "+percentage);
In showC() }
a=10 public static void main(String[] args)
c=30 {
In showD() Result r=new Result();
a=10 [Link](101,"Raj");
d=40 [Link]();
2. The following program demonstrates the [Link](50,40,65,36);
multilevel inheritance: [Link]();
class Student [Link]();
{ [Link]();
int rollNo; }
String name; }
void setStudent(int rollNo, String name) javac [Link]
{ java Result
[Link]=rollNo; O/P
[Link]=name; Roll No : 101
} Name : Raj
- 17 -
Core Java By Kadam R.R
S1 : 50 collecting un-used memory space and improved
S2 : 40 the performance of java application.
S3 : 65
S4 : 36
Total Marks : 191 Super Keyword
Percentage : 47.0 Super keyword in java is a reference variable
that is used to refer parent class object. Super is an
implicit keyword creates by JVM and supply each and
every java program for performing important role in
Important Points for Inheritance: three places.
1. In java programming one derived class can 1. Accessing Super class variables
extends only one base class because java 2. Accessing Super classmethods
programming does not support multiple 3. Accessing Super classconstructor
inheritance through the concept of classes, but
it can be supported through the concept of Need of super keyword:
Interface. Whenever the derived class is inherits the
2. Whenever we develop any inheritance base class features, there is a possibility that base
application first create an object of bottom class features are similar to derived class features
most derived class but not for top most base and JVM gets an ambiguity. In order to
class. differentiate between base class features and
3. When we create an object of bottom most derived class features must be preceded by super
derived class, first we get the memory space for keyword.
the data members of top most base class, and Syntax
then we get the memory space for data [Link]
member of other bottom most derived class.
4. Bottom most derived class contains logical 1. Accessing Super class variables
appearance for the data members of all top Whenever the derived class inherits base class
most base classes. data members there is a possibility that base class data
5. If we do not want to give the features of base member are similar to derived class data member and
class to the derived class then the definition of JVM gets an ambiguity.
the base class must be preceded by final hence In order to differentiate between the data
final base classes are not reusable or not member of base class and derived class, in the context
inheritable. of derived class the base class data members must be
6. If we are do not want to give some of the preceded by super keyword.
features of base class to derived class than such Syntax
features of base class must be as private hence super.superclass_datamember_name
private features of base class are not If we are not writing super keyword before the
inheritable or accessible in derived class. base class data member name than it will be referred
7. Data members and methods of a base class can as current class data member name and base class data
be inherited into the derived class but member are hidden in the context of derived class.
constructors of base class can not be inherited The following example demonstrate the use of
because every constructor of a class is made for super keyword for accessing super class variables.
initializing its own data members but not made class Employee
for initializing the data members of other {
classes. float salary=10000;
 An object of base class can contain details }
about features of same class but an object of class HR extends Employee
base class never contains the details about {
special features of its derived class (this concept float salary=20000;
is known as scope of base class object). void display()
 For each and every class in java there exists {
an implicit predefined super class called [Link]("Base class Salary: "+[Link]);
[Link]. because it providers garbage [Link]("Child class Salary: "+salary);
collection facilities to its sub classes for }
- 18 -
Core Java By Kadam R.R
} In case there is no method in subclass as
class Supervarible parent, there is no need to use super.
{
public static void main(String[] args) 3. Accessing Super class constructor
{ The super keyword can also be used to
HR obj=new HR(); invoke or call the parent class constructor.
[Link](); Constructor are calling from bottom to top and
} executing from top to bottom.
} To establish the connection between base
javac [Link] class constructor and derived class constructors
java Supervarible JVM provides two implicit methods they are:
O/P 1. super()
Base class Salary: 10000.0 2. super(parameterList)
Child class Salary: 20000.0
1. super()
2. Accessing Super class methods It is used for calling super class default
The super keyword can also be used to invoke constructor from the derived class constructors.
or call parent class method. It should be use in case of The following example demonstrate how to call
method overriding. super class constructor from sub-class constructor:
In other word super keyword use when base class Vehicle
class method name and derived class method name {
have same name. Vehicle()
The following example demonstrate the use {
of super keyword for accessing super class [Link]("Vehicle is created");
method. }
class Parent }
{ class Bike extends Vehicle
int bikeSpeed=50; {
public void showSpeed() Bike()
{ {
[Link]("Parent's speed : "+bikeSpeed); super();//will invoke parent class constructor
} [Link]("Bike is created");
} }
class Child extends Parent public static void main(String args[])
{ {
int speed=100; Bike b=new Bike();
public void showSpeed() }
{ }
[Link]("Child's speed : "+speed); javac [Link]
[Link](); java Bike
} O/P
public static void main(String[] args) Vehicle is created
{ Bike is created
Child c1=new Child();  The first line inside constructor should be
[Link](); either super() or this().
}  If we are not writing then compiler will always
} generate super keyword.
javac [Link]
java Child
O/P
Child's speed : 100
Parent's speed : 50

- 19 -
Core Java By Kadam R.R
subclass need to modify the implementation (code)
of a method defined in the superclass without
changing the parameter list. This is achieved by
overriding or redefining the method in the subclass.
If sub class has the same method as
declared in the parent class, it is known as “method
overrding”.
In other words, if the sub-class provides
specific implementation of the method that has
We can use super() only at the first line of been provided by one of its parent class, it is known
constructor, if we are using anywhere else we will as “method overriding”.
get CE: If we doesn’t satisfy with the parent class
call to super must be first statement in implementation then we should override that
constructor. method in the sub-class in our own way.

Advantages of method overriding?


1. Method overriding is used to provide
specific implementation of a method that is
already provided by its super class.
Method Overriding 2. Method overriding is used for Runtime
Polymorphism is an important feature of Polymorphism.
OOP. The process of representing one Form in Rules for method overriding
multiple forms is known as Polymorphism. Here 1. Method must have same name as in the
one form represent original form or original parent class.
method always resides in base class and multiple 2. Method must have same parameter as in the
forms represents overridden method which resides parent class.
in derived classes. 3. The accessibility must not be more
Polymorphism is derived from 2 greek restrictive than original method.
words: poly and morphs. The word "poly" means 4. Must have the IS-A relationship(inheritance
many and "morphs" means forms. So is must).
polymorphism means many forms. The following is the syntax of method
Real life example of polymorphism overriding:
Suppose if you are in class room that time you Syntax:
behave like a student, when you are in market at
that time you behave like a customer, when you at
your home at that time you behave like a son or
daughter, Here one person present in different-
different behaviors.

How to achieve Polymorphism in Java ?


In java programming the Polymorphism
principal is implemented with method overriding
concept of java.
Polymorphism principal is divided into two
sub principal they are:
 Static or Compile time polymorphism
 Dynamic or Runtime polymorphism
Static polymorphism is implemented by
using method overloading and dynamic
polymorphism is implemented by using method
overriding.
What is method overriding?
A subclass inherits methods from a
superclass. However in certain situations, the
- 20 -
Core Java By Kadam R.R
E.g.

The following example demonstrate the use of final


method:
class Account
{
final void getDetails()
{
[Link]("Base class method");
}
}
class Clerk extends Account
{
void getDetails()
To override a subclass's method, we simply {
redefine the method in the subclass with the same [Link]("Child class method");
name, same return type and same parameter list as }
its superclass counterpart. public static void main(String[] args)
When the method with the same name exists in {
both the superclass as well as in the subclass, the Clerk c1=new Clerk();
object of the subclass will invoke the method of the [Link]();
subclass, not the method inherited from the base }
class. }
If we try to compile the above program then
Use of final keyword with method it gives CE saying:
The “final” is a keyword or access modifier getDetails() in Clerk cannot override getDetails() in
applicable for variables, methods and classes. Account; overridden method is final
If we declare a method as a final then we
can’t override that method in child class i.e. Use of final keyword with class
overriding is not possible with final methods. If we declare a class as a final then we can’t
We can simply add the keyword final at the extend that class i.e. inheritance concept is not
start of the method declaration in a super class. applicable with final class.
The following is the syntax of declaring final If we declare a class as a final then all the
method. variables and methods in that class are by default
Syntax: final.
When we want to restrict inheritance then
make a class as a final.
We can simply add final keyword at the
class declaration.
The following is the syntax of declaring final
class:
Syntax:

E.g.

- 21 -
Core Java By Kadam R.R

An abstract class is one which is containing


some concrete methods and some abstract
methods.
A class is made abstract by putting the
keyword abstract in front of class keyword in the
first line of class definition.
The following is the syntax of declaring
E.g. abstract class:
Syntax:

E.g.

The following example demonstrate the use of final


with class.
final class Account
{
int accNo=1001;
float balance=50000; Abstract Method
float getBalance() A method that is declared as abstract and
{ does not have implementation is known as abstract
[Link]("Balance : "+balance); method.
} To create an abstract method, simply specify
} the modifier abstract followed by the method
class Customer extends Account declaration and end the method with semicolon.
{ The following is the syntax of abstract
public static void main(String a[]) method.
{ Syntax:
Customer c1=new Customer();
[Link]();
}
}
In the above example we have created two E.g
classes i.e. Account and Customer. We have
declared Account class as a final it means we can’t
extend this class but here we are trying to extends
Account class therefore it gives CE saying:
javac [Link] The following is the example of abstract class:
cannot inherit from final Account abstract class Vehicle
{
abstract void speed();
Abstract class }
A class that is declared with abstract keyword class Bike extends Vehicle
is known as abstract class {

- 22 -
Core Java By Kadam R.R
void speed()
{
[Link]("Speed limit is 50 km/hr..");
}
}
class Car extends Vehicle
{
void speed()
{
[Link]("Speed limit is 80 km/hr..");
}
}
class AbsTest
{
public static void main(String args[])
{
Bike b = new Bike();
Car c=new Car();
[Link]();
[Link]();
}
}
javac [Link]
java AbsTest
O/P
Speed limit is 50 km/hr..
Speed limit is 80 km/hr..

If you extend the abstract class then you must


have to provide implementation for each and every
abstract method otherwise we will get CE:
E.g.
In above example if you doesn’t override
speed() method in Bike class then compiler gives an
error CE:
Bike is not abstract and does not override
abstract method speed () in Vehicle

- 23 -

You might also like