SlideShare a Scribd company logo
2
Most read
13
Most read
14
Most read
Lab Report:
Object-oriented programming Lab
Arafat Sahin Afridi
PC-A
ID: 211-15-3971
Course Code: CSE 222
Course Title: Object-oriented programming Lab
Department of Computer Science and Engineering
Daffodil International University
Class and Object:
OBJECT:
An object is an identifiable entity with some characteristics, stateand
behaviour. Understanding the concept of objects is much easier when we
consider real-life examples around us because an objectis simply a realworld
entity.
Example
Object: House
State: Address, Color, Area
Behavior: Open door, close door
Class:
A class is a group of objects that share common properties and behavior.
For example, we can consider a car as a class that has characteristics like
steering wheels, seats, brakes, etc. And its behavior is mobility. But we can say
Honda City having a registration number: 4654 is an ‘object’ that belongs to the
class ‘car’.
It was a brief description of objects and classes. Now we will understand the
Java class in detail.
Syntax: Createa class named "Main" with a variablex:
public class Studen{
//fields(or instancevariable)
String StudName;
int StudAge;
// constructor
Studen(String name, int age){
this.StudName=name;
this.StudAge=age;
}
public static void main(String args[]){
//Creating objects
Studenobj1= new Studen("Arafat", 20);
Studenobj2 = new Studen("Abir", 18);
System.out.println(obj1.StudName+" "+obj1.StudAge);
System.out.println(obj2.StudName+" "+obj2.StudAge);
}
}
Getter –Setter Methods
Here “Main” is a Java class.Setter Method & Getter Method:
Encapsulation provide public get and set methods to access and update the
value of a Private variable
We learned that, private variables can only be accessed within the same
class and outside class has no access to it. However, it is possible to access
them if we provide public get and set methods.
The get method returns the variable value, and the set method sets the
value.
Syntax for both is that they start with either get or set, followed by the name
of the variable, with the first letter in upper case:
Example:
classEmployee
{
// classmember variable
privateinteId;
privateStringeName;
privateStringeDesignation;
privateStringeCompany;
public intgetEmpId()
{
return eId;
}
public voidsetEmpId(finalinteId)
{
this.eId= eId;
}
public String getEmpName()
{
return eName;
}
public voidsetEmpName(finalString eName)
{
// Validating theemployee'snameand
// throwing an exception if thenameisnullor itslength isless thanor equal
to 0.
if(eName== null|| eName.length()<=0)
{
thrownewIllegalArgumentException();
}
this.eName= eName;
}
public String getEmpDesignation()
{
return eDesignation;
}
public voidsetEmpDesignation(final String eDesignation)
{
this.eDesignation = eDesignation;
}
public String getEmpCompany()
{
return eCompany;
}
publicvoid setEmpCompany(final String eCompany)
{
this.eCompany= eCompany;
}
@Override
public String toString()
{
String str = "Employee: [id = " + getEmpId()+ ", name= " + getEmpName()+
", designation= " + getEmpDesignation() + ", company= " + getEmpCompany() +
"]";
return str;
}
}
// Mainclass.
publicclassGetterSetterExample1
{
// main method
public static voidmain(Stringargvs[])
{
// Creating an objectof theEmployeeclass
finalEmployeeemp= newEmployee();
// theemployeedetailsaregetting setusingthesetter methods.
emp.setEmpId(3971);
emp.setEmpName("Arafat");
emp.setEmpDesignation("SoftwareTester");
emp.setEmpCompany("XYZCorporation");
System.out.println(emp.toString());
}
}
Output
Constructor:
In Java, a constructor is a block of codes similar to the method. It is called when an instance
of the class is created. At the time of calling the constructor, memory for the object is
allocated in the memory. It is a special type of method which is used to initialize the object.
Code:
/Let us see example of default constructor
class Student3{
int id;
String name;
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student3 s1=new Student3();
Student3 s2=new Student3();
s1.display();
s2.display();
}
}
Output
Constructor Overloading:
The constructor overloading can be defined as the concept of having more
than one constructor with different parameters so that every constructor can
performa different task. Consider the following Java program, in which we
have used different constructors in the class.
Constructors can be overloaded in a similar way as function overloading.
Overloaded constructors havethe samename (name of the class) butthe
different number or arguments. Depending upon the number and type of
arguments passed, the corresponding constructor is called.
Example:
//Java programto overload constructors class
class StudentData
{
privateint stuID;
privateString stuName;
privateint stuAge;
StudentData()
{
//Default constructor
stuID =3971;
stuName= "Arafat";
stuAge= 21;
}
StudentData(intnum1, String str, int num2)
{
//Parameterized constructor
stuID =num1;
stuName= str;
stuAge= num2;
}
//Getter and setter methods
public int getStuID() {
return stuID;
}
public void setStuID(intstuID) {
this.stuID =stuID;
}
public String getStuName() {
return stuName;
}
public void setStuName(String stuName) {
this.stuName= stuName;
}
public int getStuAge() {
return stuAge;
}
public void setStuAge(int stuAge) {
this.stuAge= stuAge;
}
public static void main(String args[])
{
StudentData myobj = new StudentData();
System.out.println("StudentNameis:
"+myobj.getStuName());
System.out.println("StudentAgeis:
"+myobj.getStuAge());
System.out.println("StudentID is:
"+myobj.getStuID());
StudentData myobj2 = new
StudentData(3975, "Wahid", 20);
System.out.println("StudentNameis:
"+myobj2.getStuName());
System.out.println("StudentAgeis:
"+myobj2.getStuAge());
System.out.println("StudentID is:
"+myobj2.getStuID());
}
}
Output
Inheritance:
Inheritance:
Inheritance is one of the key featuresof OOP that allows us to create a new
class from an existing class. The new class that is created is known as
subclass (child or derived class) and the existing class from where the child
class is derived is known assuperclass(parentor base class).
Code:
class Teacher {
private String designation = "Teacher";
private String collegeName = "DffodilInternatinalUnivercity";
public String getDesignation() {
return designation;
}
protected void setDesignation(String designation) {
this.designation = designation;
}
protected String getCollegeName() {
return collegeName;
}
protected void setCollegeName(String collegeName) {
this.collegeName = collegeName;
}
void does(){
System.out.println("Teaching");
}
}
public class JavaExampleextendsTeacher{
String mainSubject= "OOP";
public static void main(String args[]){
JavaExampleobj = new JavaExample();
System.out.println(obj.getCollegeName());
System.out.println(obj.getDesignation());
System.out.println(obj.mainSubject);
obj.does();
}
}
Output :
Single Inheritance: When a class is extended by only one class, it is
called single-level inheritance in java or simply single inheritance.
In other words, creating a subclass from a single superclass is called single
inheritance. In single-level inheritance, there is only one base class and can be
one derived class.
The derived class inherits all the properties and behaviors only from a single
class. Itis represented as shown in the below figure:
Code:
package singleLevelInheritance;
// Create a base class or superclass.
public class A
{
// Declare an instance method.
public void methodA()
{
System.out.println("Base class method");
}
}
// Declare a derived class or subclass and extends class A.
public class B extends A
{
public void methodB()
{
System.out.println("Child class method");
}
}
public class Myclass
{
public static void main(String[] args)
{
// Create an object of class B.
B obj = new B();
obj.methodA(); // methodA() of B will be called because by default, it is available in
B.
obj.methodB(); // methodB() of B will be called.
}
}
Output :
Output:
Base class m
ethod
Hierarchical Inheritance: A class that is inherited by many subclasses is
known as hierarchical inheritance in java. In other words, when oneclass is
extended by many subclasses, itis known as hierarchical inheritance..
Code:
package hierarchicalInheritanceEx;
public class A
{
public void msgA()
{
System.out.println("Method of class A");
}
}
public class B extends A
{
// Empty class B, inherits msgA of parent class A.
}
public class C extends A
{
// Empty class C, inherits msgA of parent class A.
}
public class D extends A
{
// Empty class D, inherits msgA of parent class A.
}
public class MyClass
{
public static void main(String[] args)
{
// Create the object of class B, class C, and class D.
B obj1 = new B();
C obj2 = new C();
D obj3 = new D();
// Calling inherited function from the base class.
obj1.msgA();
obj2.msgA();
obj3.msgA();
}
}
Output:
Multilevel Inheritance: A class that is extended by a class and that class is
extended by another class forming chain inheritance is called multilevel
inheritance in java.
In multilevel inheritance, there is one baseclass and one derived class at one
level. At the next level, the derived class becomes the baseclass for the next
derived class and so on. This is as shown below in the diagram.
Code:
packagemultilevelInheritance;
public class Bus{
public Bus ()
{
System.out.println("ClassBus");
}
public void vehicleType()
{
System.out.println("VehicleType: Bus");
}
}
class TATA extends Bus{ public TATA()
{
System.out.println("ClassTATA");
}
public void brand()
{
System.out.println("Brand: TATA");
}
public void speed()
{
System.out.println("Max: 70Kmph");
}
}
public class TATA80 extends TATA{
public TATA80()
{
System.out.println("TATAModel: 80");
}
public void speed()
{
System.out.println("Max: 80Kmph");
}
public static void main(String args[])
{
TATA80 obj=new TATA80();
obj.vehicleType();
obj.brand();
obj.speed();
}
}
Output:

More Related Content

What's hot (20)

PDF
Cs8591 Computer Networks
Kathirvel Ayyaswamy
 
PDF
Constructor and Destructor
Kamal Acharya
 
PPTX
Chomsky Normal Form
Dhrumil Panchal
 
PPTX
Stack & Queue using Linked List in Data Structure
Meghaj Mallick
 
PPT
Data structure lecture7
Kumar
 
PPTX
Binary parallel adder
jignesh prajapati
 
PPSX
Files in c++
Selvin Josy Bai Somu
 
PPTX
Polymorphism in C++
Rabin BK
 
PPT
Polymorphism
Nilesh Dalvi
 
PPTX
Friend functions
Megha Singh
 
PDF
Unit ii chapter 2 Decision making and Branching in C
Sowmya Jyothi
 
PPT
Mitigating Layer2 Attacks
dkaya
 
PPTX
Implementation Of String Functions In C
Fazila Sadia
 
PPT
Heaps
Hafiz Atif Amin
 
PPT
Java Swing JFC
Sunil OS
 
PPTX
Object Oriented Programming with C#
foreverredpb
 
PPTX
Data Type Conversion in C++
Danial Mirza
 
DOC
Data Structure
Ibrahim MH
 
Cs8591 Computer Networks
Kathirvel Ayyaswamy
 
Constructor and Destructor
Kamal Acharya
 
Chomsky Normal Form
Dhrumil Panchal
 
Stack & Queue using Linked List in Data Structure
Meghaj Mallick
 
Data structure lecture7
Kumar
 
Binary parallel adder
jignesh prajapati
 
Files in c++
Selvin Josy Bai Somu
 
Polymorphism in C++
Rabin BK
 
Polymorphism
Nilesh Dalvi
 
Friend functions
Megha Singh
 
Unit ii chapter 2 Decision making and Branching in C
Sowmya Jyothi
 
Mitigating Layer2 Attacks
dkaya
 
Implementation Of String Functions In C
Fazila Sadia
 
Java Swing JFC
Sunil OS
 
Object Oriented Programming with C#
foreverredpb
 
Data Type Conversion in C++
Danial Mirza
 
Data Structure
Ibrahim MH
 

Similar to OOP Lab Report.docx (20)

PDF
Hello. Im currently working on the last section to my assignment a.pdf
irshadkumar3
 
PPT
14. Defining Classes
Intro C# Book
 
PPT
Defining classes-and-objects-1.0
BG Java EE Course
 
PPTX
Java2
Shridhar Ramesh
 
PPTX
Inheritance.pptx
RutujaTandalwade
 
PPT
Java tutorial for Beginners and Entry Level
Ramrao Desai
 
PPTX
Code Smells y Refactoring o haciendo que nuestro codigo huela (y se vea) mejo...
.NET Conf UY
 
DOCX
Unit-3 Practice Programs-5.docx
R.K.College of engg & Tech
 
PDF
Object Oriented Solved Practice Programs C++ Exams
MuhammadTalha436
 
PPTX
Constructor&method
Jani Harsh
 
PDF
Java Basic day-2
Kamlesh Singh
 
PPT
Inheritance, polymorphisam, abstract classes and composition)
farhan amjad
 
PDF
OOPs & Inheritance Notes
Shalabh Chaudhary
 
PDF
Object Oriented Programming (OOP) using C++ - Lecture 4
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
DOCX
Assignment 7
IIUM
 
PPTX
Detailed_description_on_java_ppt_final.pptx
technicaljd3
 
PPTX
class object.pptx
Killmekhilati
 
PPT
Object Oriented Programming with Java
Jussi Pohjolainen
 
PDF
Object Oriented Programming in PHP
wahidullah mudaser
 
PPT
Java Generics
jeslie
 
Hello. Im currently working on the last section to my assignment a.pdf
irshadkumar3
 
14. Defining Classes
Intro C# Book
 
Defining classes-and-objects-1.0
BG Java EE Course
 
Inheritance.pptx
RutujaTandalwade
 
Java tutorial for Beginners and Entry Level
Ramrao Desai
 
Code Smells y Refactoring o haciendo que nuestro codigo huela (y se vea) mejo...
.NET Conf UY
 
Unit-3 Practice Programs-5.docx
R.K.College of engg & Tech
 
Object Oriented Solved Practice Programs C++ Exams
MuhammadTalha436
 
Constructor&method
Jani Harsh
 
Java Basic day-2
Kamlesh Singh
 
Inheritance, polymorphisam, abstract classes and composition)
farhan amjad
 
OOPs & Inheritance Notes
Shalabh Chaudhary
 
Object Oriented Programming (OOP) using C++ - Lecture 4
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Assignment 7
IIUM
 
Detailed_description_on_java_ppt_final.pptx
technicaljd3
 
class object.pptx
Killmekhilati
 
Object Oriented Programming with Java
Jussi Pohjolainen
 
Object Oriented Programming in PHP
wahidullah mudaser
 
Java Generics
jeslie
 
Ad

Recently uploaded (20)

PPTX
Product Development & DevelopmentLecture02.pptx
zeeshanwazir2
 
PPTX
Introduction to Neural Networks and Perceptron Learning Algorithm.pptx
Kayalvizhi A
 
PPTX
Lecture 1 Shell and Tube Heat exchanger-1.pptx
mailforillegalwork
 
DOC
MRRS Strength and Durability of Concrete
CivilMythili
 
PPTX
GitOps_Without_K8s_Training simple one without k8s
DanialHabibi2
 
PPTX
美国电子版毕业证南卡罗莱纳大学上州分校水印成绩单USC学费发票定做学位证书编号怎么查
Taqyea
 
DOCX
CS-802 (A) BDH Lab manual IPS Academy Indore
thegodhimself05
 
PPTX
Mechanical Design of shell and tube heat exchangers as per ASME Sec VIII Divi...
shahveer210504
 
PDF
Unified_Cloud_Comm_Presentation anil singh ppt
anilsingh298751
 
PPTX
Evaluation and thermal analysis of shell and tube heat exchanger as per requi...
shahveer210504
 
PDF
Ethics and Trustworthy AI in Healthcare – Governing Sensitive Data, Profiling...
AlqualsaDIResearchGr
 
PPTX
Arduino Based Gas Leakage Detector Project
CircuitDigest
 
PPTX
Damage of stability of a ship and how its change .pptx
ehamadulhaque
 
PPTX
VITEEE 2026 Exam Details , Important Dates
SonaliSingh127098
 
PPTX
GitOps_Repo_Structure for begeinner(Scaffolindg)
DanialHabibi2
 
PDF
GTU Civil Engineering All Semester Syllabus.pdf
Vimal Bhojani
 
PDF
MAD Unit - 2 Activity and Fragment Management in Android (Diploma IT)
JappanMavani
 
PDF
Introduction to Productivity and Quality
মোঃ ফুরকান উদ্দিন জুয়েল
 
PDF
Basic_Concepts_in_Clinical_Biochemistry_2018كيمياء_عملي.pdf
AdelLoin
 
PPTX
The Role of Information Technology in Environmental Protectio....pptx
nallamillisriram
 
Product Development & DevelopmentLecture02.pptx
zeeshanwazir2
 
Introduction to Neural Networks and Perceptron Learning Algorithm.pptx
Kayalvizhi A
 
Lecture 1 Shell and Tube Heat exchanger-1.pptx
mailforillegalwork
 
MRRS Strength and Durability of Concrete
CivilMythili
 
GitOps_Without_K8s_Training simple one without k8s
DanialHabibi2
 
美国电子版毕业证南卡罗莱纳大学上州分校水印成绩单USC学费发票定做学位证书编号怎么查
Taqyea
 
CS-802 (A) BDH Lab manual IPS Academy Indore
thegodhimself05
 
Mechanical Design of shell and tube heat exchangers as per ASME Sec VIII Divi...
shahveer210504
 
Unified_Cloud_Comm_Presentation anil singh ppt
anilsingh298751
 
Evaluation and thermal analysis of shell and tube heat exchanger as per requi...
shahveer210504
 
Ethics and Trustworthy AI in Healthcare – Governing Sensitive Data, Profiling...
AlqualsaDIResearchGr
 
Arduino Based Gas Leakage Detector Project
CircuitDigest
 
Damage of stability of a ship and how its change .pptx
ehamadulhaque
 
VITEEE 2026 Exam Details , Important Dates
SonaliSingh127098
 
GitOps_Repo_Structure for begeinner(Scaffolindg)
DanialHabibi2
 
GTU Civil Engineering All Semester Syllabus.pdf
Vimal Bhojani
 
MAD Unit - 2 Activity and Fragment Management in Android (Diploma IT)
JappanMavani
 
Introduction to Productivity and Quality
মোঃ ফুরকান উদ্দিন জুয়েল
 
Basic_Concepts_in_Clinical_Biochemistry_2018كيمياء_عملي.pdf
AdelLoin
 
The Role of Information Technology in Environmental Protectio....pptx
nallamillisriram
 
Ad

OOP Lab Report.docx

  • 1. Lab Report: Object-oriented programming Lab Arafat Sahin Afridi PC-A ID: 211-15-3971 Course Code: CSE 222 Course Title: Object-oriented programming Lab Department of Computer Science and Engineering Daffodil International University
  • 2. Class and Object: OBJECT: An object is an identifiable entity with some characteristics, stateand behaviour. Understanding the concept of objects is much easier when we consider real-life examples around us because an objectis simply a realworld entity. Example Object: House State: Address, Color, Area Behavior: Open door, close door Class: A class is a group of objects that share common properties and behavior. For example, we can consider a car as a class that has characteristics like steering wheels, seats, brakes, etc. And its behavior is mobility. But we can say Honda City having a registration number: 4654 is an ‘object’ that belongs to the class ‘car’. It was a brief description of objects and classes. Now we will understand the Java class in detail. Syntax: Createa class named "Main" with a variablex: public class Studen{ //fields(or instancevariable) String StudName; int StudAge; // constructor Studen(String name, int age){ this.StudName=name;
  • 3. this.StudAge=age; } public static void main(String args[]){ //Creating objects Studenobj1= new Studen("Arafat", 20); Studenobj2 = new Studen("Abir", 18); System.out.println(obj1.StudName+" "+obj1.StudAge); System.out.println(obj2.StudName+" "+obj2.StudAge); } } Getter –Setter Methods Here “Main” is a Java class.Setter Method & Getter Method: Encapsulation provide public get and set methods to access and update the value of a Private variable We learned that, private variables can only be accessed within the same class and outside class has no access to it. However, it is possible to access them if we provide public get and set methods. The get method returns the variable value, and the set method sets the value. Syntax for both is that they start with either get or set, followed by the name of the variable, with the first letter in upper case:
  • 4. Example: classEmployee { // classmember variable privateinteId; privateStringeName; privateStringeDesignation; privateStringeCompany; public intgetEmpId() { return eId; } public voidsetEmpId(finalinteId) { this.eId= eId; } public String getEmpName() { return eName;
  • 5. } public voidsetEmpName(finalString eName) { // Validating theemployee'snameand // throwing an exception if thenameisnullor itslength isless thanor equal to 0. if(eName== null|| eName.length()<=0) { thrownewIllegalArgumentException(); } this.eName= eName; } public String getEmpDesignation() { return eDesignation; } public voidsetEmpDesignation(final String eDesignation) { this.eDesignation = eDesignation; }
  • 6. public String getEmpCompany() { return eCompany; } publicvoid setEmpCompany(final String eCompany) { this.eCompany= eCompany; } @Override public String toString() { String str = "Employee: [id = " + getEmpId()+ ", name= " + getEmpName()+ ", designation= " + getEmpDesignation() + ", company= " + getEmpCompany() + "]"; return str; } } // Mainclass. publicclassGetterSetterExample1 { // main method
  • 7. public static voidmain(Stringargvs[]) { // Creating an objectof theEmployeeclass finalEmployeeemp= newEmployee(); // theemployeedetailsaregetting setusingthesetter methods. emp.setEmpId(3971); emp.setEmpName("Arafat"); emp.setEmpDesignation("SoftwareTester"); emp.setEmpCompany("XYZCorporation"); System.out.println(emp.toString()); } } Output
  • 8. Constructor: In Java, a constructor is a block of codes similar to the method. It is called when an instance of the class is created. At the time of calling the constructor, memory for the object is allocated in the memory. It is a special type of method which is used to initialize the object. Code: /Let us see example of default constructor class Student3{ int id; String name; void display(){System.out.println(id+" "+name);} public static void main(String args[]){ Student3 s1=new Student3(); Student3 s2=new Student3(); s1.display(); s2.display(); } } Output
  • 9. Constructor Overloading: The constructor overloading can be defined as the concept of having more than one constructor with different parameters so that every constructor can performa different task. Consider the following Java program, in which we have used different constructors in the class. Constructors can be overloaded in a similar way as function overloading. Overloaded constructors havethe samename (name of the class) butthe different number or arguments. Depending upon the number and type of arguments passed, the corresponding constructor is called. Example: //Java programto overload constructors class class StudentData { privateint stuID; privateString stuName; privateint stuAge;
  • 10. StudentData() { //Default constructor stuID =3971; stuName= "Arafat"; stuAge= 21; } StudentData(intnum1, String str, int num2) { //Parameterized constructor stuID =num1; stuName= str; stuAge= num2; } //Getter and setter methods public int getStuID() { return stuID; }
  • 11. public void setStuID(intstuID) { this.stuID =stuID; } public String getStuName() { return stuName; } public void setStuName(String stuName) { this.stuName= stuName; } public int getStuAge() { return stuAge; } public void setStuAge(int stuAge) { this.stuAge= stuAge; } public static void main(String args[]) {
  • 12. StudentData myobj = new StudentData(); System.out.println("StudentNameis: "+myobj.getStuName()); System.out.println("StudentAgeis: "+myobj.getStuAge()); System.out.println("StudentID is: "+myobj.getStuID()); StudentData myobj2 = new StudentData(3975, "Wahid", 20); System.out.println("StudentNameis: "+myobj2.getStuName()); System.out.println("StudentAgeis: "+myobj2.getStuAge()); System.out.println("StudentID is: "+myobj2.getStuID()); } } Output
  • 13. Inheritance: Inheritance: Inheritance is one of the key featuresof OOP that allows us to create a new class from an existing class. The new class that is created is known as subclass (child or derived class) and the existing class from where the child class is derived is known assuperclass(parentor base class). Code: class Teacher { private String designation = "Teacher"; private String collegeName = "DffodilInternatinalUnivercity"; public String getDesignation() { return designation; } protected void setDesignation(String designation) { this.designation = designation; } protected String getCollegeName() { return collegeName; } protected void setCollegeName(String collegeName) { this.collegeName = collegeName; } void does(){ System.out.println("Teaching");
  • 14. } } public class JavaExampleextendsTeacher{ String mainSubject= "OOP"; public static void main(String args[]){ JavaExampleobj = new JavaExample(); System.out.println(obj.getCollegeName()); System.out.println(obj.getDesignation()); System.out.println(obj.mainSubject); obj.does(); } } Output : Single Inheritance: When a class is extended by only one class, it is called single-level inheritance in java or simply single inheritance. In other words, creating a subclass from a single superclass is called single inheritance. In single-level inheritance, there is only one base class and can be one derived class. The derived class inherits all the properties and behaviors only from a single class. Itis represented as shown in the below figure: Code: package singleLevelInheritance;
  • 15. // Create a base class or superclass. public class A { // Declare an instance method. public void methodA() { System.out.println("Base class method"); } } // Declare a derived class or subclass and extends class A. public class B extends A { public void methodB() { System.out.println("Child class method"); } } public class Myclass { public static void main(String[] args) { // Create an object of class B. B obj = new B(); obj.methodA(); // methodA() of B will be called because by default, it is available in B. obj.methodB(); // methodB() of B will be called. } } Output : Output: Base class m ethod
  • 16. Hierarchical Inheritance: A class that is inherited by many subclasses is known as hierarchical inheritance in java. In other words, when oneclass is extended by many subclasses, itis known as hierarchical inheritance.. Code: package hierarchicalInheritanceEx; public class A { public void msgA() { System.out.println("Method of class A"); } } public class B extends A { // Empty class B, inherits msgA of parent class A. } public class C extends A { // Empty class C, inherits msgA of parent class A. } public class D extends A { // Empty class D, inherits msgA of parent class A. } public class MyClass { public static void main(String[] args) { // Create the object of class B, class C, and class D. B obj1 = new B(); C obj2 = new C(); D obj3 = new D(); // Calling inherited function from the base class. obj1.msgA();
  • 17. obj2.msgA(); obj3.msgA(); } } Output: Multilevel Inheritance: A class that is extended by a class and that class is extended by another class forming chain inheritance is called multilevel inheritance in java. In multilevel inheritance, there is one baseclass and one derived class at one level. At the next level, the derived class becomes the baseclass for the next derived class and so on. This is as shown below in the diagram. Code: packagemultilevelInheritance; public class Bus{ public Bus () { System.out.println("ClassBus"); } public void vehicleType() { System.out.println("VehicleType: Bus"); } } class TATA extends Bus{ public TATA() { System.out.println("ClassTATA");
  • 18. } public void brand() { System.out.println("Brand: TATA"); } public void speed() { System.out.println("Max: 70Kmph"); } } public class TATA80 extends TATA{ public TATA80() { System.out.println("TATAModel: 80"); } public void speed() { System.out.println("Max: 80Kmph"); } public static void main(String args[]) { TATA80 obj=new TATA80(); obj.vehicleType(); obj.brand(); obj.speed(); } } Output: