[go: up one dir, main page]

0% found this document useful (0 votes)
38 views42 pages

Oops Unit-Ii

oops part 2

Uploaded by

sowmyanaidumoyyi
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)
38 views42 pages

Oops Unit-Ii

oops part 2

Uploaded by

sowmyanaidumoyyi
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
You are on page 1/ 42

INHERITANCE

Abstract class in Java


A class which is declared with the abstract keyword is known as an abstract class
in Java. It can have abstract and non-abstract methods (method with the body).
Before learning the Java abstract class, let's understand the abstraction in Java first.
Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only
functionality to the user.
Another way, it shows only essential things to the user and hides the internal details,
for example, sending SMS where you type the text and send the message. You don't
know the internal processing about the message delivery.
Abstraction lets you focus on what the object does instead of how it does it.
Ways to achieve Abstraction
There are two ways to achieve abstraction in java
Abstract class (0 to 100%)
Interface(100%)
Abstract class in Java
A class which is declared as abstract is known as an abstract class. It
can have abstract and non-abstract methods. It needs to be extended and
its method implemented. It cannot be instantiated.
Points to Remember
An abstract class must be declared with an abstract keyword.
• It can have abstract and non-abstract methods.
• It cannot be instantiated.
• It can have constructors and static methods also.
• It can have final methods which will force the subclass not to change
the body of the method.
Example of Abstract class that has an abstract method
In this example, Bike is an abstract class that contains only one abstract
method run. Its implementation is provided by the Honda class.
abstract class Bike{
abstract void run();
}
class Honda4 extends Bike{
void run(){System.out.println("running safely");}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
} }

OUTPUT: running safely


Understanding Base Class in Java
• A key idea in object-oriented programming (OOP) is inheritance, which
enables classes to take on traits and characteristics from other classes.
Through the usage of base classes and derived classes, the idea of
inheritance is implemented in Java.
• We shall examine what a base class in Java is in this post as well as its
importance in the world of programming.
• A base class, usually referred to as a superclass or parent class, is a type of
class that acts as a template or guide for additional classes. Multiple derived
classes may have its common features and behaviours.
• You can create a hierarchical relationship between classes by establishing a
base class, which encourages code reuse and offers a structured method of
organising your code.
• To create a base class in Java, you simply define a class as you normally
would, but without explicitly inheriting from another class.
Let's consider a simple example to illustrate this:
public class Animal {
private String name;
private int age;
public Animal(String name, int age) {
this.name = name;
this.age = age;
}
public void eat() {
System.out.println("The animal is eating.");
}
public void sleep() {
System.out.println("The animal is sleeping.");
}
}
Inheritance in Java
• Inheritance in Java is a mechanism in which one object acquires all
the properties and behaviors of a parent object. It is an important part
of OOPs (Object Oriented programming system).
• The idea behind inheritance in Java is that you can create
new classes that are built upon existing classes. When you inherit from
an existing class, you can reuse methods and fields of the parent class.
Moreover, you can add new methods and fields in your current class
also.
• Inheritance represents the IS-A relationship which is also known as
a parent-child relationship.
Why use inheritance in java

1) Method Overriding

2)Code Reusability.
Terms used in Inheritance
• Class: A class is a group of objects which have common properties. It
is a template or blueprint from which objects are created.
• Sub Class/Child Class: Subclass is a class which inherits the other
class. It is also called a derived class, extended class, or child class.
• Super Class/Parent Class: Superclass is the class from where a
subclass inherits the features. It is also called a base class or a parent
class.
• Reusability: As the name specifies, reusability is a mechanism which
facilitates you to reuse the fields and methods of the existing class
when you create a new class. You can use the same fields and methods
already defined in the previous class.
The syntax of Java Inheritance

class Subclass-name extends Superclass-name


{
//methods and fields
}
Java Inheritance Example
As Programmer is the subclass and
Employee is the superclass. The relationship
between the two classes is Programmer IS-A
Employee. It means that Programmer is a type
of Employee.
INHERITANCE Sample Program:
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
OUTPUT:
Programmer salary is:40000.0
Bonus of programmer is:10000
Benefits of Inheritance:
1) Inheritance helps in code reuse.
2) The child class may use the code defined in the parent class without re-
writing it.
3) Inheritance can save time and effort as the main code need not be written
again.
4) Inheritance provides a clear model structure which is easy to understand.
Syntax:
class Subclass-name extends Superclass-name
{
//methods and fields
}
• The extends keyword indicates that you are making a new class that derives
from an existing class. The meaning of "extends" is to increase the
functionality.
Types of Inheritance:
On the basis of class, there can be three types of inheritance in
java supported by extends keyword: single, multilevel and hierarchical.
Sample Program for Single Inheritance :
class Animal{
void eat(){
System.out.println("eating..."); } }
class Dog extends Animal{
void bark(){
System.out.println("barking...");
}}
class TestInheritance
{
public static void main(String args[])
{ Output:
Dog d=new Dog(); d.bark(); barking...
d.eat(); eating...
}}
Sample Program for Multilevel Inheritance :
class Animal {
void eat(){ System.out.println("eating..."); } }
class Dog extends Animal {
void bark(){ System.out.println("barking..."); } }
class BabyDog extends Dog {
void weep(){
System.out.println("weeping..."); } }
class TestInheritance2 {
public static void main(String args[]) { BabyDog Output:
d=new BabyDog(); d.weep(); weeping...
d.bark(); barking...
d.eat(); eating...
}. }
Sample Program for hierarchical Inheritance:
class Animal {
void eat(){ System.out.println("eating...");
}}
class Dog extends Animal {
void bark(){
System.out.println("barking..."); } }
class Cat extends Animal {
void meow(){
System.out.println("meowing..."); } }
class TestInheritance3 {
Output:
public static void main(String args[]) { meowing...
Cat c=new Cat(); c.meow(); eating...
c.eat(); //c.bark();//C.T.Error
}}
final keyword: The final keyword in java is used to restrict the user.
The java final keyword can be used in many contexts. Final can be:
1) variable
2) method
3) class
Sample Program for final variable:
class Bike{
final int speedlimit=90; //final variable
void run() {
speedlimit=400; }
public static void main(String args[]) {
Bike obj=new Bike();
obj.run();
}}
Output- Compile Time Error
Sample Program for final method-
class Bike{
final void run() { //final method
System.out.println("running");
}}
class Honda extends Bike {
void run() {
System.out.println("running safely with 100kmph"); }
public static void main(String args[]) {
Honda honda= new Honda(); honda.run();
}
}
Output- Compile Time Error
Sample Program for final class–
final class Bike{}
class Honda1 extends Bike{
void run() {
System.out.println("running safely with 100kmph");
}
public static void main(String args[]){
Honda1 honda= new Honda1();
honda.run();
}
}
Output- Compile Time Error
super Keyword - It is a reference variable which is used to refer
immediate parent class object and parent class data.
Sample Program –
class Person{ void display() {
System.out.println(id+" "+name+" "+salary); }
int id;
String name; }
class TestSuper5{
Person(int id,String name){ public static void main(String[] args){
this.id=id; Emp e1=new Emp(1,"ankit",45000);
this.name=name; }. } e1.display();
class Emp extends Person{ }
}
float salary;
Output –
Emp(int id,String name,float salary){
super(id,name);//reusing parent constructor 1 ankit 45000
this.salary=salary;
}
Polymorphism:

Polymorphism means "many forms", and it occurs when we have


many classes that are related to each other by inheritance. It is one of
the core concepts of OOPS in Java. It allows you define one interface
and have multiple implementations.
Polymorphism has two types-
Compile Time Polymorphism – method resolution at compile time
Method Overloading – Multiple methods with same name but
different signature.
Operator Overloading – we can’t overload operators in java.
Runtime Polymorphism – method resolution at runtime, achieved using
method overriding in subclasses.
Abstraction :
Abstraction is a process of hiding the
implementation details and showing only functionality
to the user.
-Another way, it shows only essential things to the
user and hides the internal details.

Abstract class – A class which is declared as abstract


keyword is known as an abstract class.
Sample Program –
Bike is an abstract class that contains only one abstract method run. Its
implementation is provided by the Honda class.
abstract class Bike {
abstract void run();
}
class Honda extends Bike{
void run(){
System.out.println("running safely"); }
public static void main(String args[]) {
Bike obj = new Honda();
obj.run();
}
}
Output - running safely
Package –
A java package is a group of similar types of classes, interfaces and sub- packages.
Package in java can be categorized in two form,
1) built-in package and
2) user- defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql
etc.
Here, we will have the detailed learning of creating and using user-defined packages.

Advantage of Java Package


-Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
-Java package provides access protection.
-Java package removes naming collision/conflicts.
Sample program using package keyword -

package mypack;
public class Simple{
public static void main(String args[]) {
System.out.println("Welcome to
package");
}
}
How to run java package program

You need to use fully qualified name e.g. Simple to run the class.
To Compile: javac Simple.java
To Run: java Simple

How to access package from another package?


There are three ways to access the package from outside the package.

import package.*;
import package.classname;
fully qualified name.
Sequence of the program must be package then import then class.
How to send the class file to another directory or drive?
package mypack; public class Simple{
public static void main(String args[]){

System.out.println("Welcome to package");
}}
To Compile: e:\sources> javac -d c:\classes Simple.java
To Run: To run this program from e:\source directory, you need to set
classpath of the directory where the class file resides.
e:\sources> set classpath=c:\classes;.;
e:\sources> java mypack.Simple
Another way to run this program by -classpath switch of java:

• The -classpath switch can be used with javac and java tool.
• To run this program from e:\source directory, you can use -
classpath switch of java that tells where to look for class file.

For example: e:\sources> java -classpath c:\classes mypack.Simple


JAVA Interface
An interface in Java is a blueprint of a class. It has static
constants and abstract methods. In other words, you can say that
interfaces can have abstract methods and variables. It cannot have a
method body. Java Interface also represents the IS-A relationship

Why use Java Interface


There are mainly three reasons to use interface. They are given
below.
1) It is used to achieve abstraction.
2) By interface, we can support the functionality of multiple inheritance.
3) It can be used to achieve loose coupling.

• In java programming, multiple and hybrid inheritance is supported through


interface only.
Syntax for Java Interfaces

interface {
// declare constant fields
// declare methods that abstract
// by default.
}
Uses of Interfaces in Java are mentioned below:

• It is used to achieve total abstraction.


• Since java does not support multiple inheritances in the case of
class, by using an interface it can achieve multiple inheritances.
• Any class can extend only 1 class, but can any class implement an
infinite number of interfaces.
• It is also used to achieve loose coupling.
• Interfaces are used to implement abstraction.
Relationship Between Class and Interface:

A class can extend another class similar to this an interface can extend
another interface. But only a class can extend to another interface, and
vice-versa is not allowed.
Difference Between Class and Interface:
Interface Variables in Java
• Java interfaces provide a way to define a contract or blueprint for
classes to implement. In addition to methods, interfaces can also
include variables.
• These variables, known as interface variables or constants, are a
fundamental aspect of Java interfaces.
• In Java, an interface variable is implicitly public, static, and final.
• This means that the variable's value cannot be changed once it is
assigned.
• Interface variables are accessible to all implementing classes,
promoting code reusability and standardization.
Example:
public interface Shape {
int DEFAULT_SIZE = 10;
void draw();
}

In this example, the Shape interface defines an interface variable


named DEFAULT_SIZE, which is assigned a value of 10.
Implementing classes can use this variable to provide a default size
for different shapes.
Java Inner Classes (Nested Classes)
• Java inner class or nested class is a class that is declared inside the
class or interface.
• We use inner classes to logically group classes and interfaces in one
place to be more readable and maintainable.
• Additionally, it can access all the members of the outer class, including
private data members and methods.
Syntax of Inner class
class Java_Outer_class{
//code
class Java_Inner_class{
//code
} }
Advantage of Java inner classes

1.Nested classes represent a particular type of relationship that is it can


access all the members (data members and methods) of the outer
class, including private.
2.Nested classes are used to develop more readable and maintainable
code because it logically group classes and interfaces in one place
only.
3.Code Optimization: It requires less code to write.
Java Anonymous inner class
• Java anonymous inner class is an inner class without a name and for
which only a single object is created.
• An anonymous inner class can be useful when making an instance of
an object with certain "extras" such as overloading methods of a class
or interface, without having to actually subclass a class.
• In simple words, a class that has no name is known as an anonymous
inner class in Java.
• It should be used if you have to override a method of class or
interface. Java Anonymous inner class can be created in two ways:
1.Class (may be abstract or concrete).
2.Interface
Java anonymous inner class example using class
TestAnonymousInner.java
abstract class Person{
abstract void eat();
}
class TestAnonymousInner{
public static void main(String args[]){
Person p=new Person(){
void eat(){System.out.println("nice fruits");}
};
p.eat();
}
}

You might also like