Вы находитесь на странице: 1из 16

What are Abstract Classes

You can require that certain methods be overridden by subclasses by specifying the abstract type
modifier. To declare an abstract method, use this general form:

abstract type name(parameter-list);

No method body is present for abstract method.

Any class that contains one or more abstract methods must also be declared abstract.

abstract class MyAbstractClass{


abstract type name(parameter-list);
}

Here is an abstract class, followed by a class which implements its abstract method.

Question 1
abstract class MyAbstractClass {
abstract void callme();

void callmetoo() {
System.out.println("This is a concrete method.");
}
}

class B extends MyAbstractClass {


void callme() {
System.out.println("B's implementation of callme.");
}
}

public class Main {


public static void main(String args[]) {
B b = new B();
b.callme();
b.callmetoo();
}
}

Question 2

Using abstract methods and classes


abstract class Shape {
double height;
double width;

Shape(double a, double b) {
height = a;
width = b;
}
abstract double area();
}

class Rectangle extends Shape{


Rectangle(double a, double b) {
super(a, b);
}
double area() {
System.out.println("Inside Area for Rectangle.");
return height * width;
}
}
class Triangle extends Shape{
Triangle(double a, double b) {
super(a, b);
}
double area() {
System.out.println("Inside Area for Triangle.");
return height * width / 2;

}
}

public class Main {


public static void main(String args[]) {
Rectangle r = new Rectangle(10, 5);
Triangle t = new Triangle(10, 8);

Shape figref;

figref = r;
System.out.println("Area is " + figref.area());

figref = t;
System.out.println("Area is " + figref.area());
}
}

What is a Java Package


Packages are containers for classes.

Packages are used to keep the class name space compartmentalized.


In Java, package is mapped to a folder on your hard drive.

Defining a Package
To define a package, 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.

If you omit the package statement, the class names are put into the default package, which has no
name.This is the general form of the package statement:

package packageName;

Create a hierarchy of packages.

To create a hierarchy of packages, separate each package name from the one above it by use of a
period. The general form of a multileveled package statement:

package pkg1[.pkg2[.pkg3]];

A package hierarchy must be reflected in the file system of your Java development system.

Java package maps to directory

A Short Package Example

Question 3
package MyPack;

public class Main {


public static void main(String args[]) {
System.out.println("hi");
}
}

Then try executing the class, using the following command line:

java MyPack.Main
Importing Packages
In a Java source file, import statements occur immediately following the package statement and
before class definitions.

This is the general form of the import statement:

import pkg1[.pkg2].(classname|*);

* means including all classes under that package. For example,

import java.lang.*;

Any place you use a class name, you can use its fully qualified name, which includes its full
package hierarchy.

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 {

Source Files
All Java source files must end with the .java extension.
A source file should contain, at most, one top-level public class definition.
If a public class is present, the class name should match the unextended filename.
Three top-level elements known as compilation units may appear in a file. None of these
elements is required.
If they are present, then they must appear in the following order:

1. Package declaration
2. Import statements
3. Class, interface, and enum definitions
Question 4
package MyPack;
import java.util.Date;

public class Main {


public static void main(String args[]) {
System.out.println(new Date());
}
}

Access Control
Java's access specifiers are public, private, protected and a default access level.

• A public class member can be accessed by any other code.


• A private class member can only be accessed within its class.

Default (without an access modifier)

• A class's fields, methods and the class itself may be default.


• A class's default features are accessible to any class in the same package.
• A default method may be overridden by any subclass that is in the same package as the
superclass.

protected

• protected features are more accessible than default features.


• Only variables and methods may be declared protected.
• A protected feature of a class is available to all classes in the same package(like a default).
• Moreover, a protected feature of a class can be available to its subclasses.

Here is an example for a public member variable

public int i;

The following code defines a private member variable and a private member method:

private double j;
private int myMethod(int a, char b) { // ...

To understand the effects of public and private access, consider the following program:

Question 5
class Test {
int a; // default access
public int b; // public access
private int c; // private access
// methods to access c
void setc(int i) {
c = i;
}
int getc() {
return c;
}
}
public class Main {
public static void main(String args[]) {
Test ob = new Test();
ob.a = 1;
ob.b = 2;
// This is not OK and will cause an error
// ob.c = 100; // Error!
// You must access c through its methods
ob.setc(100); // OK
System.out.println("a, b, and c: " + ob.a + " " + ob.b + " " +
ob.getc());
}
}

Member Access and Inheritance


A subclass cannot access the private members of the superclass.
For example, consider the following simple class hierarchy:
If you try to compile the following program, you will get the error message.

Question 6
class A {
private int j; // private to A
}
class B extends A {
int total;

void sum() {
total = j; // ERROR, j is not accessible here
}
}

Class Member Access Protection and


Package
The following table shows the access matrix for Java.

Position and Access

No
Position Private Protected Public
modifier
Same class Yes Yes Yes Yes
Same package subclass No Yes Yes Yes
Same package non-subclass No Yes Yes Yes
Different package subclass No No Yes Yes

Different package non-subclass No No No Yes

Modifiers and Features


Not all modifiers can be applied to all features.

Top-level classes may not be protected.

Methods may not be transient.

Static can apply it to free-floating blocks of code.

All Possible Combinations of Features and Modifiers

Modifier Class Variable Method Constructor Code Block


public yes yes yes yes no
protected no yes yes yes no
empty accessor yes yes yes yes yes
private no yes yes yes no
final yes yes yes no no
abstract yes no yes no no
static no yes yes no yes
native no no yes no no
transient no yes no no no
volatile no yes no no no
synchronized no no yes no yes
What is a Java Interface
interface specifies what a class must do, but not how it does it.

To implement an interface, a class must create the complete set of methods defined by the
interface.

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;


}
Variables can be declared inside of interface declarations.

They are implicitly final and static.

They must also be initialized with a constant value.

All methods and variables are implicitly public if the interface, itself, is declared as public.

Here is an example of an interface definition.

interface MyInterface{
void callback(int param);
}

Implementing Interfaces
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:
access-level class classname [extends superclass] [implements interface
[,interface...]] {
// class-body
}

Here is a small example class that implements the interface shown earlier.

Question 7
interface MyInterface {
void callback(int param);
}

class Client implements MyInterface{


// Implement Callback's interface
public void callback(int p) {

System.out.println("callback called with " + p);


}
}

callback() is declared using the public access specifier. When you implement an interface
method, it must be declared as public.

Accessing Implementations Through


Interface References
The following example calls the callback( ) method via an interface reference variable:

Question 8
interface MyInterface {
void callback(int param);
}
class Client implements MyInterface{
// Implement Callback's interface
public void callback(int p) {
System.out.println("callback called with " + p);
}
}
public class Main {
public static void main(String args[]) {
MyInterface c = new Client();
c.callback(42);

}
}
Question 9
Polymorphic and interface
interface MyInterface {
void callback(int param);
}
class Client implements MyInterface{
// Implement Callback's interface
public void callback(int p) {
System.out.println("Client");
System.out.println("p squared is " + (p * 2));
}
}
class AnotherClient implements MyInterface{
// 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[]) {
MyInterface c = new Client();
AnotherClient ob = new AnotherClient();
c.callback(42);
c = ob; // c now refers to AnotherClient object
c.callback(42);
}
}

Partial interface Implementations


If a class implements an interface but does not fully implement its methods, then that class must
be declared as abstract. For example:

Question 10
interface MyInterface {
void callback(int param);

void show();
}
abstract class Incomplete implements MyInterface {
int a, b;

public void show() {


System.out.println(a + " " + b);
}

Variables in Interfaces
We can use interface to organize constants.

Question 11
interface MyConstants {
int NO = 0;
int YES = 1;
}

class Question implements MyConstants {


int ask() {
return YES;
}
}

public class Main implements MyConstants {


static void answer(int result) {
switch (result) {
case NO:
System.out.println("No");
break;
case YES:
System.out.println("Yes");
break;
}
}
public static void main(String args[]) {
Question q = new Question();
answer(q.ask());
}
}

Interfaces Can Be Extended


One interface can inherit another interface with the keyword extends.

Question 12
interface IntefaceA {
void meth1();
void meth2();
}
interface IntefaceB extends IntefaceA {
void meth3();
}
class MyClass implements IntefaceB {
public void meth1() {
System.out.println("Implement meth1().");
}
public void meth2() {
System.out.println("Implement meth2().");
}
public void meth3() {
System.out.println("Implement meth3().");
}
}
public class Main {
public static void main(String arg[]) {
MyClass ob = new MyClass();
ob.meth1();
ob.meth2();
ob.meth3();
}
}

The transient and volatile Modifiers


When an instance variable is declared as transient, then its value need not persist when an object
is stored. For example:

class T {
transient int a; // will not persist
int b; // will persist
}

The volatile variables can be changed unexpectedly by other parts of your program.

Using instanceof
Java provides the run-time operator instanceof to check class type for an object. The instanceof
operator has this general form:

object instanceof type

The following program demonstrates instanceof:


Question 13

class A {
}

class B {
}

class C extends A {
}

class D extends A {
}

public class Main{


public static void main(String args[]) {
A a = new A();
B b = new B();
C c = new C();
D d = new D();

if (a instanceof A)
System.out.println("a is instance of A");
if (b instanceof B)
System.out.println("b is instance of B");
if (c instanceof C)
System.out.println("c is instance of C");
if (c instanceof A)
System.out.println("c can be cast to A");

if (a instanceof C)
System.out.println("a can be cast to C");

A ob;
ob = d; // A reference to d
System.out.println("ob now refers to d");
if (ob instanceof D)
System.out.println("ob is instance of D");

ob = c; // A reference to c
System.out.println("ob now refers to c");
if (ob instanceof D)
System.out.println("ob can be cast to D");
else
System.out.println("ob cannot be cast to D");

if (ob instanceof A)
System.out.println("ob can be cast to A");
// all objects can be cast to Object
if (a instanceof Object)
System.out.println("a may be cast to Object");
if (b instanceof Object)
System.out.println("b may be cast to Object");
if (c instanceof Object)
System.out.println("c may be cast to Object");
if (d instanceof Object)
System.out.println("d may be cast to Object");
}
}

Inner Classes
An inner class is declared inside (between the opening and closing curly brac
es).

class MyClass{
class MyInnerClass{
}
}

A normal Java class can have another class declared inside it: a member of th
e normal class.

Member classes cannot have the same name as the enclosing class.

If the class is declared static, it is called a nested class and can access o
nly static methods and variables.

Inner classes can be named or anonymous.

For a local inner class (inside a method) to use local variables or method pa
rameters,
it must be declared final.

Instances of the inner class retain the ability to access the members of the outer class

Question 14
class Outer {
int outer_x = 100;
void test() {
Inner inner = new Inner();
inner.display();
}
class Inner {
void display() {
System.out.println("display: outer_x = " + outer_x);
}
}
}
public class Main {
public static void main(String args[]) {
Outer outer = new Outer();
outer.test();
}
}

Question 15
class Outer {
int outer_x = 100;
void test() {

}
class Inner {
void display() {
System.out.println("display: outer_x = " + outer_x);
}
}
}
public class Main {
public static void main(String args[]) {
new Outer().new Inner().display();

}
}

Question 16

public class MainClass {


public static void main(String[] argv) {
new OuterOne().makeInner();
System.out.println();
}
}

class OuterOne {
private int x = 0;

public OuterOne() {
InnerOne inner = new InnerOne();

outerMethod();
}

public class InnerOne {


private int x = 1;

public void innerMethod() {


System.out.println("enclosing x is " + x);
}
}

public void outerMethod() {


System.out.println("x is " + x);
}

public void makeInner() {


InnerOne anInner = new InnerOne();
anInner.innerMethod();
}
}

Question 17
Question 18

Question 19

Question 20

Question 21

Вам также может понравиться