0% found this document useful (0 votes)
5 views36 pages

Java Unit - II

Inheritance in Java allows a derived class to inherit properties from a base class using the 'extends' keyword, and it can be categorized into types such as single, multilevel, hierarchical, and multiple inheritance (the latter is not supported in Java). Member access rules are governed by access modifiers (public, protected, default, private) that determine the visibility of class members. The document also covers method overloading, overriding, abstract classes, dynamic method dispatch, the final keyword, and the usage of 'this' and 'super' keywords in Java.

Uploaded by

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

Java Unit - II

Inheritance in Java allows a derived class to inherit properties from a base class using the 'extends' keyword, and it can be categorized into types such as single, multilevel, hierarchical, and multiple inheritance (the latter is not supported in Java). Member access rules are governed by access modifiers (public, protected, default, private) that determine the visibility of class members. The document also covers method overloading, overriding, abstract classes, dynamic method dispatch, the final keyword, and the usage of 'this' and 'super' keywords in Java.

Uploaded by

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

UNIT - II

INHERITANCE

Definition-
 Inheritance is a mechanism in java by which derived class can
borrow the properties of base class and at the same time the
derived class may have some additional properties.
 The inheritance can be achieved by incorporating the
definition of one class into another using the keyword extends.

CONCEPT OF INHERITANCE

 The inheritance is a mechanism in


which the child class is derived
from a parent class.
 This derivation is using the
keyword extends.
For example:
Class A <- base class
{
…….
}
Class B extends A
{
---- //uses of properties of A
}

TYPES OF INHERITANCE

1.Single Inheritance: refers to a sub and super class relationship


where a class extends the another class.
2.Multilevel inheritance: refers to a sub and super class
relationship where a class extends the subclass. For example class C
extends class B and class B extends class A.
3.Hierarchical inheritance: refers to a sub and super class
relationship where more than one classes extends the same class.
For example, classes B, C & D extends the same class A.
4.Multiple Inheritance: refers to the concept of one class extending
more than one classes, which means a sub class has two super
classes. For example class C extends both classes A and B. Java
doesn’t support multiple inheritance.
MEMBER ACCESS RULES

In Java, member access rules govern the visibility and accessibility


of fields, methods, and inner classes defined in a class. These rules
are primarily controlled by access modifiers and determine how
members can be accessed from other classes, including subclasses
and classes in different packages.
Access Modifiers in Java
There are four main access modifiers in Java:
1. public
2. protected
3. default (no modifier)
4. private
Each modifier defines different levels of accessibility for class
members (fields, methods, and constructors).
1. public Access Modifier
 Visibility: The member is accessible from any other class in
the same package or in different packages.
 Use case: Used when you want the member to be universally
accessible.
class MyClass {
public int x; // Can be accessed from anywhere
}
class AnotherClass {
public static void main(String[] args) {
MyClass obj = new MyClass();
obj.x = 10; // Accessing the public member
}
}
2. protected Access Modifier
 Visibility: The member is accessible within its own package
and by subclasses (including those in different packages).
 Use case: Used when you want a member to be accessible to
subclasses, but you don’t want to expose it globally.
class Animal {
protected String name; // Accessible within the same package and
by subclasses
}
class Dog extends Animal {
void setName(String name) {
this.name = name; // Accessing the protected member from the
superclass
}
}
3. default (Package-Private) Access Modifier
 Visibility: The member is accessible only within the same
package. If no access modifier is specified, Java assumes
package-private access by default.
 Use case: Used when you want to limit access to the members
of a class within the same package, but not from outside.
class MyClass {
int x; // Default access (package-private), accessible only within
the same package
}
class AnotherClass {
public static void main(String[] args) {
MyClass obj = new MyClass();
obj.x = 10; // Can be accessed because it's in the same package
}
}
4. private Access Modifier
 Visibility: The member is accessible only within the same
class. It cannot be accessed from any other class, not even
subclasses.
 Use case: Used to encapsulate the internal state of a class and
to prevent other classes from modifying it directly.
class MyClass {
private int x; // Can only be accessed within this class
private void display() {
System.out.println("Private method");
}
}

class AnotherClass {
public static void main(String[] args) {
MyClass obj = new MyClass();
// obj.x = 10; // Error: x has private access
// obj.display(); // Error: display() has private access
}
}
Summary of Access Modifiers and Their Visibility
Access Same Same Subclasses Other Classes
Modifier Class Package (Different (Different
Package) Package)
public Yes Yes Yes Yes
protected Yes Yes Yes No
default Yes Yes No No
(package-
private)
private Yes No No No
Additional Notes:
 Accessing private members: Private members cannot be
accessed directly from outside the class. However, they can be
accessed using public getter and setter methods.
 Inheritance and access modifiers: A subclass can access
members of the superclass only if they are public or protected.
default members are not accessible outside the package, and
private members are never accessible outside the class.
 Static Members: Static members (variables and methods)
follow the same access rules as instance members. However,
static members are accessed using the class name and are not
tied to a specific object.

METHOD OVERLOADING

Def- Method Overloading means to define different methods with


the same name but different parameters lists and different
definitions. It is used when objects are required to perform similar
task but using different input parameters that may vary either in
number or type of arguments. Overloaded methods may have
different return types. It is a way of achieving polymorphism in java.
int add( int a, int b)
// prototype 1
int add( int a , int b , int c)
// prototype 2
double add( double a, double b)
// prototype 3
Example :
class Sample
{
int addition(int i, int j)
{
return i + j ;
}
String addition(String s1, String s2)
{
return s1 + s2;
}
double addition(double d1, double d2)
{
return d1 + d2;
}
}
class AddOperation
{
public static void main(String args[])
{
Sample sObj = new Sample();
System.out.println(sObj.addition(1,2));
System.out.println(sObj.addition("Hello ","World"));
System.out.println(sObj.addition(1.5,2.2));
}
}

OVERRIDING(METHOD OVERRIDING)

If subclass (child class) has the same method as declared in the


parent class, it is known as method overriding in java. If subclass
provides the specific implementation of the method that has been
provided by one of its parent class, it is known as method
overriding. Method overriding is used for runtime polymorphism.
Example:
class Vehicle
{
void run()
{
System.out.println("Vehicle is running");
}
}
class Bike extends Vehicle
{
void run()
{
System.out.println("Bike is running safely");
}
public static void main(String args[])
{
Bike2 obj = new Bike2();
obj.run();
}

ABSTRACT METHODS AND CLASSES

Abstract methods, similar to methods within an interface, are


declared without any implementation. They are declared with the
purpose of having the child class provide implementation. They
must be declared within an abstract class. A class declared abstract
may or may not include abstract methods. They are created with the
purpose of being a super class.
Syntax:
modifier abstract class className {
//declare fields
//declare methods
abstract dataType methodName();
}
modifier class childClass extends className {
dataType methodName(){}
}
 Abstract classes and methods are declared with the 'abstract'
keyword. Abstract classes can only be extended, and cannot be
directly instantiated.
 Abstract classes provide a little more than interfaces.
Interfaces do not include fields and super class methods that
get inherited, whereas abstract classes do. This means that an
abstract class is more closely related to a class which extends
it, than an interface is to a class that implements it.
Example:
public abstract class Animal
{
String name;
abstract String sound(); //all classes that implement Animal must
have a sound method
}
public class Cat extends Animal
{
public Cat()
{
this.name = "Garfield";
}
public String sound()
{
//implemented sound method from the abstract class & method
return "Meow!";
}
}

DYNAMIC METHOD DISPATCH (RUNTIME


POLYMORPHISM)

Dynamic method dispatch is a mechanism by which a call to an


overridden method is resolved at runtime. This is how java
implements runtime polymorphism. When an overridden method is
called by a reference, java determines which version of that method
to execute based on the type of object it refer to. In simple words the
type of object which it referred determines which version of
overridden method will be called.
Example:
class Game
{
public void type()
{ System.out.println("Indoor & outdoor"); }
}
Class Cricket extends Game
{
public void type()
{
System.out.println("outdoor game");
}
public static void main(String[] args)
{
Game gm = new Game();
Cricket ck = new Cricket();
gm.type();
ck.type();
gm=ck;
//gm refers to Cricket object
gm.type(); //calls Cricket's version of type
}

final KEYWORD

1. Final Variables
When a variable is declared as final, its value cannot be changed
after initialization. It is a constant, and once assigned, its value
remains constant throughout the program.

 Instance Variables: You can assign the value only once, either
at the time of declaration or in the constructor.
 Local Variables: Must be assigned a value before use, and it
cannot be reassigned.
 Static Variables: Can be assigned once and remain constant
across all instances of the class.

final int MAX_VALUE = 100; // The value cannot be changed


2. Final Methods
When a method is declared as final, it cannot be overridden by
subclasses. This is useful when you want to prevent any
modification to the method's behavior in child classes.

class Parent {
final void display() {
System.out.println("This is a final method.");
}
}
class Child extends Parent {
// This will cause a compile-time error
// void display() {
// System.out.println("Cannot override this method.");
// }
}
3. Final Classes
A final class cannot be subclassed or extended. This is useful when
you want to create an immutable class (like String in Java) that
cannot be modified or extended.

final class ImmutableClass {


// Class implementation
}
// The following would cause a compile-time error:
// class SubClass extends ImmutableClass { }
4. Final Parameters
When a method parameter is declared as final, it cannot be
reassigned within the method. However, the object it references can
still be modified (if it's mutable).

void method(final int x) {


// x = 5; // Error: cannot assign a value to final variable x
}
 final variable: Constant value that cannot be changed.
 final method: Method that cannot be overridden.
 final class: Class that cannot be extended.
 final parameter: Parameter whose value cannot be reassigned
within the method.
USAGE OF this and super KEYWORDS

1. this Keyword in Java


The this keyword refers to the current instance of a class. It is
primarily used in the following scenarios:
a) Referring to the current object
When you want to refer to the current instance of the class, this can
be used. It is implicit in many cases but can be explicitly stated.
class Example {
int x;
Example(int x) {
this.x = x; // Refers to the current object's field 'x'
}
void display() {
System.out.println("Value of x: " + this.x);
}
}
public class Main {
public static void main(String[] args) {
Example obj = new Example(5);
obj.display(); // Output: Value of x: 5
}
}
In the constructor above, this.x refers to the instance variable x of
the current object, while x without this refers to the method
parameter.
b) Calling other constructors in the same class (Constructor
Chaining)
You can use this() to call another constructor in the same class. This
is known as constructor chaining. It helps avoid code duplication.
class Example {
int x;
int y;
Example() {
this(0, 0); // Calls another constructor with two parameters
}
Example(int x, int y) {
this.x = x;
this.y = y;
}
}
c) Returning the current object
this can also be used to return the current object from a method,
allowing method chaining.
class Example {
int value;
Example setValue(int value) {
this.value = value;
return this; // Returns the current object
}
}
public class Main {
public static void main(String[] args) {
Example obj = new Example();
obj.setValue(10).setValue(20); // Method chaining
}
}
2. super Keyword in Java
The super keyword refers to the superclass (parent class) of the
current object. It is used to access superclass members (fields,
methods, and constructors) that are inherited by the subclass.
Below are the main uses of super:

a) Accessing superclass methods


If a subclass overrides a method from the superclass, you can use
super to invoke the method of the superclass.

class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Dog barks");
}
void callSuperMethod() {
super.sound(); // Calls the method in the Animal class
}
}
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.sound(); // Output: Dog barks
dog.callSuperMethod(); // Output: Animal makes a sound
}
}
b) Accessing superclass constructors
super() is used to call a constructor of the superclass. If the
superclass does not have a no-argument constructor, you need to
call a constructor with arguments using super(arg1, arg2, ...) within
the subclass constructor.
class Animal {
Animal(String name) {
System.out.println("Animal's name is " + name);
}
}
class Dog extends Animal {
Dog() {
super("Buddy"); // Calls the superclass constructor with a
String argument
System.out.println("Dog's constructor");
}
}
public class Main {
public static void main(String[] args) {
Dog dog = new Dog(); // Output: Animal's name is Buddy
// Dog's constructor
}
}
c) Accessing superclass fields
If a subclass has fields that shadow (or hide) fields from the
superclass, you can use super to access the superclass's fields.

class Animal {
String name = "Animal";
}
class Dog extends Animal {
String name = "Dog";
void printNames() {
System.out.println("Subclass name: " + name); // Refers to
Dog's name
System.out.println("Superclass name: " + super.name); //
Refers to Animal's name
}
}
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.printNames();
}
}
Output:
Subclass name: Dog
Superclass name: Animal
Summary of this and super Keywords:
Keyword Usage
this 1. Refers to the current instance of the class. 2. Used to
call another constructor in the same class (constructor
chaining). 3. Can be used to return the current object
(method chaining).
super 1. Refers to the superclass of the current object. 2. Used
to call a superclass method (especially if overridden in
the subclass). 3. Used to access a superclass
constructor. 4. Used to access fields from the
superclass that are hidden by subclass fields.

 this: Deals with the current object.


 super: Deals with the parent class and allows you to access or
invoke superclass methods, constructors, and fields.

PACKAGES
Packages are containers for classes that are used to keep the class
name space compartmentalized. For example, a package allows you
to create a class named List, which you can store in your own
package without concern that it will collide with some other class
named List stored elsewhere. Packages are stored in a hierarchical
manner and
are explicitly imported into new class definitions.

DEFINING A PACKAGE

To create a package is quite easy: simply include a package


command as the first statement in a Java source file. Any classes
declared within that file will belong to the specified package. The
package statement defines a name space in which classes are stored.
If you omit the package statement, the class names are put into the
default package, which has no name. (This is why you haven’t had to
worry about packages before now.) While the default package is fine
for short, sample programs, it is inadequate for real applications.
Most of the time, you will define a package for your code.
This is the general form of the package statement:
package pkg;

Here, pkg is the name of the package. For example, the following
statement creates a package called MyPackage.
package MyPackage;
 Java uses file system directories to store packages. For
example, the .class files for any classes you declare to be part of
MyPackage must be stored in a directory called MyPackage.
 Remember that case is significant, and the directory name
must match the package name exactly.
 More than one file can include the same package statement.
The package statement simply specifies to which package the
classes defined in a file belong. It does not exclude other
classes in other files from being part of that same package.
Most real-world packages are spread across many files.
 You can create a hierarchy of packages. To do so, simply
separate each package name from the one above it by use of a
period. The general form of a multileveled package statement
is shown here:
package pkg1[.pkg2[.pkg3]];
 A package hierarchy must be reflected in the file system of
your Java development system. For example, a package
declared as
package java.awt.image;
needs to be stored in java\awt\image in a Windows environment.
Be sure to choose your package names carefully. You cannot rename
a package without renaming the directory in which the classes are
stored.
A Short Package Example
Keeping the preceding discussion in mind, you can try this simple
package:
// A simple package
package MyPack;
class Balance {
String name;
double bal;
Balance(String n, double b) {
name = n;
bal = b;
}
void show() {
if(bal<0)
System.out.print("--> ");
System.out.println(name + ": $" + bal);
}
}
class AccountBalance {
public static void main(String args[]) {
Balance current[] = new Balance[3];
current[0] = new Balance("K. J. Fielding", 123.23);
current[1] = new Balance("Will Tell", 157.02);
current[2] = new Balance("Tom Jackson", -12.33);
for(int i=0; i<3; i++) current[i].show();
}
}
Call this file AccountBalance.java and put it in a directory called
MyPack

ACCESS PROTECTION

In the preceding chapters, you learned about various aspects of


Java’s access control mechanism and its access specifiers. For
example, you already know that access to a private member of a
class is granted only to other members of that class. Packages add
another dimension to access control. As you will see, Java provides
many levels of protection to allow fine-grained control over the
visibility of variables and methods within classes, subclasses, and
packages. Classes and packages are both means of encapsulating and
containing the name space and scope of variables and methods.
Packages act as containers for classes and other subordinate
packages. Classes act as containers for data and code. The class is
Java’s smallest unit of abstraction. Because of the interplay between
classes and packages, Java addresses four categories of visibility for
class members:
• Subclasses in the same package
• Non-subclasses in the same package
• Subclasses in different packages
• Classes that are neither in the same package nor subclasses
The three access specifiers, private, public, and protected, provide
a variety of ways to produce the many levels of access required by
these categories. Table 9-1 sums up the interactions.
While Java’s access control mechanism may seem complicated, we
can simplify it as follows. Anything declared public can be accessed
from anywhere. Anything declared private cannot be seen outside
of its class. When a member does not have an explicit access
specification, it is visible to subclasses as well as to other classes in
the same package.
This is the default access. If you want to allow an element to be seen
outside your current package, but only to classes that subclass your
class directly, then declare that element protected.
IMPORTING PACKAGES

Java includes the import statement to bring certain classes, or entire


packages, into visibility. Once imported, a class can be referred to
directly, using only its name. The import statement is a convenience
to the programmer and is not technically needed to write a complete
Java program. If you are going to refer to a few dozen classes in your
application, however, the import statement will save a lot of typing.
In a Java source file, import statements occur immediately following
the package statement (if it exists) and before any class definitions.
This is the general form of the import statement:
import pkg1[.pkg2].(classname|*);
Here, pkg1 is the name of a top-level package, and pkg2 is the name
of a subordinate package inside the outer package separated by a
dot (.). There is no practical limit on the depth of a package
hierarchy, except that imposed by the file system. Finally, you
specify either an explicit classname or a star (*), which indicates that
the Java compiler should import the entire package. This code
fragment shows both forms in use:
import java.util.Date;
import java.io.*;
This is equivalent to the following line being at the top of all of your
programs:
import java.lang.*;
For example, this fragment uses an import statement:
import java.util.*;
class MyDate extends Date {
}
The same example without the import statement looks like this:
class MyDate extends java.util.Date {
}
In this version, Date is fully-qualified
INTERFACES

Using the keyword interface, you can fully abstract a class’ interface
from its implementation. That is, using interface, you can specify
what a class must do, but not how it does it. Interfaces are
syntactically similar to classes, but they lack instance variables, and
their methods are declared without any body.
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.

DEFINING AN INTERFACE

An interface is defined much like a class. This is the general form of


an interface:
access 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;
}
 When no access specifier is included, then default access
results, and the interface is only available to other members of
the package in which it is declared. When it is declared as
public, the interface can be used by any other code.
 In this case, the interface must be the only public interface
declared in the file, and the file must have the same name as
the interface. name is the name of the interface, and can be any
valid identifier. Notice that the methods that are declared have
no bodies. They end with a semicolon after the parameter list.
 They are, essentially, abstract methods; there can be no default
implementation of any method specified within an interface.
Each class that includes an interface must implement all of the
methods.
 Variables can be declared inside of interface declarations. They
are implicitly final and static, meaning they cannot be
changed by the implementing class. They must also be
initialized. All methods and variables are implicitly public.
Here is an example of an interface definition. It declares a simple
interface that contains one method called callback( ) that takes a
single integer parameter.
interface Callback {
void callback(int param);
}

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 the 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
}
If a class implements more than one interface, the interfaces are
separated with a comma. If a class implements two interfaces that
declare the same method, then the same method will be used by
clients of either interface. The methods that implement an interface
must be declared public. Also, the type signature of the
implementing method must match exactly the type signature
specified in the interface definition.
Here is a small example class that implements the Callback
interface shown earlier.
class Client implements Callback {
// Implement Callback's interface
public void callback(int p) {
System.out.println("callback called with " + p);
}
}
Notice that callback( ) is declared using the public access specifier.

EXTENDING

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:
// One interface can extend another.
interface A {
void meth1();
void meth2();
}
// B now includes meth1() and meth2() -- it adds meth3().
interface B extends A {
void meth3();
}
// This class must implement all of A and B
class MyClass implements B {
public void meth1() {
System.out.println("Implement meth1().");
}
public void meth2() {
System.out.println("Implement meth2().");
}
public void meth3() {
System.out.println(“Implement meth3().”);
}}
Class IFExtend {
Public static void main(String arg[]) {
MyClass ob = new MyClass();
Ob.meth1();
Ob.meth2();
Ob.meth3();
}
}

You might also like