Abstract class
• A class that is declared with abstract keyword is known as abstract
class in java. It can have abstract and non-abstract methods (method
with body)
• abstract keyword in front of the class keyword
• No objects of an abstract class, cannot declare abstract constructors,
or abstract static methods
abstract class A {
abstract void callme();
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();
}
}
abstract class Figure {
double dim1;
double dim2;
Figure(double a, double b) { class Main {
dim1 = a; public static void main(String args[]) {
dim2 = b; } Rectangle r = new Rectangle(9, 5);
abstract double area(); Triangle t = new Triangle(10, 8);
} Figure figref; // no object is created
figref = r;
class Rectangle extends Figure { System.out.println("Area is " + figref.area());
Rectangle(double a, double b) { figref = t;
super(a, b); System.out.println("Area is " + figref.area());
} }
double area() { }
System.out.println("Inside Area for Rectangle.");
return dim1 * dim2; }
} Reference
variable Can
class Triangle extends Figure { be used to refer
Triangle(double a, double b) { to an object of
super(a, b);
any class derived
}
double area() { from super class
System.out.println("Inside Area for Triangle.");
return dim1 * dim2 / 2;}}
Package
• Both a naming and a visibility control mechanism.
• Classes can be defined inside a package that are not accessible by code
outside that package
• Class members can be defined that are exposed only to other members
of the same package
• General form of the package statement:
package pkg;
• Hierarchy of packages is created by separating 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]];
package MyPack; class AccountBalance
class Balance { {
String name; public static void main(String args[])
double bal; {
Balance(String n, double b) Balance current[] = new Balance[3];
{ current[0] = new Balance("K. J. Fielding", 123.23);
name = n; current[1] = new Balance("Will Tell", 157.02);
bal = b; current[2] = new Balance("Tom Jackson", -12.33);
} for(int i=0; i<3; i++)
void show() current[i].show();
{ }
if(bal<0) }
System.out.print("--> ");
System.out.println(name + ": $" + bal);
}
}
• Compilation
• java MyPack.AccountBalance
• java AccountBalance // Not to be used
Access Protection
• Java provides many levels of protection to allow fine-grained control
over the visibility of variables and methods within classes, subclasses,
and packages.
• 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
• Access modifiers
• Private cannot be accessed outside of its class
• Public Accessed from anywhere
• Protected Seen outside your current package, but only to classes that subclass your
class directly.
This is file Protection.java:
package p1;
public class Protection {
int n = 1;
private int n_pri = 2;
protected int n_pro = 3;
public int n_pub = 4;
public Protection()
{
System.out.println("base constructor");
System.out.println("n = " + n);
System.out.println("n_pri = " + n_pri);
System.out.println("n_pro = " + n_pro);
System.out.println("n_pub = " + n_pub); } }
This is file Derived.java:
package p1;
class Derived extends Protection {
Derived() {
System.out.println("derived constructor");
System.out.println("n = " + n);
// class only
System.out.println("n_pri = " + n_pri);
System.out.println("n_pro = " + n_pro);
System.out.println("n_pub = " + n_pub); } }
This is file SamePackage.java:
package p1;
class SamePackage {
SamePackage() {
Protection p = new Protection();
System.out.println("same package constructor");
System.out.println("n = " + p.n);
// class only
System.out.println("n_pri = " + p.n_pri);
System.out.println("n_pro = " + p.n_pro);
System.out.println("n_pub = " + p.n_pub);
}
}
package p2;
class Protection2 extends p1.Protection {
Protection2() {
System.out.println("derived other package constructor");
// class or package only
System.out.println("n = " + n);
// class only
System.out.println("n_pri = " + n_pri);
System.out.println("n_pro = " + n_pro);
System.out.println("n_pub = " + n_pub); }
}
This is file OtherPackage.java:
package p2;
class OtherPackage {
OtherPackage() {
p1.Protection p = new p1.Protection();
System.out.println("other package constructor");
// class or package only
System.out.println("n = " + p.n);
// class only
System.out.println("n_pri = " + p.n_pri);
// class, subclass or package only
System.out.println("n_pro = " + p.n_pro);
System.out.println("n_pub = " + p.n_pub); } }
Importing Packages
• General form of the import statement:
import pkg1 [.pkg2].(classname | *);
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 (.).
• Either an explicit classname or a star (*), which indicates that the Java
compiler should import the entire package.
Example:
• import java.util.Date; import java.io
• The basic language functions are stored in a package inside of the java
package called java.lang Implicitly imported by the compiler for all
programs.
• Import java.util.*
• Import java.util.Scanner
• The star form may increase compilation time—while importing
several large packages. Explicitly name the classes to be used rather
than importing whole packages.
INTERFACES
• Interfaces are syntactically similar to classes, group of related
methods without definition and constants.
• Example for abstraction
• Implemented by classes using implements keyword.
• Designed to support dynamic method resolution at run time.
• Variables declared inside of interface declarations are implicitly final
and static. All methods and variables are implicitly public.
• A class implementing an interface must include all the methods inside
the interface with same type signature.
Declaring an Interface
Access-specifier interface 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;
}
Example
interface Callback
{
void callback(int param);
While implementing interface
} method, it should be declared as
public. Callback is declared
class Client implements Callback public
{
public void callback(int p)
{
System.out.println("callback called with " + p);
}
}
Example
interface Callback
{
void callback();
}
class Client implements Callback
{
public void callback(int p)
{
System.out.println("callback called with " + p);
}
}
Interface Course
{
void study();
void publish();
}
Class Javacourse implement Course
{
void study()
{
---------
---------
}
}
public interface Encryptable
{
void encrypt(String key);
}
public class SecretText implements Encryptable
{
private String text;
_________________
{
// code to encrypt the text using encryption key goes here
}
}
The classes that implement interfaces to define additional members of their own. For example,
the following version of Client implements callback( ) and adds the method nonIfaceMeth( ):
class Client implements Callback
{
// Implement Callback's interface
public void callback(int p)
{
System.out.println("callback called with " + p);
}
void nonIfaceMeth()
{
System.out.println("Classes that implement interfaces " + "may also define other
members, too.");
}
}
Accessing Implementations Through
Interface References
class TestIface
{
public static void main(String args[])
{
Callback c = new Client();
c.callback(42);
}
}
class AnotherClient implements Callback {
// Implement Callback's interface
public void callback(int p) {
System.out.println("Another version of callback");
System.out.println("p squared is " + (p*p));
}
}
class TestIface2 {
public static void main(String args[]) {
Callback c = new Client();
AnotherClient ob = new AnotherClient();
c.callback(42);
c = ob; // c now refers to AnotherClient object
c.callback(42);
}
}
interface A{
void display();
}
interface B extends A
{}
public class Test implements B{
public void display(){
System.out.print("Hi");
}
public static void main(String args[]){
Test t = new Test();
t.display();
}
}
Hi
public interface A{
protected String getName();
}
public class Test implements A{
public String getName(){
return "name";
}
public static void main (String[] args){
Test t = new Test();
System.out.println(t.getName());
}
}
Compilation error due to protected
interface calculate{
void cal(int item);
}
class display implements calculate{
int x;
public void cal(int item){
x = item * item;
}
}
class interfaces{
public static void main(String [] args){
display arr = new display();
arr.x = 0;
arr.cal(2);
System.out.print(arr.x);
}
}
Output 4
Nested Interface
class A { class Main {
public interface NestedIF { public static void main(String args[]) {
boolean isNegative(int x);
} A.NestedIF nif = new B();
} if(nif.isNegative(10))
class B implements A.NestedIF { System.out.println("10 is not negative");
public boolean isNegative(int x) { if(nif.isNegative(-12))
return x < 0 ? true: false; System.out.println("-12 is negative");
} }
} }
import java.util.Scanner; System.out.println("WEDNESDAY");
interface SharedConstants { break;
int SUN = 0; int MON = 1; int TUE = 2; case THU:
int WED = 3; int THU = 4; int FRI = 5; System.out.println("THURSDAY");
int SAT = 6; } break;
class Days implements SharedConstants { case FRI:
void answer(int x) { System.out.println("FRIDAY");
switch(x) { break;
case SUN: case SAT:
System.out.println("SUNDAY"); System.out.println("SATURDAY");
break; break; } } }
case MON: class Main{
System.out.println("MONDAY"); public static void main(String args[]) {
break; Days q = new Days();
case TUE: Scanner sc=new Scanner(System.in);
System.out.println("TUESDAY"); int n= sc.nextInt();
break; q.answer(n); } }
Interfaces Can Be Extended
interface A { System.out.println("Implement meth2"); }
void meth1(); public void meth3() {
void meth2(); } System.out.println("Implement
interface B extends A { meth3"); } }
void meth3(); } class Main {
class MyClass implements B { public static void main(String arg[]) {
public void meth1() { MyClass ob = new MyClass();
System.out.println("Implement meth1"); ob.meth1();
} ob.meth2(); ob.meth3();
public void meth2() { } }
Default methods
public interface MyIF {
int getNumber();
default String getString() { class Main
return "Default String"; {
} } public static void main(String args[]) {
class MyIF1 implements MyIF MyIF1 obj = new MyIF1();
{ System.out.println(obj.getNumber());
public int getNumber() { System.out.println(obj.getString());
return 100; }
} } }
Multiple Inheritance
• Java does not support the multiple inheritance of classes.
• Multiple inheritance is achieved through interfaces.
interface PI1 {
default void show()
{
System.out.println("Default PI1");
}
}
interface PI2 {
default void show()
{ public void showOfPI1() {
System.out.println("Default PI2"); PI1.super.show(); }
}
} public void showOfPI2() {
class TestClass implements PI1, PI2 { PI2.super.show();
}
public void show()
{ public static void main(String args[])
{
PI1.super.show(); TestClass d = new TestClass();
PI2.super.show(); } d.show();
System.out.println("Now Executing PI1 andPI2");
d.showOfPI1();
Which of the following statements about interfaces is not true in java?
1. An interface can extend another interface.
2. An interface can implement another interface.
3. A class can implement two interfaces.
4. A class can extend another class.
The ______ methods must be implemented when using an interface.
5. abstract
6. private
7. public
8. static
Which of the following is an incorrect statement about interfaces?
1. Interface specifies what class must do but not how it does
2. Interfaces are specified public if they are to be accessed by any code in the program
3. All variables in interface are implicitly final and static
4. All variables are static and methods are public if interface is defined public
Which of the following is true about methods in an interface in Java?
5. An interface can contain only abstract method.
6. We can define a method in an interface
7. Private and protected access modifiers can also be used to declare methods in interface
8. None
Which of the following is true regarding class and interface types?
9. You can convert from a class type to any interface type that is in the same package as the class.
10. You can convert from a class type to any interface type that the class implements.
11. You can convert from a class type to any interface type that the class defines.
12. You cannot convert from a class type to any interface type.