JAVA Material

Download as pdf or txt
Download as pdf or txt
You are on page 1of 11

Using final

The keyword final can be used

To prevent method overriding


To prevent Inheritance
To prevent method overriding: Sometimes, we do not want a superclass method to be
overridden in
the subclass. Instead, the same superclass method definition has to be used by every subclass.
In such
situation, we can prefix a method with the keyword final as shown below –
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!");
}
}
To prevent Inheritance: As we have discussed earlier, the subclass is treated as a specialized
class and superclass is most generalized class. During multi-level inheritance, the bottom most
class will be with all the features of real-time and hence it should not be inherited further. In
such situations, we can prevent a particular class from inheriting further, using the keyword
final. For example –
final class A
{
// ...
}
class B extends A // ERROR! Can't subclass A
{
// ...
}
Note:

Declaring a class as final implicitly declares all of its methods as final, too. 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 implementations
Method Overloading and Overriding
Example: Example:
class demo class demo
{ {
void add(){ void add(){
System.out.println(“Sum=”+(10+20)); } System.out.println(“Sum=”+(10+20));
}
void add(int a, int b) { }
System.out.println(“Sum=”+(a+b)); } class demo1 extends demo
int add(){ {
return a+b; void add(){
} System.out.println(“Sum=”+(80+40));
} }
class example }
{ class example
public static void main(String args[]){ {
demo d = new demo(); public static void main(String args[]){
d.add(); demo1 d = new demo1();
d.add(10,20); d.add();
int a = add(); super.add();
} }
} }

Default method in interface


In a typical design based on abstractions, where an interface has one or multiple
implementations, if one or more methods are added to the interface, all the implementations
will be forced to implement them too. Otherwise, the design will just break down.
Default interface methods are an efficient way to deal with this issue. They allow us to add
new methods to an interface that are automatically available in the implementations.
Therefore, we don’t need to modify the implementing classes.
In this way, backward compatibility is neatly preserved without having to refactor the
implementers.
public interface Vehicle {
String speedUp();
String slowDown();
default String turnAlarmOn() {
return "Turning the vehicle alarm on.";
}
default String turnAlarmOff() {
return "Turning the vehicle alarm off.";
}
}
public class Car implements Vehicle {
@Override
public String speedUp() {
return "The car is speeding up.";
}
@Override
public String slowDown() {
return "The car is slowing down.";
}
}
public static void main(String[] args) {
Vehicle car = new Car("BMW");
System.out.println(car.speedUp());
System.out.println(car.slowDown());
System.out.println(car.turnAlarmOn());
System.out.println(car.turnAlarmOff());
}
Static methods in interface
Static Methods in Interface are those methods, which are defined in the interface with the
keyword static. Unlike other methods in Interface, these static methods contain the complete
definition of the function and since the definition is complete and the method is static,
therefore these methods cannot be overridden or changed in the implementation class.
Example:
// Java program to demonstrate
// static method in Interface.

interface NewInterface {

// static method
static void hello()
{
System.out.println("Hello, New Static Method Here");
}

// Public and abstract method of Interface


void overrideMethod(String str);
}

// Implementation Class
public class InterfaceDemo implements NewInterface {

public static void main(String[] args)


{
InterfaceDemo interfaceDemo = new InterfaceDemo();

// Calling the static method of interface


NewInterface.hello();

// Calling the abstract method of interface


interfaceDemo.overrideMethod("Hello, Override Method here");
}

// Implementing interface method

@Override
public void overrideMethod(String str)
{
System.out.println(str);
}
}
Defining Package:
A set of classes and interfaces grouped together are known as Packages in JAVA. 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.
The package keyword is used to create a package in java.
//save as Simple.java
package mypack;
public class Simple
{
public static void main(String args[])
{
System.out.println("Welcome to package");
}
}
The general form of a multileveled package statement is :
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.

Importing Package
Import keyword is used to import the package. 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 (.)

Example:
import java.util.Date;
import java.io.*;

Programming example for creating and I porting package


package MyPack;
public class Balance {
String name;
double bal;
public Balance(String n, double b) {
name = n;
bal = b;
}
public void show() {
if(bal<0)
System.out.print("--> ");
System.out.println(name + ": $" + bal);
}
}

import MyPack.*;
class TestBalance {
public static void main(String args[]) {
Balance test = new Balance("J. J. Jaspers", 99.88);
test.show(); // you may also call show() }

}
Access Specifiers
There are 4 types of java access modifiers:
1. private
2. default
3. protected
4. public
1. private access modifier: The private access modifier is accessible only within class. 2.
default access modifier: If you don't use any modifier, it is treated as default by default. The
default modifier is accessible only within package.
3. protected access modifier: The protected access modifier is accessible within package and
outside the package but through inheritance only. The protected access modifier can be
applied on the data member, method and constructor. It can't be applied on the class.
4. public access modifier: The public access modifier is accessible everywhere. It has the
widest scope among all other modifiers.
Exception:
An Exception, It can be defined as an abnormal event that occurs during program execution
and disrupts the normal flow of instructions.
An exception is a run-time error that occurs during the execution of a java program.
Example: If you divide a number by zero or open a file that does not exist, an
exception is raised.

1. try Block: The java code that you think may produce an exception is placed within a try
block for a suitable catch block to handle the error.
2. catch Block: Exceptions thrown during execution of the try block can be caught and
handled in a catch block.
3. throw keyword is used to throw an exception explicitly. Only object of
Throwable class or its sub classes can be thrown.

4. finally Block: A finally block is always executed, regardless of the cause of exit from the
try block, or whether any catch block was executed.
5. throws: Any method capable of causing exceptions must list all the exceptions possible
during its execution, so that anyone calling that method gets a prior knowledge about which
exceptions to handle. A method can do so by using the throws keyword.
Example:
import java.util.Scanner;
public class Custom_Exception
{
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter two numbers: ");
int a = scanner.nextInt();
int b = scanner.nextInt();
try {
if (b == 0) {
throw new ArithmeticException("Division by zero is not
allowed!");
}
float result = a / b;
System.out.println("Result: " + result);
}
catch (ArithmeticException e)
{
System.out.println(e.getMessage());
}
finally {
scanner.close();
}
}
}
Inbuilt Exceptions in JAVA

Creating Thread using Runnable Interface


class NewThread implements Runnable {
Thread t;

NewThread() {
// Create a new, second thread
t = new Thread(this, "Demo Thread");
System.out.println("Child thread: " + t);
t.start(); // Start the thread
}

// This is the entry point for the second thread.


public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Child Thread: " + i);
Thread.sleep(500);
}
} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}

class ThreadDemo {
public static void main(String args[]) {
NewThread n = new NewThread(); // create a new thread

try {
for(int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}

Here main thread is created first and then main thread calls constructor of NewThread class.
In NewThread class Demo thread is created by calling constructor of Thread class. Then start
function is called. Which in turn invokes the run function defined in runnable interface.
Creating Thread by extending Thread class
class NewThread extends Thread {

NewThread() {
// Create a new, second thread
super("Demo Thread");
System.out.println("Child thread: " + this);
start(); // Start the thread
}

// This is the entry point for the second thread.


public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Child Thread: " + i);
Thread.sleep(500);
}
} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}

class ExtendThread {
public static void main(String args[]) {
new NewThread(); // create a new thread

try {
for(int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}

Here main thread is created first and then main thread calls constructor of NewThread class.
In NewThread class Demo thread is created by calling super class constructor. Then start
function is called. Which in turn invokes the run function defined in Thread class.
Enumeration
Enumeration is a list of named constants.
Enumeration is created using enum keyword
Example:
// An enumeration of apple varieties.
enum Apple {
Jonathan, GoldenDel, RedDel, Winesap, Cortland
}
Once you have defined an enumeration, you can create a variable of that type. However,
even though enumerations define a class type, you do not instantiate an enum using new.
Instead, you declare and use an enumeration variable in much the same way as you do one
of the primitive types. For example, this declares ap as a variable of enumeration type
Apple:

Apple ap;
Because ap is of type Apple, the only values that it can be assigned (or can contain) are
those defined by the enumeration. For example, this assigns ap the value RedDel:
ap = Apple.RedDel;

The values( ) and valueOf( ) Methods


All enumerations automatically contain two predefined methods: values( ) and valueOf( ).
Their general forms are shown here:

public static enum-type[ ] values( )


public static enum-type valueOf(String str)

The values( ) method returns an array that contains a list of the enumeration constants.
The valueOf( ) method returns the enumeration constant whose value corresponds to the
string passed in str. In both cases, enum-type is the type of the enumeration

Example:
enum Apple {
Jonathan, GoldenDel, RedDel, Winesap, Cortland
}
class EnumDemo2 {
public static void main(String args[])
{
Apple ap;
System.out.println("Here are all Apple constants:");
// use values()
Apple allapples[] =
Apple.values(); for(Apple a :
allapples)

System.out.println(a);
System.out.println();
// use valueOf()
ap = Apple.valueOf("Winesap");
System.out.println("ap contains " +
ap); }

You might also like