0% found this document useful (0 votes)
16 views

Oops Unit 2 Theoritical Points

Uploaded by

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

Oops Unit 2 Theoritical Points

Uploaded by

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

Inheritance is an important pillar of OOP(Object Oriented Programming).

It is the process in Java by which one class can inherit the


features(fields and methods) of another class.
Important terminology:
 Super Class: The class whose features are inherited is known as super class(or a base class or a parent class).
 Sub Class: The class that inherits the other class is known as sub class(or a derived class, extended class, or child class). The
subclass can add its own fields and methods in addition to the superclass fields and methods.
 Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a new class and there is already a
class that includes some of the code that we want, we can derive our new class from the existing class. By doing this, we are
reusing the fields and methods of an existing class.

Example Inheritance is used to achieve IS-A


relationship .
Simple
Inheritance Examples

-
The keyword used for inheritance is extends.
Syntax:
Class Sub-classname extends Super-classname
{
Declaration of variables;
Declaration of methods;
}
Example:
class Circle
{ Circle() { }
private int radius;
void setRadius(int radius){
this.radius= radius; class SimpleInheritance {
} public static void main(String args[])
int getRadius(){ { double vol;
return this.radius; Cone cn=new Cone();
} cn. setRadius(5);
double computeArea(){ cn.setHeight(10);
return (3.141*this.radius*this.radius); vol=cn.volume();
} System.out.println(vol);
double comutePerimeter(){ }
return 2*3.141*this.radius; }
} As you can see ,sub class Cone can access methods of Circle but
} not data member, because radius of super class is declared as
class Cone extends Circle{ private. sub class can’t inherit the private properties of super
int height; class.
Cone() { }
void setHeight(int height){
this.height= height;
}
int getHeight(){
return this.height;
}
double volume(){
double v=(this.computeArea() *this.height )/3;
return v;
}
}
What You Can Do in a Subclass
A subclass inherits all of the public, defult and protected members of its parent. The inherited fields can be used directly, just like
any other fields.
 You can declare new fields in the subclass that are not in the superclass.
 The inherited methods can be used directly as they are.
 You can write a new instance method in the subclass that has the same signature as the one in the superclass, thus overriding it.
 You can declare new methods in the subclass that are not in the superclass.
 You can write a subclass constructor that invokes the constructor of the superclass, either implicitly or by using the
keyword super.
Private Members in a Superclass
A subclass does not inherit the private members of its parent class. However, if the superclass has public or protected methods for
accessing its private fields, these can also be used by the subclass.
Types of
inheritance :

• Single
• Hierarchica C

l
• Multiple
• Multilevel
• Hybrid C

B C
Single Inheritance : In single inheritance, subclass inherits features of superclass. In image below, the class A serves as a
super class for the sub class B

Exampl Person
e

Employ
ee
Exampl
e
2.Hierarchical Inheritance : In Hierarchical Inheritance, one class serves as a superclass (base class) for more than one sub
class.
Person

Employ Student
ee
Multilevel Inheritance : In Multilevel Inheritance, a derived class will be inheriting a super class and as well as the derived class also act as the base class to other
class. In below image, the class A serves as a super class for the derived class B, which in turn serves as a super class for the derived class C.

Person

Employ
ee
Manage
Example 2 Example 3
Important facts about inheritance in Java
 Default superclass: Except Object class, which has no superclass, every class has one and only one direct
superclass (single inheritance). In the absence of any other explicit superclass, every class is implicitly a
subclass of Object class.
 Superclass can only be one: A superclass can have any number of subclasses. But a subclass can have
only one superclass. This is because Java does not support multiple inheritance with classes. Although with
interfaces, multiple inheritance is supported by java.
 Inheriting Constructors: 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.
 Private member inheritance: A subclass does not inherit the private members of its parent class. However,
if the superclass has public or protected methods(like getters and setters) for accessing its private fields, these
can also be used by the subclass.
Super Keyword in Java
The super keyword in java is a reference variable that is used to refer parent class objects. The keyword “super” came into the
picture with the concept of Inheritance. It is majorly used in the following contexts:
Use of super with variables: This scenario occurs when a derived class and base class has same data members. In that case
there is a possibility of ambiguity . We can understand it more clearly using this code snippet:
class vehicle */
class Vehicle
{
int maxSpeed = 120;
} In this example, both base class and subclass have
a member maxSpeed. We could access maxSpeed
/* sub class Car extending vehicle */
class Car extends Vehicle of base class in sublcass using super keyword.
{
int maxSpeed = 180;

void display()
{
/* print maxSpeed of base class (vehicle) */
System.out.println("Maximum Speed: " + super.maxSpeed);
}
}

/* Driver program to test */


class Test
{
public static void main(String[] args)
{
Car small = new Car();
small.display();
}
}
2. Use of super with methods: This is used when we want to call parent class method. So, whenever a parent and child class
have same named methods then to resolve ambiguity, we use super keyword. This code snippet helps to understand the said usage
of super keyword.
//Base class Person
class Person{
void message() {
System.out.println("This is person class");
}
}
/* Subclass Student */
class Student extends Person{
void message(){
System.out.println("This is student class");
}
void display(){
message();
super.message();
}
}
/* Driver program to test */
class Test{
public static void main(String args[]){
Student s = new Student();
// calling display() of Student
s.display();
}
}
In the above example, we have seen that if we call method message() then, the current class message() is invoked but with the use
of super keyword, message() of superclass could also be invoked.
3. Use of super with constructors: super keyword can also be used to access the parent class constructor. One more important
thing is that, ‘’super’ can call both parametric as well as non parametric constructors depending upon the situation. Following is
the code snippet to explain the above concept:
The following figure shows the order of constructor invocation and order of execution. Invocation takes place from bottom
class to top class and execution takes place from top to bottom.
class Person{
private String name; Example to demonstrate invocation of super class
Person(){} parameterized constructor from sub class
Person(String name){ class Student extends Person{
this.name=name; private int sno;
} Student(){}
void displayPerson(){ Student(int sno, String name){
System.out.println("Name "+ this.name); super(name);
this.sno=sno;
}
}
void displayStudent(){
} this.displayPerson();
class Employee extends Person{ System.out.println("Student No: "+this.sno);
private int eno; System.out.println();
Employee(){}
Employee(int eno, String name){ }
super(name); }
this.eno=eno; class HIHDemo{
public static void main(String args[]){
} Employee e1=new Employee(101,"Sarada");
void displayEmployee(){ Employee e2=new Employee(110,"Mahesha");
this.displayPerson(); Student s=new Student(501,"Abishek");
System.out.println("Employee No: e1.displayEmployee();
"+this.eno); e2.displayEmployee();
System.out.println(); s.displayStudent();
} }}
}Other Important points:
1.Call to super() must be the first statement in Derived(Student) Class constructor.
2.If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument(or default) constructor of the
superclass.
Method Overriding:
1.In a class hierarchy, when a method in a subclass has the same name and type signature as a method in its superclass, then the method in
the subclass is said to override the method in the superclass.
2.When an overridden method is called from within a subclass, it will always refer to the version of that method defined by the subclass.
3.The version of the method defined by the superclass will be hidden.
Consider the following Example:

Class B extends A{
• Example double j;
B() { }
B(double I,double j){
class A super(i);
{ double i; this.i=i;
A() { } }
A(double i){ void show()// this method overrides{
this.i=i; System.out.println(“i=“+i);
} System.out.println(“j=“+j);
void show(){ }
System.out.println(“i=“+i); Public class Mainclass{
} public static void main(String[] args){
} B obj= new B();
obj.show();
}
}
Dynamic Method Dispatch
Dynamic method dispatch is the mechanism by which a call to an overridden method is resolved at
run time, rather than compile time. Dynamic method dispatch is important because this is how Java
implements run-time polymorphism.

Method overriding forms the basis for one of Java’s most powerful concept: dynamic method
dispatch.

In inheritance a superclass reference variable can refer to a subclass object. Java uses this fact to
resolve calls to overridden methods at run time. When an overridden method is called through a
superclass reference, Java determines which version of that method to execute based upon the type
of the object being referred to at the time the call occurs. Thus, this decision is made at run time.
When different types of objects are referred to, different versions of an overridden method will be
called.
Dynamic Method Dispatch Example:
This program creates one superclass called A and sub class B .
Subclasses B override show( ) declared in A. Inside the main( ) method, a reference of type A, called
obj , is declared. The program then in turn assigns a reference to each type of object to obj and uses
that reference to invoke show( ). As the output shows, the version of show( ) executed is determined by
the type of object being referred to at the time of the call.
Class B extends A{
Example double k;
B() { }
B(double I, double j){
super(i);
class A this.i=i;
{ double i; }
void show()// this method overrides{
A() { }
System.out.println(“i=“+i);
A(double i){ System.out.println(“j=“+j);
this.i=i; }
} Public class Mainclass{
public static void main(String[] args){
void show(){
A obj;
System.out.println(“i=“+i); obj= new A();
} obj.show();
} obj=new B();
obj.show();
}
}
Polymorphism:

Polymorphism is essential to object-oriented programming for one reason: it allows a general class to
specify methods that will be common to all of its derivatives, while allowing subclasses to define the
specific implementation of some or all of those methods. Overridden methods allow Java to support
run-time polymorphism.

Dynamic or run-time polymorphism is one of the most powerful mechanisms that object oriented
design brings to bear on code reuse and robustness.

In Java, compile time polymorphism occurs through method overloading and dynamic
polymorphism occurs when a parent class reference is used to refer to a child class object.

Let’s look at a practical example that uses method overriding to achieve run_time polymorphism. The
following program creates a superclass called Bank that contains members related to bank . It
defines a methods called deposit( ) and withdraw() . The program derives two subclasses from
Bank. The first is SBI and the second is HDFC. Each of these subclasses overrides withdraw( )
method Note:
to have their
Write specificprogram
concerned defintions
here
Abstract classes and Abstract methods
An abstract class captures common characteristics of subclasses and may or may not contain any abstract
method. It cannot be instantiated but can be used as a superclass .
An abstract method is a method that is declared without an implementation.
An abstract method is declared like this:
abstract returntype methodname(Parameterlist);
An abstract class is declared like this:
accessmodifier abstract className {
// declare fields
// declare abstract methods
//define non abstract methods
}
If a class includes abstract methods, then the class itself must be declared as abstract.
We use abstract classes if any of these statements apply to your situation:
You want to share base code among several closely related classes.
If certain methods of class need to be made as abstract .
 You expect that classes that extend your abstract class have many common methods or fields,
or require access modifiers other than public (such as protected and private) .
--
abstract Employee
Empno
Name Note: Write something
Employee() about this example
diplayEmpData()
abstract calculateSalary()

Monthly_Based_Employee Contract_Based_Employee
Basicpay NoOfHours,wage

Monthly_Based_Employee(- Contract_Based_Employee(---
------) --------)
calculateSalary() calculateSalary()
import java.util.Scanner;
abstract class Employee{ class CBEmployee extends Employee
private int Empno; private String Name; { double Nohours,hourlyWage, Netsalary;
Employee(int Empno, String Name){ CBEmployee(int eno, String Name,double NH, double
this.Empno=Empno; this.Name=Name; HW){
} super(eno, Name);
void displayEmpData(){ Nohours=NH;
System.out.println("Employee no"+Empno); hourlyWage=HW;
System.out.println("Name"+Name); }
} void calculateSalary(){
abstract void calculateSalary(); Netsalary=Nohours*hourlyWage;
}//EMP CLASS CLASE }
class MBEmployee extends Employee void CBdisplay(){
{ double BasicPay, Netsalary; displayEmpData();
MBEmployee(int eno, String name, double bp){ System.out.println("Total salary"+Netsalary);
super(eno,name); BasicPay=bp; }
} }// Teacher close
void calculateSalary(){
if(BasicPay>=10000) public class AbstractDemo{
Netsalary=BasicPay+(BasicPay*20/100.0) +(BasicPay*50/100.0)- public static void main(String[] args){
(BaiscPay*18/100.0); MBEmployee ME=new MBEmployee(101,”KAPIL”, 20000);
else CBEmployee CE=new CBEmployee(201, “LAYA”, 30,200);
Netsalary=BasicPay+(BasicPay*15/100.0) +(BasicPay*75/100.0) - ME.calculateSalary();
(BaiscPay*12/100.0); CE.calculateSalary();
} ME.MBdisplay();
void MBdisplay(){ CE.CBdisplay();
displayEmpData(); }
System.out.println("Employee no"+Netsalary); }
}}
Interface
Interface is a complete abstract class.
Using interface ;you can specify what a class must do, but not how it does it. Interfaces are syntactically like classes, but
they lack instance variables, and their methods are declared without any body.

In practice, this means that you can define interfaces that don’t make assumptions about how they are implemented. Once it
is defined, any number of classes can implement an interface. Also, one class can implement any number of interfaces.

To implement an interface, a class must create the complete set of methods defined by the interface. However, each class is
free to determine the details of its own implementation. By providing the interface keyword, Java allows you to fully utilize
the “one interface, multiple methods” aspect of polymorphism.
An interface is defined much like a class. This is the general form of an interface:
accessmodifier interface name {
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
type final-varname1 = value;
type final-varname2 = value;
// ...
return-type method-nameN(parameter-list);
type final-varnameN = value;
}
All methods in an interface are public abstract. All interface variables are public static final

Implementing Interfaces:
Once an interface has been defined, one or more classes can implement that interface. To implement an interface, include
the implements clause in a class definition, and then create methods defined by the interface. The general form of a class
that includes the implements clause looks like this:

class classname [extends superclass] [implements interface [,interface...]] {


// class-body
}

Example:
Interfaces Can Be Extended
One interface can inherit another by use of the keyword extends. The syntax is the same as for
inheriting classes. When a class implements an interface that inherits another interface, it must
provide implementations for all methods defined within the interface inheritance chain. Following
is an example: class MyClass implements B {
public void meth1() {
interface A {
System.out.println("Implement meth1().");
void meth1(); }
void meth2(); public void meth2() {
} System.out.println("Implement meth2().");
}
public void meth3() {
interface B extends A { System.out.println("Implement meth3().");
void meth3(); }
} }
class IFExtend {
public static void main(String arg[]) {
MyClass ob = new MyClass();
ob.meth1();
ob.meth2();
ob.meth3();
}
}
Multiple inheritance in Java by interface
In Java a class can implements multiple interfaces, or an interface extends multiple interfaces .

Example:

interface I1{ interface I2{


void add(int a, void sub(int a,
int b); int b);
void mul(int a, void div(int a, int
int b); b);
} }
concrete class that
implements both
interfaces
Final Keyword In Java

Final keyword can be used in three cases


1) final variable
2) final method
3) final class

final variable
Final variables are nothing but constants. We cannot change the value of a final variable once it is
initialized. Lets have a look at the below code: In this program MAX_VALUE is the final variable.
class Demo{
final int MAX_VALUE=99;
void myMethod(){
System.out.pritln(MAX_VALUE);
}
public static void main(String args[]){
Demo obj=new Demo();
obj.myMethod();
}
}
final method
A final method can be inheritance but cannot be overridden. Which means even though a sub
class can call the final method of parent class without any issues but it cannot override it.
Example:

class XYZ{
final void demo(){
System.out.println("XYZ Class Method");
}
}

class ABC extends XYZ{


@Override
void demo(){ This program would throw a compilation error,
System.out.println("ABC Class Method");however we can use the parent class final method
} in sub class without any issues.

public static void main(String args[]){


ABC obj= new ABC();
obj.demo();
}
}
The following program would run fine as we are not overriding the final method. That shows that
final methods are inherited but they are not eligible for overriding.
class XYZ{
final void demo(){
System.out.println("XYZ Class Method");
}}
class ABC extends XYZ{
public static void main(String args[]){
ABC obj= new ABC();
obj.demo();
}}
final class
We cannot extend a final class. Consider the below example:
final class XYZ{
}
class ABC extends XYZ{
void demo(){
System.out.println("My Method");
}
public static void main(String args[]){
ABC obj= new ABC();
obj.demo();
}}
Topic 15: Packages

When a program needs any package, it is to be imported. for example when we need user input, we
import a package like this:
import java.util.Scanner
Here:
→ java is a top level package
→ util is a sub package
→ and Scanner is a class which is present in the sub package util.
Before we see how to create a user-defined package in java, lets see the advantages of using a package.

Advantages of using a package in Java:


These are the reasons why you should use packages in Java:
•Reusability: While developing a project in java, we often feel that there are few things that we are writing again
Example 1: Java packages
Here, a class Calculator is created inside a package name MyPack. To create a class inside a package,
declare the package name in the first statement in your program. A class can have only one package
declaration.
Calculator.java file created inside a package MyPack
package MyPack;
public class Calculator {
public int add(int a, int b){
return a+b;
}
public static void main(String args[]){
Calculator obj = new Calculator();
System.out.println(obj.add(10, 20)); } }
}
How to compile java package
javac -d directory javafilename
For example
d:>javac -d . Calculator.java
The -d switch specifies the destination directory where to put the generated package. You can use any
directory name like /home (in case of Linux), d:/abc (in case of windows) etc. If you want to keep the
package within the same directory, you can use . (dot).
How to run java package program. You need to use fully qualified name to run the class.Following
are the commands to compile and execute the above program with current directory as the base
folder.
To Compile: javac -d . Calculator.java
CLASSPATH - For Locating Classes
CLASSPATH is an environment variable needed for the Java compiler and runtime to locate the
Java packages used in a Java program

CLASSPATH can be set in one of the following ways:


1. CLASSPATH can be set permanently in the environment: In Windows,
choose control panel ⇒
System ⇒
Advanced ⇒
Environment Variables ⇒ choose "System Variables" (for all the users) or
"User Variables" (only the currently login user) ⇒
choose "Edit" (if CLASSPATH already exists) or "New" ⇒
Enter "CLASSPATH" as the variable name ⇒
Enter the required directories e.g., ".;c:\javaproject\classes; Take
note that you need to
include the current working directory (denoted by '.') in
the CLASSPATH.

2.CLASSPATH can be set temporarily for that particular CMD shell session by issuing the
following command: SET CLASSPATH
3. Instead of using the CLASSPATH environment variable, you can also use the command-line
option -classpath
or -cp of the javac and java commands, for example,

You might also like