[Go to site: main page, start]

0% found this document useful (0 votes)
67 views7 pages

Java Inner Class and Exception Handling

Uploaded by

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

Java Inner Class and Exception Handling

Uploaded by

soccho roy
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

>>>>Inner class example

import [Link];

class Outer
{
int x;
int y;
class Add
{
Scanner sc = new Scanner([Link]);
void InnerDisplay()
{
x=[Link]();
y=[Link]();
[Link]("The sum of two number is : "+(x+y));
}
}
class Minus
{
Scanner sc = new Scanner([Link]);
void InnerDisplay()
{
x=[Link]();
y=[Link]();

[Link]("The minus value is : "+(+x-y));


}
}

void display()
{
Add a = new Add();
[Link]();
Minus m = new Minus();
[Link]();

}
}

class Main
{
public static void main (String[] args) {
Outer o = new Outer();
[Link]();
}
}

here also i learn one more thing that scanner class doesnot work on class if we
don't write it on method block then it don't work.

[Link] Class

interface Test
{
void display();
}
class Outer
{
public void math()
{
Test t = new Test()
{
public void display()
{
[Link]("Hi There! lol happend to him");
}
};
}
}

class Main
{
public static void main (String[] args) {
Outer o = new Outer();
[Link]();
}
}

>>>> if you want to access a static varriable then you just don't need nothing just
need what is class [Link] name thats it under sop then it's perfect and ready
to compile

>>>>>>>>>>>static nested class example

public class TestOuter2{


static int data=30;
static class Inner{
static void msg(){[Link]("data is "+data);}
}
public static void main(String args[]){
[Link]();//no need to create the instance of static nested class
}
}

>>>final varriable should be write in capital letter and for inialize we ued
static block and one more way used constructor,and another way is when intialize
write the value,and afeter intialize we don't replace the value and in static
method we don't use this and super method

>>>>>and for final we can not use subclass and final method can not be override and
final class can not be extended
example of constructor with passing the value used liked method
class Test
{
final int X;
final int Y;
public Test(int l,int m)
{
X=l;
Y=m;
[Link]("here the final two value is : "+X,+Y);
}
}
public class Main
{
public static void main (String[] args) {
Scanner sc = new Scanner([Link]);
int x;
int y;
[Link]("Please enter two value : ");
x=[Link]();
y=[Link]();
Test t = new Test(x,y);

}
}

>>>>i need ot cover the java package after all the study i have learned (including
basic things like how to create a pakages using cmd and how to access thess live)

>>>>>Acesss Modifire

inner class can be private default anything outer class can not private and
protected
only public and default
test (has a) object of demo one and for inheriting (is a) such case like demo
extends demo-one

>>>>>Multiple Exception Handeling

public class Main {

public static void main(String[] args) {

int a[]=new int[5];


try{
[Link](a[5]);
}
catch(Exception e)
{
[Link](e);
}
try
{
a[5]=30/0;

}
catch(Exception e)
{
[Link](e);
}
[Link]("rest of the code");
}
}

...here multiple inner catch and try block and one outer try block and one outer
catch block

import [Link];

public class Main


{
public static void main (String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("please enter how many number : ");
int m;
m=[Link]();

int[ ] arr = new int[m];


try
{
int value;
[Link]("Please enter which value you want to see : ");
value=[Link]();
//first try block
try
{
[Link]("here the value of your given index is :
"+arr[value]);
}
//frist cathc block
catch(ArrayIndexOutOfBoundsException e)
{
[Link]("your index value is so high input valid
number");
}
//intialize the value again zero to store value when it's not actually
necessary
value=0;
[Link]("please enter a value for index : ");
value=[Link]();

arr[2]=value;
//second try block
try{
int ot =arr[2]/0;

}
//second cathc block
catch(ArithmeticException e)
{
[Link]("Sorry any number is not divisible by zero asked
your developer to changed the demonitor to zero to any number");
}
}

catch(Exception e)
{
[Link]("time invesxt for your brain for your life don't use
the time for another thing which don't give you happiness ");
}
}
}

>>>>another class method throws exception and handle by main class and also solve
the exception by catch

import [Link];
class test
{
public void divisor(int monitor,int demonitor)throws ArithmeticException
{
int result;
result=monitor/demonitor;
[Link]("Here rsult is : "+result);
}
}
class Main
{
public static void main (String[] args) {
Scanner sc = new Scanner([Link]);
int up;
int down;
[Link]("please enter monitor : ");
up=[Link]();
[Link]("please enter demonitor : ");
down=[Link]();
test t = new test();
try {
[Link](up,down);

} catch(ArithmeticException e) {
[Link]("you should not enter demonitor value zero thats why
we add two in your demonitor either you showed up a infiniy "+up/(down+2));
}
}
}

>>>>>we cannot use overriden method from super class to subclass for IOException
and though i test this code for arithmeticexception there override method work
succesfully.

import [Link].*;
class Parent{

// defining the method


void msg() {
[Link]("parent method");
}
}

public class TestExceptionChild extends Parent{

// overriding the method in child class


// gives compile time error
void msg() throws IOException {
[Link]("TestExceptionChild");
}
public static void main(String args[]) {
Parent p = new TestExceptionChild();
[Link]();
}
}

>>>>>>>>second one
import [Link].*;
class Parent{

// defining the method


void msg() {
[Link]("parent method");
}
}

public class TestExceptionChild extends Parent{

// overriding the method in child class


// gives compile time error
void msg() throws ArithmeticException {
[Link]("TestExceptionChild");
}

public static void main(String args[]) {


Parent p = new TestExceptionChild();
[Link]();
}
}

>>>>>here you see where you use same method but that's not a big issue you use same
method for parent class and child class and in two method you create exception but
child class run

import [Link].*;
class Parent{
void msg() throws Exception {
[Link]("parent method");
}
}

public class TestExceptionChild3 extends Parent {


void msg()throws Exception {
[Link]("child method");
}

public static void main(String args[]){


Parent p = new TestExceptionChild3();

try {
[Link]();
}
catch(Exception e) {}
}
}
>>>create custom exception class and use it for exception

import [Link];

class test extends Exception


{
public test(String str)
{
super(str);
}

class Main
{
public static void liggle(int age)throws test
{
if(age<18)
{
throw new test("not eligable");
}
else
{

}
}

public static void main (String[] args) {


Scanner sc = new Scanner([Link]);
int age_user;
[Link]("please enter your age : ");
;
try
{
age_user=[Link]();
liggle(age_user);
}
catch(test t)
{
[Link]("sorry brother for voting you must be an adult");
[Link]("Exception type : "+t);
}
[Link]("Exception handled Successfully");

}
}

Common questions

Powered by AI

Polymorphism in the 'TestExceptionChild' class is demonstrated through method overriding, where the 'msg' method in the child class provides a different implementation than in the parent class. This is a central tenet of polymorphism, allowing different behavior based on the object's runtime type. However, Java's exception handling requires that overridden methods must not throw broader or new checked exceptions than the method in the superclass, which affects how developers manage exceptions hierarchically. The 'TestExceptionChild' example shows that unchecked exceptions like 'ArithmeticException' can still be added in subclasses without compilation issues, whereas checked exceptions like 'IOException' lead to errors if not correctly managed, indicating a key nuance in Java's exception model .

The use of multiple try-catch blocks as shown in the examples allows for functionally isolated error handling, where specific exceptions can be caught and managed separately. This provides more control over what happens when different types of exceptions are thrown. For instance, catching 'ArrayIndexOutOfBoundsException' separately from 'ArithmeticException' allows tailored responses to each error, improving user feedback and allowing the execution of specific recovery strategies based on which exception is encountered, leading to more stable and user-friendly applications .

The 'static' keyword in 'TestOuter2' indicates that 'Inner' is a static nested class. Such classes do not require an instance of the outer class to be instantiated or accessed. In the example, the 'msg' method of the 'Inner' class is accessed directly using 'TestOuter2.Inner.msg()', without creating an object of 'TestOuter2'. This contrasts with non-static nested classes, which require an instance of the outer class .

Declaring a method as 'final' in Java prevents it from being overridden in subclasses. This is useful when you want to make sure that the specific implementation of the method remains unchanged across the inheritance hierarchy. It is a way to enforce consistent behavior and prevent alterations that might compromise the class's integrity or violate its contract. As highlighted, a 'final' method ensures its implementation is the definitive version, thus ensuring security and consistent application behavior .

Static methods, as shown in the examples, belong to the class rather than any instance, meaning they can be called without creating an object. This can be both a limitation and a benefit. The limitation lies in their inability to access instance variables or methods, which might restrict their utility in contexts where object state is important. However, they provide efficient, stateless utility which can aid performance and simplicity, making them ideal for operations that don't require object context. This aligns with object-oriented principles by encouraging clear and predictable static behavior .

Final variables in Java are constant variables, meaning that once they are initialized, their value cannot be changed. This characteristic makes final variables particularly useful for defining constants and ensuring that these values remain unchanged throughout the execution of a program. They promote immutability, aiding predictability and safety in concurrent or complex environments where data consistency is critical. Unlike regular variables, final variables can be initialized via a static block, constructor, or at the time of declaration, and once set, any attempt to modify them results in a compile-time error, enforcing discipline in mutability and state control .

Creating a custom exception class, such as the 'test' exception, allows for more specific and meaningful error handling that is tailored to the particular application's domain. It can provide clearer error messages and make exception handling more precise. In this example, the custom message 'not eligable' gives specific feedback that is contextually relevant to the user trying to vote, highlighting both the issue and the application logic behind the restriction .

Anonymous classes in Java, like the one implemented in the 'Outer' class example, allow for concise instantiation and implementation of interfaces directly at the point of use, avoiding the need for separate, named class declarations. This approach can improve code encapsulation and readability, particularly for small, one-off implementations, which don't require reuse or multiple instantiations. This pattern reduces boilerplate and clearly indicates that the implementation of the 'display' method is only utilized within the 'math' method, emphasizing its localized scope and use .

In the provided Java example, the classes 'Add' and 'Minus' are inner classes defined within the outer class 'Outer'. These inner classes can access the private data members 'x' and 'y' directly, showing encapsulation of functionality within 'Outer'. This setup allows for logical grouping of classes that are only used in one place, simplifying class namespaces and providing better data hiding by restricting the scope of 'Add' and 'Minus' to 'Outer'. The inner classes also neatly encapsulate the functionality of adding and subtracting the numbers, showcasing the use of inner classes to perform operations relevant to the outer class instance .

Using 'throws' in a method signature indicates that the method can propagate exceptions up the call stack to be handled elsewhere, rather than handling them internally. This approach shifts responsibility for managing exceptions to the caller and is particularly effective for promoting modular and reusable code. In the 'divisor' method, the 'throws ArithmeticException' clause alerts users of potential division errors, enabling them to handle it appropriately in their code. This separation of concerns allows for more flexible exception handling strategies .

You might also like