0% found this document useful (0 votes)
56 views35 pages

Chap 4, Interf - Pack

The document discusses inner classes, static classes, final variables, methods and classes in Java. It provides examples of how to declare and use inner classes and static inner classes. It explains that inner classes can access private members of the outer class and must be instantiated using an outer class instance. It also discusses how static variables and methods can be accessed without object instantiation and are common across all class instances. It describes how final variables cannot be reassigned once initialized and final methods cannot be overridden in subclasses.

Uploaded by

birhanu gebisa
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)
56 views35 pages

Chap 4, Interf - Pack

The document discusses inner classes, static classes, final variables, methods and classes in Java. It provides examples of how to declare and use inner classes and static inner classes. It explains that inner classes can access private members of the outer class and must be instantiated using an outer class instance. It also discusses how static variables and methods can be accessed without object instantiation and are common across all class instances. It describes how final variables cannot be reassigned once initialized and final methods cannot be overridden in subclasses.

Uploaded by

birhanu gebisa
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/ 35

Outlines

 Inner and outer class


 Static and final
 Interfaces
 Packages
Inner and outer class
Inner class are defined inside the body of another class known as outer
class.
 can have access modifier or even can be marked
as abstract and final.
 have special relationship with outer class instances.
 This relationship allows them to have access to outer class
members including private members too.
Cont..
An inner class is declared and coded inside the curly braces of outer class.
 Inner class acts as a member of the outer class and can have any access
modifiers: abstract, final, public, protected, private, static.
 Inner class can access all members of the outer class including those
marked as private .
Instantiating an inner class
To instantiate an instance of inner class, there should be a live instance of
outer class.
 An inner class instance can be created only from an outer class instance.
 An inner class shares a special relationship with an instance of the outer
class.
Cont..
class MyOuterClassDemo { public static void main(String args[]){
private int x= 1; MyOuterClassDemo outer = new MyOuterClassDemo();
// inner class definition MyInnerClassDemo inner=outer.new
class MyInnerClassDemo { MyInnerClassDemo();
public void seeOuter () { inner.seeOuter();
System.out.println("Outer }
Value of x is :" + x);
} } // end outer class definition
} // end inner class definition
Cont..
The public static void main code in the above example can be
replaced with this one.
It will also give the same output.
public static void main(String args[]){
MyOuterClassDemo.MyInnerClassDemo inner = new
MyOuterClassDemo().new MyInnerClassDemo();
inner. seeOuter();
}
Static
Static keyword used when instances or methods needs to be common to
all the objects of a class.
 Can be used with:
-- Variables
-- Methods
-- Classes
Cont..
Accessibility
Static variable
 if access specifier is private, it can
 used to store data that is common to the entire
be accessed only within the class
class
 In case of other access specifier, it
 single copy of the data will be shared by
can be accessed using class name or
all instances
through object reference
 known as class variables
syntax
********
<<access specifier>> static <<Datatype>>
<<variable name>>
Example:
public static int counter;
Sample code
public class customer { public static void main(String[] args)
private int custID; {
// static variable customer cust1=new customer();
public static int counter=0; System.out.println("1-Customer ID:
"+cust1.getCustID());
public customer() customer cust2=new customer();
{ System.out.println("2-Customer ID:
custID=++counter; "+cust2.getCustID());
} System.out.println("Total number of customers are:
public int getCustID() "+counter);
{
return custID; }
} }
Cont..
Static methods Accessibility

>> Generic to the entire class >> class_name.method_name();

>> Used for accessing the static variables and >> object_name.method_name();

invoke static methods of the class Rules

>> can be invoked using class name  static methods can access only static

-- object reference can also be used variables and other static methods
 cannot access the non static

syntax variables and methods directly in side

********* the static method

<<access specifier>> static <<return  to access non static variables

datatype>><<method name()>> and methods inside the static methods

{ we have to use objects

<<code inside the method>>


}
Sample code
public class staticMethod{ public static void main(String args[]) {
static int i; //Its a Static Method
static String s; {
//Static method staticMethod obj=new
static void display() staticMethod();
{ //Static method called in another
System.out.println("static method display"); static method
} display();
void funcn() //non-static method called in
{ another static method
//Static method called in non-static method obj. funcn();
display(); }
} }
Cont..
Static class
 A Class can be made static only if it is a nested Class (inner class)
 The nested static class can be accessed without having an object of outer class.
 static class can access only static variables.
[if the inner class has static variables or methods, it should be static.]
 Using class name, we can access only static methods.
 If the method is non-static, we have to create object for static class.
syntax
static class <<className>>
{
<<code inside the class>>
}
Sample code
public class MyOuterClassDemo { public static void main(String args[]){
private static int x= 1;
MyInnerClassDemo innerr=new
// static inner class definition MyInnerClassDemo();
static class MyInnerClassDemo { innerr.seeOuter();
}
public void seeOuter () { } // end outer class definition
//the variable should be static
System.out.println("Outer Value of x is :" + x);
}
} // end inner class definition
Final

Final keyword can be used with


 variables
 methods
 classes
Cont..
Final variable
 Final variables are constants.
 We cannot change the value of a final variable once it is initialized.

class Demo{
final int MAX_VALUE=99;
void myMethod(){
MAX_VALUE=101;
}
public static void main(String args[]){
Demo obj=new Demo(); obj.myMethod();
}}

Error: cannot re-initialize final variables


Cont..
Blank final variable
 A final variable that is not initialized at the time of declaration
is known as blank final variable.
 We must initialize the blank final variable in constructor of the
class otherwise it will throw a compilation error (Error:
variable MAX_VALUE might not have been initialized).
Cont..
class Demo{
//Blank final variable What is the use of blank final variable?
final int MAX_VALUE; Lets say we have a Student class which
Demo(){ is having a field called Roll No.
//It must be initialized in constructor Since Roll No should not be changed once the

MAX_VALUE=100; student is registered, we can declare it as a


final variable in a class but we cannot initialize
} void myMethod(){
roll no in advance for all the students
System.out.println(MAX_VALUE);
(otherwise all students would be having same
}
roll no).
public static void main(String args[]){
 In such case we can declare roll no variable
Demo obj=new Demo(); as blank final and we initialize this value
obj.myMethod(); during object creation
}}
Cont..
Final Method
 A final method 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.
Cont..
class XYZ{ class XYZ{
final void demo(){ final void demo()
System.out.println("XYZ Class Method"); {
}} System.out.println("XYZ Class Method");
class ABC extends XYZ{ }}
void demo(){ class ABC extends XYZ{
System.out.println("ABC Class Method"); public static void main(String args[]){
} ABC obj= new ABC();
public static void main(String args[]){ obj.demo();
ABC obj= new ABC(); }}
obj.demo();
}} Output: XYZ Class Method

Error: demo() in ABC cannot override demo() in XYZ


Cont..
Final Class
We cannot extend a final class.
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();
Error: cannot inherit from final XYZ
}}
Cont..
Points to Remember:
1) A constructor cannot be declared as final.
2) Local final variable must be initializing during declaration.
3) All variables declared in an interface are by default final.
4) We cannot change the value of a final variable.
5) A final method cannot be overridden.
6) A final class not be inherited.
7) If method parameters are declared final then the value of these
parameters cannot be changed.
8) It is a good practice to name final variable in all CAPS.
Interface
 An interface is a reference type in Java, it is similar to class,
it is a collection of abstract methods and static & final variables.
 A class implements an interface, thereby inheriting the
abstract methods of the interface.
 Writing an interface is similar to writing a class.
 But a class describes the attributes and behaviors of an object.
 And an interface contains behaviors that a class implements
Interface, abstract class and non- abstract class

Interface Abstract class Normal class


All methods are abstract Can have abstract All methods are non-
methods and non-abstract abstract
methods
Has no instance fields Has instance fields Has instance fields

Extends any number of Extends only one class Extends only one class
interfaces
Cannot be instantiated Cannot be instantiated Can be instantiated

Has no constructors Has no constructors Has constructors


Declaring Interfaces
The interface keyword is used to declare an interface
<<access specifier>>interface<<interfaceName>>
{
// final and static fields
// abstract methods
}
Interfaces have the following properties:
 An interface is implicitly abstract.
 You do not need to use the abstract keyword while declaring an interface.
 Each method in an interface is also implicitly abstract, so the abstract keyword
is not needed.
 Methods in an interface are implicitly public.
Implementing Interfaces
 When a class implements an interface, you can think of the class as signing a
contract, agreeing to perform the specific behaviors of the interface.
 If a class does not perform all the behaviors of the interface, the class must declare
itself as abstract.
 A class uses the implements keyword to implement an interface.
<<access specifier>>class<<className>> implements <<interfaceName>>{}
A class can implement more that one interfaces
<<access specifier>>class<<className>> implements <<interface1Name>> ,
<<interface2Name>> {}

Implementing an interface is like signing a contract with the compiler that states “ I will
define all the method specified by the interface or I will declare my class abstract”
Extending Interfaces
When implementation interfaces there are several rules:
 A class can implement more than one interface at a time.
 A class can extend only one class, but implement many interfaces.
 An interface can extend another interface, similarly to the way that
a class can extend another class.
 The extends keyword is used to extend an interface, and the child
interface inherits the methods of the parent interface.
<<access specifier>>interface<<interfaceName>> extends
<<super_interfaceName>> {}
Cont..
Extending Multiple Interfaces:
 A Java class can only extend one parent class.
 Multiple inheritance is not allowed.
 Interfaces are not classes, however, and an interface can extend
more than one parent interface.
 The extends keyword is used once, and the parent interfaces are
declared in a comma-separated list.
<<access specifier>>interface<<interfaceName>> extends
<<super_interfaceName>> , <<super_interfaceName2>> {}
Why do we use Interfaces?
 To have unrelated classes implement similar methods
Example:
Class PDF and Music
– Not related
– Both implements download methods
-- isDownload
 To model multiple inheritance which allows a class to have
more than one superclass
Sample code
public interface Relation class music implements Relation

{ {
public boolean isDownload()
public boolean isDownload();
{
}
System.out.println(“PDF download”);
class PDF implements Relation
}
{
}
public boolean isDownload() Class test{
{ public static void main(String[] args) {
System.out.println(“PDF download”); PDF p= new PDF();
} p.isDownload();

} }}
Packages
 Sub-directories within which related classes can be placed together
for organization.
 Group of classes placed within folder(s).
Example: package transportation can contain classes Airplane, Train,
Car, Boat, Bike
 To make a class a part of a package transportation we have to write
“package transportation” at the first line of code
[you cannot write any java code before package name]
 packages can have sub package.
Example: java.awt [awt is a sub package in the java package]
Cont..
Importing a particular class
One declared that a class belongs to some package, the actual name of
the class is packageName.className
Example: transportation.Car is the actual name for class Car
 To import anywhere in your code use: import transportation.Car
[ this for if you need to use the class Car in other package, not in the same package ]
Importing a package
Importing a package means importing the whole classes of the package.

Example: import java.awt.*; Instead of importing


import java.awt.Graphics
import java.awt.Button;
Cont..
 Classes in the same package can access each other without importing
 You can avoid importing classes by using the filename of the class
[packageName.className] everywhere in code.

Drawbacks of importing the whole package


 causes the virtual machine to use extra RAM to keep track of the
names of the elements within that package
 Slows the system down slightly.
 Class collision can occur, if you have the same class name in 2
packages.
Cont..
Code organization with package
 packages are used to organize and group related classes together.
 Java.io: contains classes for doing input/output
 Java.awt: contains classes for creating GUI
 Java.net: contains classes for doing network operation.
 Java.util: contains other tools for encoding decoding, vector, stacks…

Implicit imports
The class of java.lang are automatically imported.
Example: Math class and system class are directly used without any import
statements.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy