Qa 12 JP
Qa 12 JP
Answer:
• Object Oriented Programming is a Methodology or Paradigm.
• In OOP an Object represents an entity in the real world.
• An OOP program, a collection of objects that interact to solve a task/problem.
Characteristics of Object-Oriented Programming
1. Objects
• Objects are basic concepts of Object Oriented Programming which revolve around the
real life entities.
• Objects are real-world entity such as book, cat, house, pencil, person, etc. Any things
we see, that could be differentiated from another is called object.
• Objects should have a well-defined boundary.
• An object is an instance of a class.
• Every object has its own set of properties, which defines the state of the object and
its own behavior.
• State: It is represented by attributes of an object. It also reflects the properties of an
object.
• Behavior: It is represented by methods of an object. It also reflects the response of an
object with other objects.
• Identity: It gives a unique name to an object and enables one object to interact with
other objects.
Creating Object
• When an object is instantiated / created memory is allocated.
• A software object maintains its state in variables and implements its behavior with
methods.
• Objects are the building blocks of Object-Oriented Programming
Using new keyword
• The new keyword is used to create objects.
Syntax:
ClassName objectName = new ClassName();
Example:
Employee empOne = new Employee(“Vijayakumar S”);
Object Creation has three parts
1. Declaration: Variable declarations that associate a variable name with an object type.
2. Instantiation: The new keyword is a Java operator that creates the object.
3. Initialization: The new operator is followed by a call to a constructor, which initialize
the new object.
2. Class
• Classes are basic concepts of Object-Oriented Programming.
• A class is a blueprint or a template from which individual objects are created.
• A class is a collection of data members (Fields) and member functions (Methods).
• A class is a group of objects which have common properties.
• It is a logical entity (A class is a logical grouping of data and functions).
• When a class is defined, no memory is allocated.
Syntax of Class:
Access modifier class ClassName
{
fields;
methods;
constructors;
}
3.Abstraction
• Abstraction is the concept of object-oriented programming that “shows” only essential
attributes and “hides” unnecessary information.
• The main purpose of abstraction is hiding the unnecessary details from the users.
• An abstract class or method is defined with abstract keyword.
• Example: When we are driving a car, we are only concerned about driving the car
start/stop the car, accelerate, break, etc. we are not concerned about the actual
mechanism works internally.
Types of Abstraction
1. Abstract Class
2. Abstract Methods
Syntax
abstract class ParentClass
{
abstract public function someMethod1();
abstract public function someMethod2($name, $color);
abstract public function someMethod3(): string;
}
4. Encapsulation
• Encapsulation is defined as the wrapping up of data under a single unit.
• It is the mechanism that binds together code and the data it manipulates.
• Encapsulation is a protective shield that prevents the data from being accessed by the
code outside this shield.
• Technically in encapsulation, the variables or data of a class is hidden from any other
class and can be accessed only through any member function of own class in which
they are declared.
• As in encapsulation, the data in a class is hidden from other classes, so it is also
known as data-hiding.
5. Inheritance
• Inheritance is the mechanism by which one object is allowed to derive the
properties (fields and methods) of another. Inheritance in OOP = When a class
derives from another class.
• The class features are inherited is known as super class (or a base class or a parent
class). The class that inherits the other class is known as sub class (or a derived class,
extended class, or child class).
• Inheritance supports reusability.
• An inherited class is defined by using the extends keyword.
6. Polymorphism
• Polymorphism is the ability of an object to take on many forms.
• Polymorphism is a concept by which a single action can be performed by different
ways.
There are two types of polymorphism:
There are mainly three reasons to use interface. They are given below.
interface printable
{
void print();
}
class A6 implements printable
{
public void print()
{
System.out.println("Hello");
}
public static void main(String args[])
{
A6 obj = new A6();
obj.print();
}
}
Output:
Hello
1. Access specifier
It can be public or protected or private or default. It is optional to use an access specifier
while defining a method.
2. Modifier
It can be static, final, synchronized, transient, and volatile. It is optional to use a modifier
3. Return-Type
It specifies the type of value that the return statement of the function returns. It may be any
valid Java data type. If no value is being returned, we use the return type as void.
4. Function-name
The name of the function should be a valid Java identifier. The naming conventions generally
followed for method names are:
✔ It should be meaningful.
✔ It should begin with a lowercase letter. For names having multiple words, we use the
camelCase naming convention.
For example:
✔ printReportCard()
✔ getMarks()
The method name should generally begin with a verb followed by one or more nouns.
For example:
✔ readData
✔ findFile
✔ calculateInterestAmount
5. Parameter list
The parameter list is a comma-separated list of variables of a function referred to as
arguments or parameters. A function may be without any parameters and in this case, the
parameter list is empty.
6. Method Body
The body of the Java method should be enclosed within curly braces{} containing all the
code to perform operations and tasks..
Example method definition:
Syntax of Class:
Access modifier class ClassName
{
fields;
methods;
constructors;
}
Declaring class in Java.
Every class in Java can be composed of the following elements:
• fields
• methods
• constructors
Class declarations can include
• Modifiers such as public, private.
• The class name, with the initial letter capitalized by convention.
• The class body, surrounded by braces, {}.
This is a class declaration. The class body (the area between the braces) contains all the code
that provides for the life cycle of the objects created from the class.
Constructors for initializing new objects, declarations for the fields that provide the
state of the class and its objects, and methods to implement the behavior of the class and its
objects.
Train
Properties Behavior
− Train No. − reserveticket()
− Train Name − cancelticket()
− No. of seat − checkavailability()
Creating Object
• When an object is instantiated / created memory is allocated.
• A software object maintains its state in variables and implements its behaviour with
methods.
• Objects are the building blocks of Object Oriented Programming
Using new keyword
The new keyword is used to create objects.
Syntax:
ClassName objectName = new ClassName();
Example:
Employee empOne = new Employee(“Vijayakumar S”);
Object Creation has three parts
1. Declaration: Variable declarations that associate a variable name with an object type.
2. Instantiation: The new keyword is a Java operator that creates the object.
3. Initialization: The new operator is followed by a call to a constructor, which
initialize the new object.
protected: The access level of a protected modifier is within the package and outside the
package through child class. If you do not make the child class, it cannot be accessed from
outside the package.
Example:
//save by A.java
package pack;
public class A
{
protected void msg()
{
System.out.println("Hello");
}
}
//save by B.java
package mypack;
import pack.*;
class B extends A
{
public static void main(String args[])
{
B obj = new B();
obj.msg();
}
}
Output: Hello
In this example, we have created the two packages pack and mypack. The A class of pack
package is public, so can be accessed from outside the package. But msg method of this
package is declared as protected, so it can be accessed from outside the class only through
inheritance.
12a.2 Explain default and private access specifier with example?
Answer:
Access Specifier
• Java provides four Access Modifiers to set access levels
• Access Modifier set access levels for classes, variables, methods and constructors.
The four access levels are
• default
• private
• public
• protected
default: The access level of a default modifier is only within the package. It from
cannot be accessed outside the package. No modifiers are needed.
Example:
//save by A.java
package pack;
class A
{
void msg()
{
System.out.println("Hello");
}
}
//save by B.java
package mypack;
import pack.*;
class B
{
public static void main(String args[])
{
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}
In this example, we have created two packages pack and mypack. We are accessing the
A class from outside its package, since A class is not public, so it cannot be accessed
from outside the package.
private : The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
Example:
class A
{
private int data=40;
private void msg()
{
System.out.println("Hello java");
}
}
protected : The access level of a protected modifier is within the package and outside
the package through child class. If you do not make the child class, it cannot be
accessed from outside the package.
Example:
//save by A.java
package pack;
public class A
{
protected void msg()
{
System.out.println("Hello");
}
}
//save by B.java
package mypack;
import pack.*;
class B extends A
{
public static void main(String args[])
{
B obj = new B();
obj.msg();
}
}
Output: Hello
In this example, we have created the two packages pack and mypack. The A class of
pack package is public, so can be accessed from outside the package. But msg method
of this package is declared as protected, so it can be accessed from outside the class
only through inheritance.
12a.4 Explain non access modifier?
Java provides a number of non-access modifiers to achieve many other functionalities.
1. static
The static keyword in Java is used for memory management mainly. We can
apply static keyword with variables, methods, blocks and nested classes. The static
keyword belongs to the class than an instance of the class.
To access static methods there is no need to instantiate the class. Static
methods can be accessed using just the class name.
Syntax
static data_type var_name = var_value;
2. final
The final keyword in java is used to restrict the user. The java final keyword
can be used in many contexts. Final can be: variable, method and class.
The final keyword indicates that the specific class cannot be extended or a method
cannot be overridden.
Syntax
final data_type VAR_NAME= var_value;
Use uppercase to declare final variables in Java.
3. abstract
The abstract keyword is used to achieve abstraction in Java. It is a non-access
modifier which is used to create abstract class and method. The role of an abstract
class is to contain abstract methods.
Syntax
abstract class class-name
{
//body of class
}
4. Synchronized
Java programming language provides a very handy way of creating
threads and synchronizing their task by using synchronized blocks to keep shared
resources.
Syntax
public synchronized void showDetails()
{
.......
}
5. transient
Java transient keyword is used in serialization. If you define any data
member as transient, it will not be serialized.
Syntax
public transient int limit = 55; // will not persist
public int b; // will persist
6. Volatile
Volatile keyword is used to modify the value of a variable (either
primitive type or objects) by different threads. It is also used to make classes thread
safe.
Syntax
volatile data_type variable_name;
7. native
The native keyword is applied to a method to indicate that the method is
implemented in native code using JNI (Java Native Interface). Native is a modifier
applicable only for methods and cannot apply it anywhere else. The methods which
are implemented in C, C++ are called as native methods or foreign methods.
Syntax
[ public | protected | private] native [return_type] method ();
A method marked as native cannot have a body and should end with a semicolon.
1. static
The static keyword in Java is used for memory management mainly. We can apply
static keyword with variables, methods, blocks and nested classes. The static keyword
belongs to the class than an instance of the class.
To access static methods there is no need to instantiate the class. Static methods can
be accessed using just the class name.
Syntax
static data_type var_name = var_value;
Example:
// static variable
class static_gfg {
static String s = “RMK";
}
class GFG {
public static void main(String[] args)
{
// No object required
System.out.println(
static_gfg.s);
}
}
OUTPUT: RMK
In this above code sample, we have declared the String as static, part of
the static_gfg class. Generally, to access the string, we first need to create the object
of the static_gfg class, but as we have declared it as static, we do not need to create an
object of static_gfg class to access the string. We can
use className.variableName for accessing it.
2. final
• The final keyword in java is used to restrict the user. The java final keyword
can be used in many contexts. Final can be: variable, method and class.
• The final keyword indicates that the specific class cannot be extended or a
method cannot be overridden.
Syntax
final data_type VAR_NAME= var_value;
Final Variables Example:
Class GFG
// native method
static
System.loadLibrary ("LibraryName");
obj.printMethod ();
}
12b.3 Explain comment statements?
Answer:
• Comments are the statements that are not executed by the compiler and interpreter.
• Comments can be used to provide information or explanation about the variable,
method, class or any statement.
• Comments can also be used to hide program code.
Types of Comments
There are three types of comments in Java.
• Single Line Comment
• Multi Line Comment
• Documentation Comment
Single Line Comment
The single line comment is used to comment only one line.
Syntax:
//This is single line comment
Example:
public class CommentsDemo {
public static void main(String[] args) {
int i = 10; // Here, i is a variable
System.out.println(i);
}
}
Output:
10
12b.5 Write the difference between object-oriented analysis process and structure-
oriented analysis process?
Answer:
Object-oriented analysis
• It is concerned with modeling the application domain.
• The main focus in on data structure and real-world objects that are important.
• It uses Incremental or Iterative methodology to refine and extend our design.
• It is suitable for large projects with changing user requirements.
• Risk while using this analysis technique is low and reusability is also high.
• Requirement engineering includes Use case model (find Use cases, Flow of events,
Activity Diagram), the Object model (find Classes and class relations, Object
interaction, Object to ER mapping), Statechart Diagram, and deployment diagram.
• This technique is new and is mostly preferred.
Structured Analysis
• The main focus is on process and procedures of system.
• It uses System Development Life Cycle (SDLC) methodology for different purposes
like planning, analyzing, designing, implementing, and supporting an information
system.
• It is suitable for well-defined projects with stable user requirements. Risk while using
this analysis technique is high and reusability is also low.
• Structuring requirements include DFDs (Data Flow Diagram), Structured English, ER
(Entity Relationship) diagram, CFD (Control Flow Diagram), Data Dictionary,
Decision table/tree, State transition diagram.
• This technique is old and is not preferred usually.
Object Oriented
In java, everything is an object which has some data and behaviour. Java can be
easily extended as it is based on Object Model. Following are some basic concept of OOP’s.
i. Object
ii. Class
iii. Inheritance
iv. Polymorphism
v. Abstraction
vi. Encapsulation
Simple
• Java is easy to learn and its syntax is quite simple, and easy to understand. The
confusing and ambiguous concepts of C++ are either left out in Java
• Eg : Pointers and Operator Overloading are not there in java but were an important
part of C++.
Secure
• When it comes to security, Java is always the first choice.
• With java secure features it enable us to develop virus free system.
• Java program always runs in Java runtime environment with almost null interaction
with system OS, hence it is more secure.
Platform Independent
• Unlike other programming languages such as C, C++ etc which are compiled into
platform specific machines.
• Java is guaranteed to be write-once, run-anywhere language.
• On compilation Java program is compiled into bytecode. This bytecode is platform
independent and can be run on any machine, plus this bytecode format also provide
security. Any machine with Java Runtime Environment can run Java Programs.
Robust
• Robustness is the capacity of a computer system to handle the errors during execution
and manage the incorrect input of data.
Java is robust because it utilizes strong memory management.
Portable
• Java Byte code can be carried to any platform. No implementation dependent features.
• Everything related to storage is predefined, example: size of primitive data types.
Architectural Neutral
• Compiler generates bytecodes, which have nothing to do with a particular computer
architecture,
• Hence a Java program is easy to intrepret on any machine.
Dynamic
• Java is a dynamic language.
• It supports the dynamic loading of classes.
• It means classes are loaded on demand.
• It also supports functions from its native languages, i.e., C and C++.
Java Interpreter
• Java is a platform-independent programming language. It means that we can run Java
on the platforms that have a Java interpreter.
• It is the reason that makes the Java platform-independent.
• The Java interpreter converts the Java bytecode (.class file) into the code understand
by the operating system.
High Performance
• Java is faster than other traditional interpreted programming languages because Java
bytecode is "close" to native code.
• It is still a little bit slower than a compiled language (e.g., C++). Java is an interpreted
language that is why it is slower than compiled languages, e.g., C, C++, etc.
Multi-threaded
• A thread is like a separate program, executing concurrently.
• We can write Java programs that deal with many tasks at once by defining multiple
threads.
• The main advantage of multi-threading is that it doesn't occupy memory for each
thread. It shares a common memory area.
• Threads are important for multi-media, Web applications, etc.
Distributed
• Java is also a distributed language. Programs can be designed to run on computer
networks.
• Java has a special class library for communicating using TCP/IP protocols.
• Creating network connections is very much easy in Java as compared to C/C++.
13a.2 Explain the structure of java programming?
Answer:
Documentation Section
It is used to improve the readability of the program. It consists of comments in Java which
include basic information such as the method’s usage or functionality to make it easier for the
programmer to understand it while reviewing or debugging the code. A Java comment is not
necessarily limited to a confined space, it can appear anywhere in the code. The compiler
ignores these comments during the time of execution and is solely meant for improving the
readability of the Java program.
There are three types of comments that Java supports
• Single line Comment - Single line comments can be written using
// Single line Comment
• Multi-line Comment - Block comments are used to provide descriptions of files,
methods, data structures and algorithms. Block comments may be used at the
beginning of each file and before each method
/*
Here is a block comment
*/
• Documentation Comment: The JDK javadoc tool uses doc comments when
preparing automatically generated documentation.
/**
documentation comments
*/
Package Statement
Java that allows you to declare your classes in a collection called package. There can
be only one package statement in a Java program and it has to be at the beginning of the code
before any class or interface declaration. This statement is optional, for example, take a look
at the statement below.
package student;
Import Statement
Many predefined classes are stored in packages in Java, an import statement is used to
refer to the classes stored in other packages. An import statement is always written after the
package statement but it has to be before any class declaration. We can import a specific class
or classes in an import statement.
import java.util.Date; // Imports the Date class from util package
import java.sql.*; // Imports all the classes from sql package
Interface Section
This section is used to specify an interface in Java. It is an optional section which is
mainly used to implement multiple inheritance in Java. An interface is a lot similar to a class
in Java but it contains only constants and method declarations.
Class Definition
A Java program may contain several class definitions, classes are an essential part of
any Java program. It defines the information about the user-defined classes in a program. A
class is a collection of variables and methods that operate on the fields. Every program in
Java will have at least one class with the main method.
Main Method Class
The main method is from where the execution actually starts and follows the order specified
for the following statements. Structure of main method class
public class Example{
//main method declaration
public static void main(String args[])
System.out.println ("hello world");
}
}
public class Example: This creates a class called Example. You should make sure that the
class name starts with a capital letter, and the public word means it is accessible from any
other classes.
Braces: The curly brackets are used to group all the commands together. To make sure that
the commands belong to a class or a method.
public static void main: When the main method is declared public, it means that it can be
used outside of this class as well. The word static means that we want to access a method
without making its objects. As we call the main method without creating any objects. The
word void indicates that it does not return any value. The main is declared as void because it
does not return any value. Main is the method, which is an essential part of any Java program.
String[] args: It is an array where each element is a string, which is named as args. If you
run the Java code through a console, you can pass the input parameter. The main() takes it as
an input.
System.out.println(); : The statement is used to print the output on the screen where the
system is a predefined class, out is an object of the PrintWriter class. The method println
prints the text on the screen with a new line. All Java statements end with a semicolon.
Example Structure of Java Source File
/* A first program in Java */
public class Welcome
{
public static void main( String args[])
{
System.out.println( "Welcome to Java!" );
// Prints Welcome to Java!
}
}
Output:
Welcome to java!
Execution of Java Program
Java program can be executed using the following means
1. In command prompt
2. IDE
3. Online compilers
13a.3 Describe java environment/java architecture?
Answer:
Java programs can typically be developed in five stages:
• Edit
• Compile
• Loading
• Verify
• Execute
13a.5 Describe core java and explain the difference between the core java and advanced
java?
Answer:
Both Core Java and Advance Java are parts of Java programming, but for
understanding the entire Java better, we need to differentiate between both. So, below we
have described some differences between both core java and advance Java:
Core Java covers the basic concepts of the Advance Java covers the advanced topics
Java programming language. and concepts of the Java programming language.
Core Java is used for developing Advance Java is used for developing
computing or desktop applications. enterprise applications.
It is the first step, to begin with, Java. It is the next step after completing the Core
Java.
It covers core topics such as OOPs, It covers advanced topics such as JDBC,
inheritance, exception handling, etc. servlets, JSP, web services etc.
13b.1 Explain autoboxing with example?
Answer:
The automatic conversion that the Java compiler makes between the primitive types
and their corresponding object wrapper classes.
Autoboxing
• Automatic conversion of primitive types to the object of their corresponding wrapper
classes is known as autoboxing.
• For example, converting int to Integer class. The Java compiler applies autoboxing
when a primitive value is:
• Passed as a parameter to a method that expects an object of the corresponding
wrapper class.
• Assigned to a variable of the corresponding wrapper class.
Example
// Java program to demonstrate Autoboxing
class Autoboxing
{
public static void main(String[] args)
{
char ch = 'a';
// Autoboxing- primitive to Character object conversion
Character a = ch;
ArrayList<Integer> arrayList = new ArrayList<Integer>();
// Autoboxing because ArrayList stores only objects
arrayList.add(25);
// printing the values from object
System.out.println(arrayList.get(0));
}
}
13b.2 Explain unboxing with example?
Answer:
Unboxing
• It is just the reverse process of autoboxing. Automatically converting an object of a
wrapper class to its corresponding primitive type is known as unboxing.
• For example conversion of Integer to int. The Java compiler applies to unbox when an
object of a wrapper class is:
• Passed as a parameter to a method that expects a value of the corresponding
primitive type.
• Assigned to a variable of the corresponding primitive type.
Example
// Java program to demonstrate Unboxing
import java.util.ArrayList;
class Unboxing
{
public static void main(String[] args)
{
Character ch = 'a';
// unboxing - Character object to primitive conversion
char a = ch;
ArrayList<Integer> arrayList=new ArrayList<Integer>();
arrayList.add(24);
// unboxing because get method returns an Integer object
int num = arrayList.get(0);
// printing the values from primitive data types
System.out.println(num);
}
}
13b.3 Explain widening and narrow conversion with example?
Answer:
• Type promotion automatically promotes the lower range value to higher range value.
• Java automatically promotes each byte, short, or char operand to int when evaluating
an expression.
• If one operand is long, float or double the whole expression is promoted to long,
float, or double respectively.
• If we want to assign a value of a larger data type to a smaller data type we perform
explicit type casting or narrowing.
• This is useful for incompatible data types where automatic conversion cannot be
done.
Example
// Java program to Illustrate Explicit Type Conversion
// Main class
public class GFG
{
// Main driver method
public static void main(String[] args)
{
// Double datatype
double d = 100.04;
// Explicit type casting by forcefully getting
// data from long datatype to integer type
long l = (long)d;
// Explicit type casting
int i = (int)l;
// Print statements
System.out.println("Double value " + d);
// While printing we will see that
// fractional part lost
System.out.println("Long value " + l);
// While printing we will see that
// fractional part lost
System.out.println("Int value " + i);
}
}
Output
Double value 100.04
Long value 100
Int value 100
13b.4 Explain datatype promotion and automatic type conversion with example?
Answer:
Data Type Promotion
• Type promotion automatically promotes the lower range value to higher range value.
• Java automatically promotes each byte, short, or char operand to int when evaluating
an expression.
• If one operand is long, float or double the whole expression is promoted to long,
float, or double respectively.
Automatic Type Conversion
// Java Program to Illustrate Automatic Type Conversion
// Main class
class GFG {
// Main driver method
public static void main(String[] args)
{
int i = 100;
// Automatic type conversion
// Integer to long type
long l = i;
// Automatic type conversion
// long to float type
float f = l;
// Print and display commands
System.out.println("Int value " + i);
System.out.println("Long value " + l);
System.out.println("Float value " + f);
}
}
Output
Int value 100
Long value 100
Float value 100.0
13b.5 Explain explicit conversion and type promotion in expression with example?
Answer:
Narrowing or Explicit Conversion
• If we want to assign a value of a larger data type to a smaller data type we perform
explicit type casting or narrowing.
• This is useful for incompatible data types where automatic conversion cannot be
done.
Example
// Java program to Illustrate Explicit Type Conversion
// Main class
public class GFG
{
// Main driver method
public static void main(String[] args)
{
// Double datatype
double d = 100.04;
// Explicit type casting by forcefully getting
// data from long datatype to integer type
long l = (long)d;
// Explicit type casting
int i = (int)l;
// Print statements
System.out.println("Double value " + d);
// While printing we will see that
// fractional part lost
System.out.println("Long value " + l);
// While printing we will see that
// fractional part lost
System.out.println("Int value " + i);
}
}
Output
Double value 100.04
Long value 100
Int value 100
Type Promotion in Expression
While evaluating expressions, the intermediate value may exceed the range of operands and
hence the expression value will be promoted. Some conditions for type promotion are:
1. Java automatically promotes each byte, short, or char operand to int when evaluating
an expression.
2. If one operand is long, float or double the whole expression is promoted to long, float,
or double respectively.
Example
// Java program to Illustrate Type promotion in Expressions
// Main class
class GFG {
// Main driver method
public static void main(String args[])
{
// Declaring and initializing primitive types
byte b = 42;
char c = 'a';
short s = 1024;
int i = 50000;
float f = 5.67f;
double d = .1234;
// The Expression
double result = (f * b) + (i / c) - (d * s);
// Printing the result obtained after
// all the promotions are done
System.out.println("result = " + result);
}
}
Output
result = 626.7784146484375
14a.1 Explain nested class and its types?
Answer:
Inner class:
Java inner class or nested class is a class that is declared inside the class or interface.
• We use inner classes to logically group classes and interfaces in one place to be more
readable and maintainable.
Additionally, it can access all the members of the outer class, including private data members
and methods.
Syntax of Inner class
class Java_Outer_class
{
//code
class Java_Inner_class
{
//code
}
}
Types of Nested classes
There are two types of nested classes non-static and static nested classes. The non-
static nested classes are also known as inner classes.
• Non-static nested class (inner class)
• Member inner class
• Anonymous inner class
• Local inner class
• Static nested class
14a.2 Explain inner class and describe advantages of inner class?
Answer:
Java inner class or nested class is a class that is declared inside the class or interface.
• We use inner classes to logically group classes and interfaces in one place to be more
readable and maintainable.
• Additionally, it can access all the members of the outer class, including private data
members and methods.
Syntax of Inner class
class Java_Outer_class
{
//code
class Java_Inner_class
{
//code
}
}
Advantage of Java inner class
There are three advantages of inner classes in Java. They are as follows:
1. Nested classes represent a particular type of relationship that is it can access all the
members (data members and methods) of the outer class, including private.
2. Nested classes are used to develop more readable and maintainable code because it
logically group classes and interfaces in one place only.
3. Code Optimization: It requires less code to write.
Example:
class TestMemberOuter1
{
private int data=30;
class Inner
{
void msg()
{
System.out.println(“Data is "+data);
}
}
public static void main(String args[])
{
TestMemberOuter1 obj=new TestMemberOuter1();
TestMemberOuter1.Inner in=obj.new Inner();
in.msg();
}
}
Output
Data is 30
14a.3 Explain non-static class with example?
Answer:
Types of Nested classes
There are two types of nested classes
• non-static and
• static nested classes.
The non-static nested classes are also known as inner classes.
Non-static nested class (inner class)
• Member inner class
• Anonymous inner class
• Local inner class
Output
inside outerMethod
inside innerMethod
14a.5 Explain nested interface with example?
Answer:
An interface, i.e., declared within another interface or class, is known as a nested
interface. The nested interfaces are used to group related interfaces so that they can be easy to
maintain. The nested interface must be referred to by the outer interface or class. It can't be
accessed directly.
Points to remember for nested interfaces
• The nested interface must be public if it is declared inside the interface, but it can
have any access modifier if declared within the class.
• Nested interfaces are declared static
Syntax of nested interface which is declared within the interface
interface interface_name{
...
interface nested_interface_name{
...
}
}
Syntax of nested interface which is declared within the class
class class_name{
...
interface nested_interface_name{
...
}
}
Example of nested interface which is declared within the interface
TestNestedInterface1.java
interface Showable
{
void show();
interface Message
{
void msg();
}
}
class TestNestedInterface1 implements Showable.Message
{
public void msg()
{
System.out.println("Hello nested interface");
}
public static void main(String args[])
{
Showable.Message message=new TestNestedInterface1();
//upcasting here
message.msg();
}
}
Output
Hello nested interface
As you can see in the above example, we are accessing the Message interface by its
outer interface Showable because it cannot be accessed directly. It is just like the almirah
inside the room; we cannot access the almirah directly because we must enter the room first.
Internal code generated by the java compiler for nested interface Message
The java compiler internally creates a public and static interface as displayed below:
public static interface Showable$Message
{
public abstract void msg();
}
14b.1 Explain java member inner class with example?
Answer:
A non-static class that is created inside a class but outside a method is called member
inner class. It is also known as a regular inner class. It can be declared with access modifiers
like public, default, private, and protected.
Syntax:
class Outer
{
//code
class Inner
{
//code
}
}
Example
In this example, we are creating a msg () method in the member inner class that is
accessing the private data member of the outer class.
TestMemberOuter1.java
class TestMemberOuter1
{
private int data=30;
class Inner
{
void msg()
{
System.out.println(“Data is "+data);
}
}
public static void main(String args[])
{
TestMemberOuter1 obj=new TestMemberOuter1();
TestMemberOuter1.Inner in=obj.new Inner();
in.msg();
}
}
Output
Data is 30
14b.4 Define non-primitive data types and explain the difference between the primitive
and non-primitive datatypes in java?
Answer:
The main difference between primitive and non-primitive data types are:
Primitive data types:
• The primitive data types include boolean, char, byte, short, int, long, float and
double.
• Primitive types are predefined (already defined) in Java.
• Primitive types cannot be used to call methods to perform certain operations.
• A primitive type has always a value.
• A primitive type starts with a lowercase letter.
• The size of a primitive type depends on the data type.
Non-primitive data types:
• The non-primitive data types include Classes, Interfaces, and Arrays.
• Non-primitive types are created by the programmer and is not defined by Java (except
for String).
• Non-primitive types can be used to call methods to perform certain operations.
• Non-primitive types can be null.
• Non-primitive types start with an uppercase letter.
• Non-primitive types have all the same size.
1. Functionality
Suitability = To provide an adequate set of functions for specified tasks and user
objectives.
Accuracy = To provide the right or agreed-upon results or effects.
Interoperability = To interact with one or more specified systems.
Security = To prevent unintended access and resist deliberate attacks intended to gain
unauthorized access to confidential information.
2. Reliability
4. Efficiency
6. Portability
Types of Association
1) IS-A Association
The IS-A Association is also referred to as Inheritance.
Example:
2) HAS-A Association
The HAS-A Association is further classified into two parts, i.e., Aggregation
and Composition.
Aggregation
In aggregation, the child is not dependent on its parent i.e., standalone.
Example:
Composition
• In composition, the child is dependent on its parent.
• An aggregation is a special form of association, and composition is the
special form of aggregation.
Example:
Syntax
class derived-class extends base-class
{
//methods and fields
}
• The class features are inherited is known as super class (or a base class or a parent
class). The class that inherits the other class is known as sub class (or a derived class,
extended class, or child class). The subclass can add its own fields and methods in
addition to the superclass fields and methods.
• The child class will inherit all the public and protected properties and methods from
the parent class. In addition, it can have its own properties and methods.
• Inheritance supports reusability,
• i.e. When we want to add new features to an existing entity, we can derive our new
entity from the existing using inheritance. This enables reusing the fields and methods
of the existing class.
An inherited class is defined by using the extends keyword.
Types of Inheritance:
1. Single Inheritance:
2. Multilevel Inheritance:
In Multilevel Inheritance, a derived class will be inheriting a base class and as
well as the derived class also act as the base class to other class.
Example:
Class A serves as a base class for the derived class B, which in turn
serves as a base class for the derived class C.
class one {
public void print_geek()
{
System.out.println("Geeks");
}
}
Output
Geeks
for
3. Multiple Inheritance
interface two {
public void print_for();
}
4. Hybrid inheritance
In Java, the hybrid inheritance is the composition of two or more types of inheritance.
The main purpose of using hybrid inheritance is to modularize the code into well-defined
classes. It also provides the code reusability.
5. Hierarchical inheritance
When more than one classes inherit a same class then this is called hierarchical
inheritance.
Class Device has a field named as deviceName. Class Bulb extends Device that
means Bulb is a type of Device. Since Device is the parent class which implies that class
Device can store the reference of an instance of class Bulb.
Output
Device name is Bulb
Bulb is a Device
Has-A relationship: Whenever an instance of one class is used in another class, it is called
HAS-A relationship.
Example:
Consider two classes Student and Address. Each student has own address that makes
has-a relationship but address has student not makes any sense. We can understand it more
clearly using Java code.
Class Address{
int street_no;
String city;
String state;
int pin;
Address(int street_no, String city, String state, int pin ){
this.street_no = street_no;
this.city = city;
this.state = state;
this.pin = pin;
}
}
class Student
{
String name;
Address ad;
}
Here in the above code, we can see Student class has-a relationship
with Address class. We have draw an image too to demonstrate relation between these two
classes.
The Student class has an instance variable of type Address. As we have a variable of
type Address in the Student class, it can use Address reference which is ad in this case, to
invoke methods of the Address class.