0% found this document useful (0 votes)
33 views77 pages

Unit 2

Uploaded by

jeenil8040
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)
33 views77 pages

Unit 2

Uploaded by

jeenil8040
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/ 77

Unit 2: INHERITANCE

Simula
Smalltalk
Java, C#, PHP, Python, C++, etc.
Object-Oriented Programming Concepts:
• Object
• Class
• Inheritance
• Polymorphism
• Abstraction
• Encapsulation
Difference between Object-based and object-oriented programming
language
How to create class
• Syntax to declare a class:
class <class_name>{
field;
method;
}
Instance variable in Java
Method in Java
new keyword in Java
Example of class
1. class Student{
2. int id;
3. String name;
4. }
5. class TestStudent1{
6. public static void main(String args[]){
7. Student s1=new Student();
8. System.out.println(s1.id);
9. System.out.println(s1.name);
10. } }
3-Ways to initialize object

• There are 3 ways to initialize object in Java.


1.By reference variable
2.By method
3.By constructor
Object and Class Example: Initialization through reference

1. class Student{
2. int id;
3. String name;
4. }
5. class TestStudent2{
6. public static void main(String args[]){
7. Student s1=new Student();
8. s1.id=101;
9. s1.name=“XYZ";
10. System.out.println(s1.id+" "+s1.name);//printing members with a white s
pace }
11.}
Object and Class Example: Initialization through method

class Student{
int rollno;
String name;
void insertRecord(int r, String n){
rollno=r;
name=n; }
void displayInformation(){System.out.println(rollno+" "+name);} }
class TestStudent4{
public static void main(String args[]){
Student s1=new Student();
Student s2=new Student();
s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan");
s1.displayInformation();
s2.displayInformation();
} }
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 constructor,
memory for the object is allocated in the memory.
• It is a special type of method which is used to initialize the object.
• Every time an object is created using the new() keyword, at least one
constructor is called.
• It calls a default constructor if there is no constructor available in the class.
In such case, Java compiler provides a default constructor by default.
• Rules for creating Java constructor
• There are two rules defined for the constructor.
1. Constructor name must be the same as its class name
2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and synchronized
• Teypes of Java constructors
• There are two types of constructors in Java:
1. Default constructor (no-arg constructor)
2. Parameterized constructor
Example of default constructor
class Bike1{
//creating a default constructor
Bike1()
{
System.out.println("Bike is created");}
//main method
public static void main(String args[]){
//calling a default constructor
Bike1 b=new Bike1();
}
}
Java Parameterized Constructor
//Java Program to demonstrate the use of the parameterized constructor.
class Student4{
int id;
String name;
//creating a parameterized constructor
Student4(int i,String n){
id = i;
name = n;
}
//method to display the values
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
//creating objects and passing values
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
//calling method to display the values of object
s1.display();
s2.display();
}
}
Constructor Overloading in Java

1. //Java program to overload constructors


2. class Student5{
3. int id;
4. String name;
5. int age;
6. //creating two arg constructor
7. Student5(int i,String n){
8. id = i;
9. name = n;
10. }
1. Student5(int i,String n,int a){

2. id = i;

3. name = n;

4. age=a; }

5. void display(){System.out.println(id+" "+name+" "+age);}

6. public static void main(String args[]){

7. Student5 s1 = new Student5(111,"Karan");

8. Student5 s2 = new Student5(222,"Aryan",25);

9. s1.display();

10. s2.display();

11. } }
this Keyword
There can be a lot of usage of Java this keyword. In Java, this
is a reference variable that refers to the current object.
this: to refer current class instance variable
• The this keyword can be used to refer current class instance
variable. If there is ambiguity between the instance variables and
parameters, this keyword resolves the problem of ambiguity.
For example
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
rollno=rollno;
name=name;
fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
1.class TestThis1{
2.public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}
Example with this keyword
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis2{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}
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
• For Method Overriding (so runtime polymorphism can be
achieved).
• For Code Reusability.
The syntax of Java Inheritance
1.class Subclass-name extends Superclass-name
2.{
3. //methods and fields
4.}
Example
1.class Employee{
2. float salary=40000;
3.}
4.class Programmer extends Employee{
5. int bonus=10000;
6. public static void main(String args[]){
7. Programmer p=new Programmer();
8. System.out.println("Programmer salary is:"+p.salary);
9. System.out.println("Bonus of Programmer is:"+p.bonus);
10.}
11.}
Types of inheritance in java
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[]){
Dog d=new Dog();
d.bark();
d.eat();
}}
Multilevel Inheritance Example
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 d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}
Hierarchical Inheritance Example
1.class Animal{
2.void eat(){System.out.println("eating...");}
3.}
4.class Dog extends Animal{
5.void bark(){System.out.println("barking...");}
6.}
7.class Cat extends Animal{
8.void meow(){System.out.println("meowing...");}
9.}
10.class TestInheritance3{
11.public static void main(String args[]){
12.Cat c=new Cat();
13.c.meow();
14.c.eat();
15.//c.bark();//C.T.Error
16.}}
Why multiple inheritance is not supported in java?

• To reduce the complexity and simplify the language, multiple inheritance is not
supported in java.

• Consider a scenario where A, B, and C are three classes. The C class inherits A
and B classes. If A and B classes have the same method and you call it from child
class object, there will be ambiguity to call the method of A or B class.

• Since compile-time errors are better than runtime errors, Java renders compile-
time error if you inherit 2 classes. So whether you have same method or different,
there will be compile time error.
Use of Final

The keyword final has three uses. First, it can be used to


create the equivalent of a named constant. The other two
uses of final apply to inheritance.
1. Final Variable:-
A variable can be declared as final. Doing so prevents its
contents from being modified. This means that you must
initialize a final variable when it is declared. (In this usage,
final is similar to const in C/C++/C#.)
For example:- final int FILE_NEW = 1;
Using final with Inheritance
a) Using final to Prevent Overriding
While method overriding is one of Java’s most powerful
features, there will be times when you will want to prevent it
from occurring. To disallow a method from being overridden,
specify final as a modifier at the start of its declaration.
Methods declared as final cannot be overridden.

class A {
final void meth() {
System.out.println("This is a final method.");
}}
class B extends A {
void meth() { // ERROR! Can't override.
System.out.println("Illegal!");
}}
Using final to Prevent Inheritance
Sometimes you will want to prevent a class from being inherited. To
do this, precede the class declaration with final. Declaring a class as
final implicitly declares all of its methods as final, too. As you might
expect, it is illegal to declare a class as both abstract and final since
an abstract class is incomplete by itself and relies upon its subclasses
to provide complete implementation.
final class A {
// ... }
// The following class is illegal.
class B extends A { // ERROR! Can't subclass A
// ... }
Using Abstract Classes

• There are situations in which you will want to define a


superclass that declares the structure of a given abstraction
without providing a complete implementation of every
method. That is, sometimes you will want to create a
superclass that only defines a generalized form that will be
shared by all of its subclasses, leaving it to each subclass to fill
in the details. Such a class determines the nature of the
methods that the subclasses must implement.
Contd..
// A Simple demonstration of abstract.
abstract class A {
abstract void callme();
// concrete methods are still allowed in abstract classes
void callmetoo() {
System.out.println("This is a concrete method.");
} }
class B extends A {
void callme() {
System.out.println("B's implementation of callme.");
} }
class AbstractDemo {
public static void main(String args[]) {
B b = new B();
b.callme();
b.callmetoo();
} }
Using object as argument
So far we have only been using simple types as parameters to methods.
However, it is both correct and common to pass objects to methods. For
example,
// Objects may be passed to methods.
class Test {
int a, b;
Test(int i, int j) {
a = i;
b = j;
}
// return true if o is equal to the invoking object
boolean equals(Test o) {
if(o.a == a && o.b == b) return true;
else return false;
}
}
8/29/2024 [email protected] 1
Contd…
class PassOb {
public static void main(String args[]) {
Test ob1 = new Test(100, 22);
Test ob2 = new Test(100, 22);
Test ob3 = new Test(-1, -1);
System.out.println("ob1 == ob2: " + ob1.equals(ob2));
System.out.println("ob1 == ob3: " + ob1.equals(ob3));
}
}
This program generates the following output:
ob1 == ob2: true
ob1 == ob3: false
8/29/2024 2
Contd…
One of the most common uses of object parameters involves
constructors. Frequently you will want to construct a new
object so that it is initially the same as some existing object. To
do this, you must define a constructor that takes an object of its
class as a parameter

8/29/2024 3
Recursion
Java supports recursion. Recursion is the process of
defining something in terms of itself. As it relates to
Java programming, recursion is the attribute that
allows a method to call itself. A method that calls
itself is said to be recursive.
class Factorial {
// this is a recursive function
int fact(int n) {
int result;
if(n==1) return 1;
result = fact(n-1) * n;
return result;
}}
8/29/2024 4
Contd…
class Recursion {
public static void main(String args[]) {
Factorial f = new Factorial();
System.out.println("Factorial of 3 is " + f.fact(3));
System.out.println("Factorial of 4 is " + f.fact(4));
System.out.println("Factorial of 5 is " + f.fact(5));
}
}

8/29/2024
Method overriding
• You can override any method of the base class
by declaring the method in your subclass with
the same signature (same return type, method
name, and parameter list)
• If you have overridden a base class method
and wish to access the base class version of it,
you can again use the super keyword

8/29/2024 6
Overriding example
class A
{ public void sum()
{
System.out.println("this is the sum of A");
}
}

class B extends A
{

public void sum()


{
System.out.println("this is the sum of B");
} }
class abc
{ public static void main(String args[])
{ B b1=new B();
b1.sum();

} }
8/29/2024 7
Super keyword
• If your method overrides one of its superclass's
methods, you can invoke the overridden method
through the use of the keyword super. You can also
use super to refer to a hidden field.
class A
{ public void sum()
{
System.out.println("this is the sum of A");
}
}

8/29/2024 8
Contd…
class B extends A
{

public void sum()


{
super. Sum();
System.out.println("this is the sum of B");
} }
class abc
{ public static void main(String args[])
{ B b1=new B();
b1.sum();

} }

8/29/2024 9
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.

• 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 determination is made at run time.
• When different types of objects are referred to, different versions of
an overridden method will be called.
8/29/2024 10
Dynamic method dispatch
class A
{
void callme() {
System.out.println("Inside A's callme method");
} }
class B extends A {
// override callme()
void callme() {
System.out.println("Inside B's callme method");
} }
class C extends A {
// override callme()
void callme() {
System.out.println("Inside C's callme method");
}
}
8/29/2024 11
Contd….
class Dispatch {
public static void main(String args[]) {
A a = new A(); // object of type A
B b = new B(); // object of type B
C c = new C(); // object of type C
A r; // obtain a reference of type A
r = a; // r refers to an A object
r.callme(); // calls A's version of callme
r = b; // r refers to a B object
r.callme(); // calls B's version of callme
r = c; // r refers to a C object
r.callme(); // calls C's version of callme
} }
8/29/2024 [email protected] 12
output
Inside A’s callme method
Inside B’s callme method
Inside C’s callme method

8/29/2024 13
Using Command-Line Arguments
• Sometimes you will want to pass information into a program
when you run it. This is accomplished by passing command-line
arguments to main( ). A command-line argument is the
information that directly follows the program’s name on the
command line when it is executed. To access the command-line
arguments inside a Java program is quite easy—they are stored
as strings in the String array passed to main( )

8/29/2024 14
// Display all command-line arguments.
class CommandLine {
public static void main(String args[]) {
for(int i=0; i<args.length; i++)
System.out.println("args[" + i + "]: " +
args[i]);
}
}

8/29/2024 15
This Keyword
• Sometimes a method will need to refer to the
object that invoked it. To allow this, Java
defines the this keyword.
• this can be used inside any method to refer
to the current object. That is, this is always a
reference to the object on which the method
was invoked.
• You can use this anywhere a reference to an
object of the current class’ type is permitted.
8/29/2024 16
Box(double w, double h, double d)
{
this.width = w;
this.height = h;
this.depth = d;
}

8/29/2024 17
Garbage Collection in java
• Since objects are dynamically allocated by using the new
operator, you might be wondering how such objects are
destroyed and their memory released for later
reallocation.
• In some languages, such as C++, dynamically allocated
objects must be manually released by use of a delete
operator. Java takes a different approach.
• It handles deallocation for you automatically. The
technique that accomplishes this is called garbage
collection.
• It works like this: when no references to an object exist,
that object is assumed to be no longer needed, and the
memory occupied by the object can be reclaimed.
18
Finalize() Method
• Sometimes an object will need to perform
some action when it is destroyed. For
example, if an object is holding some non-Java
resource such as a file handle or window
character font, then you might want to make
sure these resources are freed before an
object is destroyed. To handle such situations,
Java provides a mechanism called finalization.
By using finalization, you can define specific
actions that will occur when an object is just
about to be reclaimed by the garbage
collector.
8/29/2024 19
Syntax of finalize() method
protected void finalize( )
{
// finalization code here
}

8/29/2024 20
Static keyword in java
The static keyword in Java is used for memory management
mainly.
We can apply static keyword with variables, methods, blocks
and nested classes. The static keyword belongs to the class
than an instance of the class.
The static can be:
1. Variable (also known as a class variable)
2. Method (also known as a class method)
3. Block
4. Nested class
Java static variable

If you declare any variable as static, it is known as a static variable.


4.5M
489ackage in Java
•The static variable can be used to refer to the common property of all objects
(which is not unique for each object),
for example, the company name of employees, college name of students, etc.
•The static variable gets memory only once in the class area at the time of
class loading.
Advantages of static variable
It makes your program memory efficient (i.e., it saves memory).
Understanding the problem without static variable
class Student{
int rollno; String name;

String college="ITS";

Suppose there are 500 students in my college, now all instance


data members will get memory each time when the object is
created. All students have its unique rollno and name, so instance
data member is good in such case. Here, "college" refers to the
common property of all objects. If we make it static, this field will
get the memory only once.
Example of static variable
class Student{

int rollno;//instance variable

String name;

static String college ="ITS";//static variable

Student(int r, String n)

{ rollno = r; name = n; }

void display () { System.out.println(rollno+" "+name+" "+college);} }

public class TestStaticVariable1{

public static void main(String args[])

{ Student s1 = new Student(111,"Karan"); Student s2 = new Student(222,"Aryan");

s1.display(); s2.display();

} }
Output:
111 Karan ITS
222 Aryan ITS
Program of the counter without static variable
//Java Program to demonstrate the use of an instance variable
//which get memory each time when we create an object of the class.
class Counter{
int count=0;//will get memory each time when the instance is created
Counter(){
count++;//incrementing value
System.out.println(count);
}
public static void main(String args[]){ //Creating objects
Counter c1=new Counter(); Counter c2=new Counter();
Counter c3=new Counter(); }
}
• In the above example, we have created an instance variable
named count which is incremented in the constructor. Since
instance variable gets the memory at the time of object
creation, each object will have the copy of the instance
variable. If it is incremented, it won't reflect other objects.
So each object will have the value 1 in the count variable.
Program of counter by static variable
As we have mentioned above, static variable will get the memory only once, if any object
changes the value of the static variable, it will retain its value.
//Java Program to illustrate the use of static variable which is shared with all
objects.
class Counter2{
static int count=0;//will get memory only once and retain its value
Counter2(){
count++;//incrementing the value of static variable
System.out.println(count);
}
public static void main(String args[]){
Counter2 c1=new Counter2();
Counter2 c2=new Counter2();
Counter2 c3=new Counter2(); }
}
Java static method

• If you apply static keyword with any method, it is known as static


method.
o A static method belongs to the class rather than the object of a
class.
o A static method can be invoked without the need for creating an
instance of a class.
o A static method can access static data member and can change
the value of it.
class Student{
int rollno;
String name;
static String college = "ITS"; //static method to change the value of static variable
static void change(){
college = "BBDIT";
}
//constructor to initialize the variable
Student(int r, String n){
rollno = r;
name = n;
}
//method to display values
void display(){System.out.println(rollno+" "+name+" "+college);} }
//Test class to create and display the values of object
public class TestStaticMethod{
public static void main(String args[]){
Student.change();//calling change method
//creating objects
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
Student s3 = new Student(333,"Sonoo"); //calling display method
s1.display();
s2.display();
s3.display();
}
}
There are two types of modifiers in Java: access modifiers and non-access modifiers.

The access modifiers in Java specifies the accessibility or scope of a field, method, constructor, or
class. We can change the access level of fields, constructors, methods, and class by applying the
access modifier on it.

There are four types of Java access modifiers:


1. Private: The access level of a private modifier is only within the class. It cannot be accessed from
outside the class.
2. Default: The access level of a default modifier is only within the package. It cannot be accessed
from outside the package. If you do not specify any access level, it will be the default.
3. Protected: The access level of a protected modifier is within the package and outside the package
through child class. If you do not make the child class, it cannot be accessed from outside the
package.
4. Public: The access level of a public modifier is everywhere. It can be accessed from within the
class, outside the class, within the package and outside the package.

There are many non-access modifiers, such as static, abstract, synchronized, native, volatile, transient,
etc. Here, we are going to learn the access modifiers only.
Interface in Java
• Java does not support multiple inheritance as
C++ supports
• Java supports an alternative approach to this
OOP feature known as interface
• What is Interface?
– An interface is basically a kind of class. Like
classes, an interface contains members and
methods; unlike classes, in interface all members
are final and all methods are abstract

Thursday, August 29, 2024 1


Why use Java interface?
• There are mainly three reasons to use
interface. They are given below.
• It is used to achieve abstraction.
• By interface, we can support the
functionality of multiple inheritance.
• It can be used to achieve loose coupling.
Syntax for Defining an Interface
• Following is the syntax to define an Interface
interface interfaceName [extends name1, ..... ]
{
[ Variable(s) declaration;]
[ Method(s) declaration;]
}
Variable in interface is declared as:
static final type varName = value;

Method in interface is declared as:


Retun-type methodName(parameter list);

Thursday, August 29, 2024 3


Defining an Interface: Examples
• Example 1
interface anItem
{
static final int code = 101;
static final String itemName = “Computer”
void recordEntry( );
}
• Example 2
interface curves extends circle, ellipse
{
static final float pi = 3.142F;
float area(int a, int b);
void print( );
}

Thursday, August 29, 2024 4


The relationship between classes and
interfaces

• As shown in the figure given below, a class extends


another class, an interface extends another interface, but
a class implements an interface.
Implementation of classes with Interface

• Syntax

class className [extends superClassName]


{
[implements interfaceName1, interfaceName2, ...]
{
Class body
}

Thursday, August 29, 2024 6


Implementing Interface
Interface area
{
final static float pi= 3.14f
Float compute (float x, float y);
}
Class rectangle implements area
{
Public float compute( float x, float y)
{
Return (x*y);
} }
Class interfacetest
{
Public static void main( String args[])
{
rectangle rect1 = new rectangle();
Rectangle cir= new Rectangle();
area area1;
area1= rect1;
System.out.println(“ Area of rectangle is “
+area1.compute(10,20));

area1=cir;
System.out.println(“ Area of circle=“
+area1.compute(10,0));
}
}
Implementing Multiple interface

Class student
{
int rollno;
void getnumber (int n)
{
rollno = n;
} void putnumber()
{
System.out.println(“rollno” +rollno);
}}
Class Test extends student
{ float part1, part2;
Void getmarks ( float m1, float m2)
{
part1=m1;
part2=m2;
}
Void putmarks()
{
System.out.println(“part1” +part11);
System.out.println(“part2” +part2);
} }
interface sports
{
Float sportwt= 6.0;
Void putwt();
}
Class results extends test implements sports
{
Float total;
Public void putwt()
{
System.out.println(“sports wt” +sportwt);
}
Void display()
{
total= part1+part2+sportwt;
putnumber( );
Putmarks( );
Putwt( );
System.out.println(“total score” +total);
} }
class hybride
{ public static void main(String args[])
{ results R1= new results();
R1.getnumber(1280)
R1.getmarks(27.0, 33.5);
R1.display();
} }

You might also like