This document discusses object-oriented programming concepts in Java like classes, objects, inheritance, polymorphism and encapsulation. It begins with defining what a class and object are - a class is a template that defines an object's data fields and methods, while an object is an instance of a class. The document then covers key OOP features like inheritance, where a subclass inherits properties from a superclass; polymorphism, which allows methods to behave differently based on the object; and encapsulation. Specific concepts like method overloading and overriding are explained in detail with examples.
Java abstract class & abstract methods,Abstract class in java
Abstract classes are classes that contain one or more abstract methods. An abstract method is a method that is declared, but contains no implementation. Abstract classes may not be instantiated, and require subclasses to provide implementations for the abstract methods.
Inheritance is the mechanism that allows programmers to create new classes from existing class. By using inheritance programmers can re-use code they've already written.
Java abstract class & abstract methods,Abstract class in java
Abstract classes are classes that contain one or more abstract methods. An abstract method is a method that is declared, but contains no implementation. Abstract classes may not be instantiated, and require subclasses to provide implementations for the abstract methods.
Inheritance is the mechanism that allows programmers to create new classes from existing class. By using inheritance programmers can re-use code they've already written.
An abstract class is a class that is declared abstract —it may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be subclassed. When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class.
What are Abstract Classes in Java | EdurekaEdureka!
YouTube Link: https://youtu.be/5X0Y--92pMI
**Java, J2EE & SOA Certification Training - https://www.edureka.co/java-j2ee-training-course **
This Edureka PPT on Abstract Classes in Java will provide you with detailed knowledge about Abstract Classes in Java and along with it, This PPT will also cover some examples of Abstract Classes in Java, in order to provide you with a deep understanding about their functionality. This PPT will cover the following topics:
What are Abstract Classes in Java?
Why do we need an Abstract Classes in Java?
Rules for using Abstract Classes in Java
Ways to achieve Abstraction in Java
The Syntax for Abstract Classes
Practical Examples of Abstract Classes
Difference between Interface and Abstract Class
Complete Java Playlist: http://bit.ly/2XcYNH5
Complete Blog Series: http://bit.ly/2YoabkT
Follow us to never miss an update in the future.
YouTube: https://www.youtube.com/user/edurekaIN
Instagram: https://www.instagram.com/edureka_learning/
Facebook: https://www.facebook.com/edurekaIN/
Twitter: https://twitter.com/edurekain
LinkedIn: https://www.linkedin.com/company/edureka
Castbox: https://castbox.fm/networks/505?country=in
Std 12 computer chapter 8 classes and object in java (part 2)Nuzhat Memon
Std 12 computer chapter 8 classes and objects in java (Part 2) by Nuzhat Memon
Variable Type (Instance Variable, Class Variable, Local Variable)
Accessing an instance variable and method using Dot notation
Accessing class variable and method using class name
Inheritance
Polymorphism (Method overloading and Method overridden)
Access Modifier or Visibility Modifier in java (4 p's Public Package Private and Private)
Accessor and Mutator
Composition and Aggregation
Constructor (special kind of method called automatically when a new object is created)
Java OOP Programming language (Part 6) - Abstract Class & InterfaceOUM SAOKOSAL
Java OOP Programming language (Part 6) - Abstract Class & Interface
Oum Saokosal
Where to me find me more:
YouTube: https://www.youtube.com/user/oumsaokosal
FB Page: https://facebook.com/kosalgeek
PPT: https://www.slideshare.net/oumsaokosal
Twitter: https://twitter.com/okosal
Web: http://kosalgeek.com
Inheritence, Terminology, Inheritance in java, The class called Object, Super keyword, Example, Method Overriding, Method Overriding example, Abstract Class, Abstract Class Number and the Java Wrapper Classes, Final Method and Classes, Multiple Inheritance
ملفات مساق البرمجة الهدفية (الشيئية) التي يتم تدريسها لطلبة بكالوريوس تكنولوجيا المعلومات وبكالوريوس تطوير نظم الحاسوب في الكلية الجامعية للعلوم والتكنولوجيا.
الملف يضم مفاهيم:
Class
Object
إعدادي وتدريسي
An abstract class is a class that is declared abstract —it may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be subclassed. When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class.
What are Abstract Classes in Java | EdurekaEdureka!
YouTube Link: https://youtu.be/5X0Y--92pMI
**Java, J2EE & SOA Certification Training - https://www.edureka.co/java-j2ee-training-course **
This Edureka PPT on Abstract Classes in Java will provide you with detailed knowledge about Abstract Classes in Java and along with it, This PPT will also cover some examples of Abstract Classes in Java, in order to provide you with a deep understanding about their functionality. This PPT will cover the following topics:
What are Abstract Classes in Java?
Why do we need an Abstract Classes in Java?
Rules for using Abstract Classes in Java
Ways to achieve Abstraction in Java
The Syntax for Abstract Classes
Practical Examples of Abstract Classes
Difference between Interface and Abstract Class
Complete Java Playlist: http://bit.ly/2XcYNH5
Complete Blog Series: http://bit.ly/2YoabkT
Follow us to never miss an update in the future.
YouTube: https://www.youtube.com/user/edurekaIN
Instagram: https://www.instagram.com/edureka_learning/
Facebook: https://www.facebook.com/edurekaIN/
Twitter: https://twitter.com/edurekain
LinkedIn: https://www.linkedin.com/company/edureka
Castbox: https://castbox.fm/networks/505?country=in
Std 12 computer chapter 8 classes and object in java (part 2)Nuzhat Memon
Std 12 computer chapter 8 classes and objects in java (Part 2) by Nuzhat Memon
Variable Type (Instance Variable, Class Variable, Local Variable)
Accessing an instance variable and method using Dot notation
Accessing class variable and method using class name
Inheritance
Polymorphism (Method overloading and Method overridden)
Access Modifier or Visibility Modifier in java (4 p's Public Package Private and Private)
Accessor and Mutator
Composition and Aggregation
Constructor (special kind of method called automatically when a new object is created)
Java OOP Programming language (Part 6) - Abstract Class & InterfaceOUM SAOKOSAL
Java OOP Programming language (Part 6) - Abstract Class & Interface
Oum Saokosal
Where to me find me more:
YouTube: https://www.youtube.com/user/oumsaokosal
FB Page: https://facebook.com/kosalgeek
PPT: https://www.slideshare.net/oumsaokosal
Twitter: https://twitter.com/okosal
Web: http://kosalgeek.com
Inheritence, Terminology, Inheritance in java, The class called Object, Super keyword, Example, Method Overriding, Method Overriding example, Abstract Class, Abstract Class Number and the Java Wrapper Classes, Final Method and Classes, Multiple Inheritance
ملفات مساق البرمجة الهدفية (الشيئية) التي يتم تدريسها لطلبة بكالوريوس تكنولوجيا المعلومات وبكالوريوس تطوير نظم الحاسوب في الكلية الجامعية للعلوم والتكنولوجيا.
الملف يضم مفاهيم:
Class
Object
إعدادي وتدريسي
Class notes(week 6) on inheritance and multiple inheritanceKuntal Bhowmick
java notes, object oriented programming using java, java tutorial, lecture notes, java programming notes, java example programs, java programs with explanation, java source code with output, java programs, java coding, java codes, java slides, java notes,inheritance in java, java inheritancenotes, java inheritancet notes,different types of inheritance in Java,inheritance with an example, inheritance hierarchy in Java
UNIT - 2
ARRAY AND ITS TYPES
INHERITANCE AND ITS TYPES
THE SUPER KEYWORD
POLYMORPHISM
ABSTRACT CLASSES
INTERFACES
DECLARING INTERFACES
IMPLEMENTING INTERFACES
EXTENDED INTERFACES
EXTENDING MULTIPLE INTERFACES
PACKAGES
THE IMPORT KEYWORD
THE DIRECTORY STRUCTURE OF PACKAGES
ACCESS SPECIFIER
Inheritance in Java beginner to advance with examples.pptxnaeemcse
Dive into the world of Java Inheritance and discover how it forms the backbone of robust and scalable code architecture. Learn how this powerful object-oriented programming concept allows you to effortlessly reuse and extend existing code, promoting a modular and maintainable design. Whether you're a novice or a seasoned developer, grasp the key principles of inheritance and elevate your Java programming skills. Join us on this journey to empower your code with the inheritance advantage, setting the stage for efficient development and enhanced software flexibility. Don't miss out on this essential building block for creating elegant and efficient Java applications!Unlock the potential of Java Inheritance with a concise exploration of single, multiple, multilevel, and hierarchical types. Discover how each type enhances code structure and flexibility. Elevate your Java skills by understanding the nuances of inheritance, optimizing code for efficiency and maintainability. Join us on this journey of code mastery and harness the diverse power of inheritance in your Java projects.
Similar to Inheritance and Polymorphism in java simple and clear (20)
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...Levi Shapiro
Letter from the Congress of the United States regarding Anti-Semitism sent June 3rd to MIT President Sally Kornbluth, MIT Corp Chair, Mark Gorenberg
Dear Dr. Kornbluth and Mr. Gorenberg,
The US House of Representatives is deeply concerned by ongoing and pervasive acts of antisemitic
harassment and intimidation at the Massachusetts Institute of Technology (MIT). Failing to act decisively to ensure a safe learning environment for all students would be a grave dereliction of your responsibilities as President of MIT and Chair of the MIT Corporation.
This Congress will not stand idly by and allow an environment hostile to Jewish students to persist. The House believes that your institution is in violation of Title VI of the Civil Rights Act, and the inability or
unwillingness to rectify this violation through action requires accountability.
Postsecondary education is a unique opportunity for students to learn and have their ideas and beliefs challenged. However, universities receiving hundreds of millions of federal funds annually have denied
students that opportunity and have been hijacked to become venues for the promotion of terrorism, antisemitic harassment and intimidation, unlawful encampments, and in some cases, assaults and riots.
The House of Representatives will not countenance the use of federal funds to indoctrinate students into hateful, antisemitic, anti-American supporters of terrorism. Investigations into campus antisemitism by the Committee on Education and the Workforce and the Committee on Ways and Means have been expanded into a Congress-wide probe across all relevant jurisdictions to address this national crisis. The undersigned Committees will conduct oversight into the use of federal funds at MIT and its learning environment under authorities granted to each Committee.
• The Committee on Education and the Workforce has been investigating your institution since December 7, 2023. The Committee has broad jurisdiction over postsecondary education, including its compliance with Title VI of the Civil Rights Act, campus safety concerns over disruptions to the learning environment, and the awarding of federal student aid under the Higher Education Act.
• The Committee on Oversight and Accountability is investigating the sources of funding and other support flowing to groups espousing pro-Hamas propaganda and engaged in antisemitic harassment and intimidation of students. The Committee on Oversight and Accountability is the principal oversight committee of the US House of Representatives and has broad authority to investigate “any matter” at “any time” under House Rule X.
• The Committee on Ways and Means has been investigating several universities since November 15, 2023, when the Committee held a hearing entitled From Ivory Towers to Dark Corners: Investigating the Nexus Between Antisemitism, Tax-Exempt Universities, and Terror Financing. The Committee followed the hearing with letters to those institutions on January 10, 202
Read| The latest issue of The Challenger is here! We are thrilled to announce that our school paper has qualified for the NATIONAL SCHOOLS PRESS CONFERENCE (NSPC) 2024. Thank you for your unwavering support and trust. Dive into the stories that made us stand out!
Acetabularia Information For Class 9 .docxvaibhavrinwa19
Acetabularia acetabulum is a single-celled green alga that in its vegetative state is morphologically differentiated into a basal rhizoid and an axially elongated stalk, which bears whorls of branching hairs. The single diploid nucleus resides in the rhizoid.
Model Attribute Check Company Auto PropertyCeline George
In Odoo, the multi-company feature allows you to manage multiple companies within a single Odoo database instance. Each company can have its own configurations while still sharing common resources such as products, customers, and suppliers.
Unit 8 - Information and Communication Technology (Paper I).pdfThiyagu K
This slides describes the basic concepts of ICT, basics of Email, Emerging Technology and Digital Initiatives in Education. This presentations aligns with the UGC Paper I syllabus.
Embracing GenAI - A Strategic ImperativePeter Windle
Artificial Intelligence (AI) technologies such as Generative AI, Image Generators and Large Language Models have had a dramatic impact on teaching, learning and assessment over the past 18 months. The most immediate threat AI posed was to Academic Integrity with Higher Education Institutes (HEIs) focusing their efforts on combating the use of GenAI in assessment. Guidelines were developed for staff and students, policies put in place too. Innovative educators have forged paths in the use of Generative AI for teaching, learning and assessments leading to pockets of transformation springing up across HEIs, often with little or no top-down guidance, support or direction.
This Gasta posits a strategic approach to integrating AI into HEIs to prepare staff, students and the curriculum for an evolving world and workplace. We will highlight the advantages of working with these technologies beyond the realm of teaching, learning and assessment by considering prompt engineering skills, industry impact, curriculum changes, and the need for staff upskilling. In contrast, not engaging strategically with Generative AI poses risks, including falling behind peers, missed opportunities and failing to ensure our graduates remain employable. The rapid evolution of AI technologies necessitates a proactive and strategic approach if we are to remain relevant.
How to Make a Field invisible in Odoo 17Celine George
It is possible to hide or invisible some fields in odoo. Commonly using “invisible” attribute in the field definition to invisible the fields. This slide will show how to make a field invisible in odoo 17.
The French Revolution, which began in 1789, was a period of radical social and political upheaval in France. It marked the decline of absolute monarchies, the rise of secular and democratic republics, and the eventual rise of Napoleon Bonaparte. This revolutionary period is crucial in understanding the transition from feudalism to modernity in Europe.
For more information, visit-www.vavaclasses.com
Normal Labour/ Stages of Labour/ Mechanism of LabourWasim Ak
Normal labor is also termed spontaneous labor, defined as the natural physiological process through which the fetus, placenta, and membranes are expelled from the uterus through the birth canal at term (37 to 42 weeks
3. Introduction
This tutorial will help you to understand about Java OOP’S concepts with
examples. Let’s discuss about what are the features of (Object Oriented
Programming). Writing object-oriented programs involves creating classes,
creating objects from those classes, and creating applications, which are
stand-alone executable programs that use those objects.
lecturer .miss .Ashna Nazm Hamasalh 3
4. A class is a template, blue print, or contract that defines what an
object’s data fields and methods will be.
An object is an instance of a class. You can create many instances of a
class.
A Java class uses variables to define data fields and methods to define
actions. Additionally, a class provides methods of a special type, known
as constructors, which are invoked to create a new object. A
constructor can perform any action, but constructors are designed to
perform initializing actions, such as initializing the data fields of objects.
lecturer .miss .Ashna Nazm Hamasalh 4
6. Objects are made up of attributes and methods. Attributes are the
characteristics that define an object; the values contained in attributes
differentiate objects of the same class from one another. To understand
this better let’s take example of Mobile as object. Mobile has
characteristics like model, manufacturer, cost, operating system etc. So
if we create “Samsung” mobile object and “IPhone” mobile object we
can distinguish them from characteristics. The values of the attributes
of an object are also referred to as the object’s state.
lecturer .miss .Ashna Nazm Hamasalh 6
7. There are three main features of OOPS.
1) Inheritance
2)Polymorphism
3) Encapsulation
lecturer .miss .Ashna Nazm Hamasalh 7
10. Inheritance
Inheritance can be defined as the process where one class acquires the
properties(methods and fields) of another. With the use of inheritance the
information is made manageable in a hierarchical order.
The class which inherits the properties of other is known as subclass
(derived class, child class) and the class whose properties are inherited is
known as superclass(base class, parent class).
lecturer .miss .Ashna Nazm Hamasalh 10
12. extends Keyword
extends is the keyword used to inherit the properties of a class. Below
given is the syntax of extends keyword.
lecturer .miss .Ashna Nazm Hamasalh 12
class Super{
.....
.....
}
class Sub extends Super{
.....
.....
}
14. Sample Code
Below given is an example demonstrating Java inheritance. In this
example you
can observe two classes namely Calculation and My_Calculation.
Using extends keyword the My_Calculation inherits the methods
addition() and
Subtraction() of Calculation class.
Copy and paste the program given below in a file with name
My_Calculation.java
lecturer .miss .Ashna Nazm Hamasalh 14
15. public class My_Calculation extends Calculation{
public void multiplication(int x, int y){
z=x*y;
System.out.println("The product of the given numb
ers:"+z);
}
public static void main(String args[]){
int a=20, b=10;
My_Calculation demo = new My_Calculation();
demo.addition(a, b);
demo.Substraction(a, b);
demo.multiplication(a, b); } }
class Calculation{
int z;
public void addition(int x, int y){
z=x+y;
System.out.println("The sum of the given numbers:"+z);
}
public void Substraction(int x,int y){
z=x-y;
System.out.println("The difference between the given n
umbers:"+z);
}
}
Child class parent class
lecturer .miss .Ashna Nazm Hamasalh 15
16. After executing the program it will produce the foll
owing result.
•The sum of the given numbers:30
•The difference between the given numbers:10
•The product of the given numbers:200
lecturer .miss .Ashna Nazm Hamasalh 16
17. In the given program when an object to My_Calculation class is created,
a copy of the contents of the super class is made with in it.
That is why, using the object of the subclass you can access the members
of a super class.
lecturer .miss .Ashna Nazm Hamasalh 17
18. The Superclass reference variable can hold the subclass object, but using that
variable you can access only the members of the superclass, so to access the
members of both classes it is recommended to always create reference variable
to the subclass.
If you consider the above program you can instantiate the class as given below as
well. But using the superclass reference variable ( cal in this case ) you cannot call
the method multiplication(), which belongs to the subclass My_Calculation.
Calculation cal=new My_Calculation();
demo.addition(a, b);
demo.Subtraction(a, b);
lecturer .miss .Ashna Nazm Hamasalh 18
19. lecturer .miss .Ashna Nazm Hamasalh 19
Note: A subclass inherits all the members (fields, methods, and nested classes)
from its superclass. Constructors are not members, so they are not inherited by
subclasses, but the constructor of the superclass can be invoked from the subclass.
20. The super keyword
The super keyword is similar to this keyword following are the scenarios
where the super keyword is used.
• It is used to differentiate the members of superclass from the members
of subclass, if they have same names.
• It is used to invoke the superclass constructor from subclass.
lecturer .miss .Ashna Nazm Hamasalh 20
21. Differentiating the members
If a class is inheriting the properties of another class. And if the members of the
superclass have the names same as the sub class, to differentiate these variables
we use super keyword as shown below.
super.variable
super.method();
lecturer .miss .Ashna Nazm Hamasalh 21
22. Sample Code
This section provides you a program that demonstrates the usage of
the super keyword.
In the given program you have two classes namely Sub_class and Super_class, both
have a method named display() with different implementations, and a variable
named num with different values. We are invoking display() method of both
classes and printing the value of the variable num of both classes, here you can
observe that we have used super key word to differentiate the members of super
class from sub class.
Copy and paste the program in a file with name Sub_class.java.
lecturer .miss .Ashna Nazm Hamasalh 22
23. lecturer .miss .Ashna Nazm Hamasalh 23
class Super_class{
int num=20;
//display method of superclass
public void display(){
System.out.println("This is the display method of superclass");
}
}
24. public class Sub_class extends Super_class {
int num=10;
//display method of sub class
public void display(){
System.out.println("This is the display method
of subclass");
}
public void my_method(){
//Instantiating subclass
Sub_class sub=new Sub_class();
//Invoking the display() method of sub class
sub.display();
//Invoking the display() method of superclass
super.display();
//printing the value of variable num of subclass
System.out.println("value of the variable
named num in sub class:"+ sub.num);
//printing the value of variable num of superclass
System.out.println("value of the variable
named num in super class:"+super.num);
}
public static void main(String args[]){
Sub_class obj = new Sub_class();
obj.my_method();
}
}
lecturer .miss .Ashna Nazm Hamasalh 24
25. Compile and execute the above code .
On executing the program you will get the following result:
This is the display method of subclass
This is the display method of superclass
value of the variable named num in sub class:10
value of the variable named num in super class:20
•
lecturer .miss .Ashna Nazm Hamasalh 25
26. Invoking Superclass constructor
If a class is inheriting the properties of another class, the subclass automatically
acquires the default constructor of the super class. But if you want to call a
parameterized constructor of the super class, you need to use the super keyword
as shown below.
lecturer .miss .Ashna Nazm Hamasalh 26
27. super(values);
Sample Code
The program given in this section demonstrates how to use the super keyword to
invoke the parameterized constructor of the superclass. This program contains a
super class and a sub class, where the super class contains a parameterized
constructor which accepts a string value, and we used the super keyword to
invoke the parameterized constructor of the super class.
Copy and paste the below given program in a file with name Subclass.java
lecturer .miss .Ashna Nazm Hamasalh 27
28. Compile and execute the above code
On executing the program you will get the following result:
The value of the variable named age in super class is: 24
class Superclass{
int age;
Superclass(int age){
this.age=age;
}
public void getAge(){
System.out.println("The value of the
variable named age in super class is: "+age);
}
}
public class Subclass extends Superclass {
Subclass(int age){
super(age);
}
public static void main(String argd[]){
Subclass s= new Subclass(24);
s.getAge();
}
}
lecturer .miss .Ashna Nazm Hamasalh 28
29. Types of inheritance
There are various types of inheritance as demonstrated below.
lecturer .miss .Ashna Nazm Hamasalh 29
30. What is polymorphism in programming?
Polymorphism is the capability of a method to do different things based
on the object that it is acting upon. In other words, polymorphism
allows you define one interface and have multiple implementations.
I know it sounds confusing. Don’t worry we will discuss this in detail.
lecturer .miss .Ashna Nazm Hamasalh 30
31. • It is a feature that allows one interface to be used for a general class
of actions.
• An operation may exhibit different behavior in different instances.
• The behavior depends on the types of data used in the operation.
• It plays an important role in allowing objects having different internal
structures to share the same external interface.
• Polymorphism is extensively used in implementing inheritance.
Following concepts demonstrate different types of polymorphism in java.
1) Method Overloading
2) Method Overriding
lecturer .miss .Ashna Nazm Hamasalh 31
32. Method Overloading:
In Java, it is possible to define two or more methods of same name in a
class,provided that there argument list or parameters are different. This
concept is known as Method Overloading.
I have covered method overloading and Overriding below. To know
more about
polymorphism types refer my post Types of polymorphism in java: Stat
ic,
Dynamic, Runtime and Compile time Polymorphism.
lecturer .miss .Ashna Nazm Hamasalh 32
33. 1) Method Overloading
1. To call an overloaded method in Java, it is must to use the type and/or
number of arguments to determine which version of the overloaded method to
actually call.
2. Overloaded methods may have different return types; the return type alone
is insufficient to distinguish two versions of a method.
3. When Java encounters a call to an overloaded method, it simply executes the
version of the method whose parameters match the arguments used in the call.
4. It allows the user to achieve compile time polymorphism.
5. An overloaded method can throw different exceptions.
6. It can have different access modifiers.
lecturer .miss .Ashna Nazm Hamasalh 33
34. public static void main (String args [])
{
Overload Obj = new Overload();
double result;
Obj .demo(10);
Obj .demo(10, 20);
}}
Example:
class Overload
{void demo (int a){
System.out.println ("a: " + a);
}
void demo (int a, int b)
{
System.out.println ("a and b: " + a + "," + b);
}
double demo(double a) {
System.out.println("double a: " + a);
return a*a;
}}
lecturer .miss .Ashna Nazm Hamasalh 34
35. Output:
a: 10
a and b: 10,20
Here the method demo() is overloaded 3 times: first having 1 int paramete
r,second one has 2 int parameters and third one is having double arg. The
methodsare invoked or called with the same type and number of paramete
rs used.
lecturer .miss .Ashna Nazm Hamasalh 35
36. Rules for Method Overloading
1. Overloading can take place in the same class or in its sub-class.
2. Constructor in Java can be overloaded
3. Overloaded methods must have a different argument list.
4. Overloaded method should always be the part of the same class (can also take
place in sub class), with same name but different parameters.
5. The parameters may differ in their type or number, or in both.
6. They may have the same or different return types.
7. It is also known as compile time polymorphism.
lecturer .miss .Ashna Nazm Hamasalh 36
37. 2) Method Overriding
Child class has the same method as of base class. In such cases child class
overrides the parent class method without even touching the source code
of the base class. This feature is known as method overriding.
lecturer .miss .Ashna Nazm Hamasalh 37
38. Example:
public class BaseClass
{
public void methodToOverride() //Base class method
{System.out.println ("I'm the method of BaseClass");
}}
lecturer .miss .Ashna Nazm Hamasalh 38
public class DerivedClass extends BaseClass
{
public void methodToOverride() //Derived Class method
{
System.out.println ("I'm the method of DerivedClass");
}
}
39. Output:
I'm the method of BaseClass
I'm the method of DerivedClass
public class TestMethod{
public static void main (String args []) {
// BaseClass reference and object
BaseClass obj1 = new BaseClass();
// BaseClass reference but DerivedClass object
BaseClass obj2 = new DerivedClass();
// Calls the method from BaseClass class
obj1.methodToOverride();
//Calls the method from DerivedClass class
obj2.methodToOverride();}}
lecturer .miss .Ashna Nazm Hamasalh 39
40. Rules for Method Overriding:
1. applies only to inherited methods
2. object type (NOT reference variable type) determines which overridden
method will be used at runtime
3. Overriding method can have different return type (refer this)
4. Overriding method must not have more restrictive access modifier
5. Abstract methods must be overridden
6. Static and final methods cannot be overridden
7. Constructors cannot be overridden
8. It is also known as Runtime polymorphism.
lecturer .miss .Ashna Nazm Hamasalh 40
41. super keyword in Overriding:
When invoking a superclass version of an overridden method the super keyword
is used.
lecturer .miss .Ashna Nazm Hamasalh 41
42. Example:
lecturer .miss .Ashna Nazm Hamasalh 42
class Vehicle {
public void move () {
System.out.println ("Vehicles are used for moving from one place to another");}}
class Car extends Vehicle {
public void move () {
super. move (); // invokes the super class method
System.out.println ("Car is a good medium of transport ");}}
public class TestCar {
public static void main (String args []){
Vehicle b = new Car (); // Vehicle reference but Car object
b.move (); //Calls the method in Car class
}}
43. Output:
Vehicles are used for moving from one place to another
Car is a good medium of transport
lecturer .miss .Ashna Nazm Hamasalh 43