Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Java Inheritance and Inner Classes, Study notes of Java Programming

An in-depth exploration of inheritance in java, including inheritance hierarchies, super and sub classes, member access rules, and the use of the 'super' keyword. It also covers the concept of preventing inheritance through final classes and methods, and delves into the object class and its methods. The document further discusses inner classes, their uses, and types, such as local, anonymous, and static inner classes. Examples are provided to illustrate these concepts.

Typology: Study notes

2022/2023

Uploaded on 04/15/2024

2iioiim2oo2
2iioiim2oo2 🇮🇳

1 document

1 / 121

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
INTRODUCTION TO JAVA
PROGRAMMING
LECTURE NOTES
B.TECH III YEAR I SEM (R17)
(2019-20)
DEPARTMENT OF ELECTRICAL & ELECTRONICS ENGINEERING
MALLA REDDY COLLEGE OF ENGINEERING & TECHNOLOGY
(Autonomous Institution UGC, Govt. of India)
(Affiliated to JNTUH, Hyderabad, Approved by AICTE - Accredited by NBA & NAAC ‘A’ Grade - ISO 9001:2015 Certified)
Maisammaguda, Dhulapally (Post Via. Hakimpet), Secunderabad 500100, Telangana State, INDIA.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46
pf47
pf48
pf49
pf4a
pf4b
pf4c
pf4d
pf4e
pf4f
pf50
pf51
pf52
pf53
pf54
pf55
pf56
pf57
pf58
pf59
pf5a
pf5b
pf5c
pf5d
pf5e
pf5f
pf60
pf61
pf62
pf63
pf64

Partial preview of the text

Download Java Inheritance and Inner Classes and more Study notes Java Programming in PDF only on Docsity!

INTRODUCTION TO JAVA

PROGRAMMING

LECTURE NOTES

B.TECH III YEAR – I SEM (R17)

DEPARTMENT OF ELECTRICAL & ELECTRONICS ENGINEERING

MALLA REDDY COLLEGE OF ENGINEERING & TECHNOLOGY

(Autonomous Institution – UGC, Govt. of India)

(Affiliated to JNTUH, Hyderabad, Approved by AICTE - Accredited by NBA & NAAC – ‘A’ Grade - ISO 9001:2015 Certified) Maisammaguda, Dhulapally (Post Via. Hakimpet), Secunderabad – 500100, Telangana State, INDIA.

MALLA REDDY COLLEGE OF ENGINEERING &TECHNOLOGY

DEPARTMENT OF EEE

Objectives:

INTRODUCTION TO JAVA PROGRAMMING

This subject aims to introduce students to the Java programming language. Upon successful completion of this subject, students should be able to create Java programs that leverage the object-oriented features of the Java language, such as encapsulation, inheritance and polymorphism; use data types, arrays and other data collections; implement error-handling techniques using exception handling, create and event-driven GUI using Swing components. UNIT-I OOP Concepts:- Data abstraction, encapsulation, inheritance, Benefits of Inheritance, Polymorphism, classes and objects, Procedural and object oriented programming paradigms. Java Programming- History of Java, comments, Data types, Variables, Constants, Scope and Lifetime of variables, Operators, Operator Hierarchy, Expressions, Type conversion and casting, Enumerated types, Control flow- block scope, conditional statements, loops, break and continue statements, simple java stand alone programs, arrays, console input and output, formatting output, constructors, methods, parameter passing, static fields and methods, access control, this reference, overloading methods and constructors, recursion, garbage collection, building strings, exploring string class. UNIT – II Inheritance – Inheritance hierarchies super and sub classes, Member access rules, super keyword, preventing inheritance: final classes and methods, the Object class and its methods. Polymorphism – dynamic binding, method overriding, abstract classes and methods. Interfaces- Interfaces Vs Abstract classes, defining an interface, implement interfaces, accessing implementations through interface references, extending interface. Inner classes- Uses of inner classes, local inner classes, anonymous inner classes, static inner classes, examples. Packages- Defining, creating and accessing a package, Understanding CLASSPATH, importing packages. UNIT-III Exception handling- Dealing with errors, benefits of exception handling, the classification of exceptions- exception hierarchy, checked exceptions and unchecked exceptions, usage of try, catch, throw, throws and finally, rethrowing exceptions, exception specification, built in exceptions, creating own exception sub classes. Multithreading – Differences between multiple processes and multiple threads, thread states, creating threads, interrupting threads, thread priorities, synchronizing threads, inter-thread communication, producer consumer pattern, Exploring java.net and java. Text. UNIT-IV Applets – Concepts of Applets, differences between applets and applications, life cycle of an applet, types of applets, creating applets, passing parameters to applets. Event Handling: Events, Handling mouse and keyboard events, Adapter classes. Files- Streams- Byte streams, Character streams, Text input/output.

MALLA REDDY COLLEGE OF ENGINEERING &TECHNOLOGY

DEPARTMENT OF EEE

INDEX

S. No Unit Topic Page no 1 I OOP Concepts:- Data abstraction, encapsulation inheritance 1 2 I Benefits of Inheritance 2 3 I Polymorphism, classes and objects 2 4 I Procedural and object oriented programming paradigms 3 5 I Java Programming- History of Java 4 6 I Comments, Data types, Variables, Constants 5 -^9 7 I Scope and Lifetime of variables 10 8 I Operators, Operator Hierarchy, Expressions 11 -^12 9 I Type conversion and casting, Enumerated types 12 -^13 10 I Control flow- block scope, conditional statements, loops, break and continue statements

11 I Simple java stand alone programs, arrays 14 -^18 12 I Console input and output, formatting output 18 -^19 13 I Constructors, methods, parameter passing 19 -^20 14 I Static fields and methods, access control, this reference, 21 -^30 15 I Overloading methods and constructors, recursion, garbage collection,

16 I

Building strings, exploring string class. 34 - 36

S. No Unit Topic Page no 17 II Inheritance – Inheritance hierarchies super and sub classes, Member access rules

18 II

super keyword, preventing inheritance: final classes and methods, the Object class and its methods.

19 II Polymorphism – dynamic binding, method overriding, 41 -^42 20 II^ abstract classes and methods.^43 21 II Interfaces- Interfaces Vs Abstract classes, defining an interface, implement interfaces

22 II^

Accessing implementations through interface references, extendinginterface.

23 II Inner classes- Uses of inner classes, local inner classes 45 -^46 24 II^ Anonymous inner classes, static inner classes, examples. 46 25 II Packages- Defining, creating and accessing a package, 46 -^47 26 II^ Understanding CLASSPATH, importing packages. 47 27 III Exception handling- Dealing with errors, benefits of exception handling

28 III

The classification of exceptions- exception hierarchy, checked exceptions and unchecked exceptions

29 III Usage of try, catch, throw, throws and finally, 50 - 54 30 III^ Rethrowing exceptions, exception specification, 54 31 III Built in exceptions, creating own exception sub classes. 54 32 III Multithreading – Differences between multiple processes and multiple threads, thread states 55 - 56 33 III^ Creating threads, interrupting threads, thread priorities, synchronizing threads 56 - 59 34 III^ Inter-thread communication, producer consumer pattern 59 35 III Exploring java.net and java.text. 60

MALLA REDDY COLLEGE OF ENGINEERING &TECHNOLOGY

DEPARTMENT OF EEE

Unit- 1 OOP Concepts Object Oriented Programming is a paradigm that provides many concepts such as inheritance , data binding , polymorphism etc. Simula is considered as the first object-oriented programming language. The programming paradigm where everything is represented as an object is known as truly object-oriented programming language. Smalltalk is considered as the first truly object-oriented programming language. OOPs (Object Oriented Programming System) Object means a real word entity such as pen, chair, table etc. Object-Oriented Programming is a methodology or paradigm to design a program using classes and objects. It simplifies the software development and maintenance by providing someconcepts: o Object o Class o Inheritance o Polymorphism o Abstraction o Encapsulation Object Any entity that has state and behavior is known as an object. For example: chair, pen, table, keyboard, bike etc. It can be physical and logical. Class Collection of objects is called class. It is a logical entity.

Inheritance

When one object acquires all the properties and behaviours of parent object i.e. known as inheritance. It provides code reusability. It is used to achieve runtime polymorphism.

Polymorphism

When one task is performed by different ways i.e. known as polymorphism. For example: to convince the customer differently, to draw something e.g. shape or rectangle etc. In java, we use method overloading and method overriding to achieve polymorphism. Another example can be to speak something e.g. cat speaks meaw, dog barks woof

etc. Abstraction

Hiding internal details and showing functionality is known as abstraction. For example: phone call, we don't know the internal processing. In java, we use abstract class and interface to achieve abstraction.

Encapsulatio n

Binding (or wrapping) code and data together into a single unit is known as encapsulation. For example: capsule, it is wrapped with different medicines. A java class is the example of encapsulation. Java bean is the fully encapsulated class because all the data members are private here.

Benefits of Inheritance

  • One of the key benefits of inheritance is to minimize the amount of duplicate code in an application by sharing common code amongst several subclasses. Where equivalent code exists in two related classes, the hierarchy can usually be refactored to move the common code up to a mutual superclass. This also tends to result in a better organization of code and smaller, simpler compilationunits. - Inheritance can also make application code more flexible to change because classesthat inherit from a common superclass can be used interchangeably. If the return type of a method issuperclass - Reusability - facility to use public methods of base class without rewriting thesame. - Extensibility - extending the base class logic as per business logic of the derivedclass.

Java Programming- History of Java The history of java starts from Green Team. Java team members (also known as Green Team ), initiated a revolutionary task to develop a language for digital devices such as set-top boxes, televisionsetc. For the green team members, it was an advance concept at that time. But, it was suited for internet programming. Later, Java technology as incorporated by Netscape. Currently, Java is used in internet programming, mobile devices, games, e-business solutions etc. There are given the major points that describes the history of java.

  1. James Gosling , Mike Sheridan , and Patrick Naughton initiated the Java language project in June 1991. The small team of sun engineers called Green Team.
  2. Originally designed for small, embedded systems in electronic appliances like set- topboxes.
  3. Firstly, it was called "Greentalk" by James Gosling and file extension was.gt. 4) After that, it was called Oak and was developed as a part of the Green project.

Java Version History

There are many java versions that has been released. Current stable release of Java is Java SE 8.

  1. JDK Alpha and Beta (1995)
  2. JDK 1.0 (23rd Jan, 1996)
  3. JDK 1.1 (19th Feb, 1997)
  4. J2SE 1.2 (8th Dec, 1998)
  5. J2SE 1.3 (8th May, 2000)
  6. J2SE 1.4 (6th Feb, 2002)
  7. J2SE 5.0 (30th Sep,2004)
  8. Java SE 6 (11th Dec,2006)
  9. Java SE 7 (28th July, 2011) 10.Java SE 8 (18th March,2014)

Features of Java

There is given many features of java. They are also known as java buzzwords. The Java Features given below are simple and easy to understand.

  1. Simple
  2. Object-Oriented
  3. Portable
  4. Platformindependent
  5. Secured
  6. Robust
  7. Architectureneutral
  8. Dynamic
  9. Interpreted
  10. HighPerformance
  11. Multithreaded
  12. Distributed

Java Comments

The java comments are statements that are not executed by the compiler and interpreter. The

comments can be used to provide information or explanation about the variable, method, class or

any statement. It can also be used to hide program code for specific time.

Types of Java Comments

There are 3 types of comments in java.

  1. Single LineComment
  2. Multi LineComment
  3. DocumentationComment

Java Single Line Comment

The single line comment is used to comment only one line. Syntax:

  1. //This is single line comment

Java Documentation Comment

The documentation comment is used to create documentation API. To create documentation API, you need to use javadoc tool. Syntax: /** This is documentation comment / Example: /* The Calculator class provides methods to get addition and subtraction of given 2 numbers./ public class Calculator { /* The add() method returns addition of given numbers./ public static int add( int a, int b){ return a+b;} /* The sub() method returns subtraction of given numbers.*/ public static int sub( int a, int b){ return a-b;} } Compile it by javac tool: javac Calculator.java Create Documentation API by javadoc tool: javadoc Calculator.java Now, there will be HTML files created for your Calculator class in the current directory. Open the HTML files and see the explanation of Calculator class provided through documentation comment.

Data Types

Data types represent the different values to be stored in the variable. In java, there are two types of data types: o Primitive datatypes o Non-primitive datatypes DataType DefaultValue Default size boolean False 1 bit char '\u0000' 2 byte byte 0 1 byte short 0 2 byte int 0 4 byte long 0L 8 byte float 0.0f 4 byte double 0.0d 8 byte Java Variable Example: Add Two Numbers class Simple{ public static void main(String[] args){ int a= 10 ; int b= 10 ; int c=a+b; System.out.println(c); }} Output:

Scope and Life Time of Variables

The scope of a variable defines the section of the code in which the variable is visible. As a general rule, variables that are defined within a block are not accessible outside that block. The lifetime of a variable refers to how long the variable exists before it isdestroyed. Destroying variables refers to deallocating the memory that was allotted to the variables when declaring it. We have written a few classes till now. You might have observed that not all variables are the same. The ones declared in the body of a method were different from those that were declared in the class itself. There are three types of variables: instance variables, formal parameters or local variables and localvariables. Instance variables Instance variables are those that are defined within a class itself and not in any method or constructor of the class. They are known as instance variables because every instance of the class (object) contains a copy of these variables. The scope of instance variables is determined by the access specifier that is applied to these variables. We have already seen about it earlier. The lifetime of these variables is the same as the lifetime of the object to which it belongs. Object once created do not exist for ever. They are destroyed by the garbage collector of Java when there are no more reference to that object. We shall see about Java's automatic garbage collector later on. Argument variables These are the variables that are defined in the header oaf constructor or a method. The scope of these variables is the method or constructor in which they are defined. The lifetime is limited to the time for which the method keeps executing. Once the method finishes execution, these variables aredestroyed. Local variables A local variable is the one that is declared within a method or a constructor (not in the header). The scope and lifetime are limited to the methoditself. One important distinction between these three types of variables is that access specifiers can be applied to instance variables only and not to argument or local variables. In addition to the local variables defined in a method, we also have variables that are defined in bocks life an if block and an else block. The scope and is the same as that of the block itself.

Operators in java

Operator in java is a symbol that is used to perform operations. For example: +, - , *, / etc. There are many types of operators in java which are given below: o UnaryOperator, o ArithmeticOperator, o shiftOperator, o RelationalOperator, o BitwiseOperator, o LogicalOperator, o Ternary Operatorand o AssignmentOperator.

Operators Hierarchy

Output: WINTER SPRING SUMMER FALL

Java Enum

Enum in java is a data type that contains fixed set of constants. It can be used for days of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY and SATURDAY) , directions (NORTH, SOUTH, EAST and WEST) etc. The java enum constants are static and final implicitly. It is available from JDK 1.5. Java Enums can be thought of as classes that have fixed set of constants. Simple example of java enum class EnumExample1{ public enum Season { WINTER, SPRING, SUMMER, FALL } public static void main(String[] args) { for (Season s : Season.values()) System.out.println(s); }} Control Flow Statements The control flow statements in Java allow you to run or skip blocks of code when special conditions are met. The “if” Statement The “if” statement in Java works exactly like in most programming languages. With the help of “if” you can choose to execute a specific block of code when a predefined condition is met. The structure of the “if” statement in Java looks like this: if(condition) { // execute this code }

The condition is Boolean. Boolean means it may be true or false. For example you may put a mathematical equation as condition. Look at this full example: Creating a Stand-Alone Java Application

1. Write a main method that runs your program. You can write this method anywhere. In this example, I'll write my main method in a class called Main that has no other methods. For example: 2. public class Main

  1. {
  2. public static void main(String[] args)
  3. {
  4. Game.play();
  5. } }
  6. Make sure your code is compiled, and that you have tested it thoroughly.
  7. If you're using Windows, you will need to set your path to include Java, if you haven't done so already. This is a delicate operation. Open Explorer, and look inside C:\ProgramFiles\Java, and you should see some version of the JDK. Open this folder, and then open the bin folder. Select the complete path from the top of the Explorer window, and press Ctrl-C to copyit. Next, find the "My Computer" icon (on your Start menu or desktop), right-click it, and select properties. Click on the Advanced tab, and then click on the Environment variables button. Look at the variables listed for all users, and click on the Path variable. Do not delete the contents of this variable! Instead, edit the contents by moving the cursor to the right end, entering a semicolon (;), and pressing Ctrl-V to paste the path you copied earlier. Then go ahead and save your changes. (If you have any Cmd windows open, you will need to close them.)
  8. If you're using Windows, go to the Start menu and type "cmd" to run a program that brings up a command prompt window. If you're using a Mac or Linux machine, run the Terminal program to bring up a commandprompt.
  9. In Windows, type dir at the command prompt to list the contents of the current directory. On a Mac or Linux machine, type ls to dothis.