Lecture Notes
Module-3, Chapter-1
Inheritance
Programme: B E (CSE)
Semester: 3
Course Code: BCS306A
Course Instructor: Demian Antony Dmello
2022 Scheme of VTU
Inheritance: Inheritance Basics, Using super, Creating a Multilevel Hierarchy, When Constructors Are Executed, Method Overriding, Dynamic Method Dispatch, Using Abstract Classes, Using final with Inheritance, Local Variable Type Inference and Inheritance, The Object Class.
Interfaces: Interfaces, Default Interface Methods, Use static Methods in an Interface, Private Interface Methods.
Lecture Notes
Module-1, Chapter-1
An Overview of Java
Programme: B E (CSE)
Semester: 3
Course Code: BCS306A
Course Instructor: Demian Antony Dmello
2022 Scheme of VTU
An Overview of Java: Object-Oriented Programming (Two Paradigms, Abstraction, The Three OOP Principles), Using Blocks of Code, Lexical Issues (Whitespace, Identifiers, Literals, Comments, Separators, The Java Keywords).
Data Types, Variables, and Arrays: The Primitive Types (Integers, Floating-Point Types, Characters, Booleans), Variables, Type Conversion and Casting, Automatic Type Promotion in Expressions, Arrays, Introducing Type Inference with Local Variables.
Operators: Arithmetic Operators, Relational Operators, Boolean Logical Operators, The Assignment Operator, The ? Operator, Operator Precedence, Using Parentheses.
Control Statements: Java’s Selection Statements (if, The Traditional switch), Iteration Statements (while, do-while, for, The For-Each Version of the for Loop, Local Variable Type Inference in a for Loop, Nested Loops), Jump Statements (Using break, Using continue, return).
An Overview of Java; Data Types, Variables and Arrays; Operators; Control Statements.
Introducing Classes; Methods and Classes.
Inheritance; Interfaces.
Packages; Exceptions.
Multithreaded Programming; Enumerations, Type Wrappers and Autoboxing.
Textbook
Java: The Complete Reference, Twelfth Edition, by Herbert Schildt, November 2021, McGraw-Hill, ISBN: 9781260463422
References:
Programming with Java, 6th Edition, by E Balagurusamy, Mar-2019, McGraw Hill Education, ISBN: 9789353162337
Thinking in Java, Fourth Edition, by Bruce Eckel, Prentice Hall, 2006 (https://sd.blackball.lv/library/thinking_in_java_4th_edition.pdf)
This document discusses a list of over 4000 words that are important for the IELTS academic test. It notes that this word list reflects the essential vocabulary level required for the test and will help test takers, especially those aiming for high scores. The list is maintained by Pacific Lava School and includes general academic words that test takers need.
This document discusses intelligent agents and their environments. It covers:
1) Intelligent agents are entities that perceive their environment through sensors and act upon the environment through actuators. They map percept sequences to actions.
2) A rational agent should select actions that are expected to maximize its performance measure given the percept sequence and its prior knowledge. Performance measures evaluate how well the agent solves its task.
3) Agent environments can have different properties such as being fully or partially observable, deterministic or stochastic, episodic or sequential, static or dynamic, discrete or continuous, and single-agent or multi-agent. The simplest is fully observable, deterministic, etc. but most real environments are more complex.
This document discusses exception handling in Java. It defines what exceptions are, why they occur, and what exception handling is. It describes the advantages of exception handling and differences between exceptions and errors. It covers the exception class hierarchy and exception handling keywords like try, catch, finally, throw, and throws. It provides examples of common exception types and an example Java code demonstrating exception handling.
The document discusses software quality and defines key aspects:
- It explains the importance of software quality for users and developers.
- Qualities like correctness, reliability, efficiency are defined.
- Methods for measuring qualities like ISO 9126 standard are presented.
- Quality is important throughout the software development process.
- Both product quality and process quality need to be managed.
The document discusses the emergence of the Internet of Things (IoT). It describes how IoT has evolved from early technologies like automated teller machines and smart meters to modern applications across various domains. It also outlines the key characteristics of IoT and the complex interdependencies between IoT and related technologies like machine-to-machine communication, cyber physical systems, and the web of things. Finally, it explains the four planes that enable IoT - services, local connectivity, global connectivity, and processing - and how technologies like edge/fog computing facilitate IoT implementation.
Java is a programming language that compiles code to bytecode that runs on a Java Virtual Machine (JVM). The JVM is an abstraction layer that executes bytecode similarly across operating systems. It includes components like the bytecode verifier, class loader, execution engine, garbage collector, and security manager. The JVM allows Java to be platform independent and "write once, run anywhere".
The document discusses file handling operations in Visual Basic. It defines a file as a collection of stored data and describes three types of files: sequential access, random access, and binary. It then explains various file handling operations like opening, closing, writing, reading and detecting the end of a file. It provides syntax for performing these operations and describes how to apply these concepts in a sample application for creating, appending to, reading from and writing to a file.
Packages in Java allow grouping of related classes and interfaces to avoid naming collisions. Some key points about packages include:
- Packages allow for code reusability and easy location of files. The Java API uses packages to organize core classes.
- Custom packages can be created by specifying the package name at the beginning of a Java file. The class files are then compiled to the corresponding directory structure.
- The import statement and fully qualified names can be used to access classes from other packages. The classpath variable specifies locations of package directories and classes.
Templates allow functions and classes to operate on generic types in C++. There are two types of templates: class templates and function templates. Function templates are functions that can operate on generic types, allowing code to be reused for multiple types without rewriting. Template parameters allow types to be passed to templates, similar to how regular parameters pass values. When a class, function or static member is generated from a template, it is called template instantiation.
Pipes allow for inter-process communication by connecting the standard output of one process to the standard input of another. Named pipes, also called FIFOs, are similar to pipes but can be accessed using file names. The inode structure for pipes contains fields like wait queues, buffers, and counters for reading/writing processes. Ptrace is a system call that allows a process to debug another by controlling its execution and memory. Sockets provide communication via the network or locally using functions like socket, connect, listen, accept, and send/receive messages as datagrams or streams.
Multithreading allows an application to have multiple points of execution operating concurrently within the same memory space. Each point of execution is called a thread. Threads can run tasks concurrently, improving responsiveness. They share memory and can access resources simultaneously. Synchronization is needed when threads access shared data to prevent inconsistencies.
The document discusses file handling in C++. It defines a file as a collection of information stored on a computer's disk. There are three main steps to processing a file in C++: opening the file, reading/writing information to the file, and closing the file. It also describes different file stream classes like ifstream for input and ofstream for output that are used to read from and write to files. Functions like seekg() and seekp() allow manipulating the file pointer position.
The document discusses different types of relationships that can exist between classes in object-oriented modeling, including aggregation, inheritance, association, and instantiation. Aggregation represents a part-whole or containment relationship. Inheritance defines a hierarchical relationship where subclasses inherit attributes and behaviors from parent classes. Association defines a symmetric relationship where two classes know of and can communicate with each other.
The document discusses various PHP array functions including:
- Array functions like array_combine(), array_count_values(), array_diff() for comparing and merging arrays.
- Sorting arrays with asort(), arsort(), ksort(), krsort().
- Other functions like array_search(), array_sum(), array_rand() for searching, summing and random values.
- Modifying arrays with array_push(), array_pop(), array_shift() for adding/removing elements.
The document provides examples of using each array function in PHP code snippets.
The document discusses various Java I/O streams including input streams, output streams, byte streams, character streams, buffered streams, properties class, print stream, file locking, serialization and print writer class. It provides examples of reading and writing files using FileInputStream, FileOutputStream, FileReader, FileWriter and other stream classes. Methods of different stream classes are also explained along with their usage.
1. The document discusses threads and multithreading in Java. It defines threads as independent paths of execution within a process and explains how Java supports multithreading.
2. Key concepts covered include the different states a thread can be in (new, ready, running, blocked, dead), thread priorities, synchronization to allow threads to safely access shared resources, and methods to control threads like start(), sleep(), join(), etc.
3. Examples are provided to demonstrate how to create and manage multiple threads that run concurrently and synchronize access to shared resources.
This document provides a tutorial on using the Action Bar in Android applications. It discusses what the Action Bar is, how to add actions and menu items, customize the Action Bar, use navigation features like tabs and dropdown menus, and more advanced topics like custom views, contextual action modes, and action providers. Code examples are provided throughout to demonstrate various Action Bar features and capabilities.
The document discusses the HTTP request methods GET and POST. GET requests retrieve data from a specified resource, while POST submits data to be processed by a specified resource. Both can send requests and receive responses. GET requests can be cached, bookmarked, and have data restrictions. POST requests are never cached, cannot be bookmarked, and have no data restrictions. The document compares the advantages and disadvantages of GET and POST and provides examples of appropriate uses for each.
The document discusses the XML DOM (Document Object Model). It defines the DOM as a standard for accessing and manipulating XML documents through a tree structure representation. The DOM defines all elements in an XML document as nodes that can be traversed and modified. It outlines DOM properties and methods for navigating and manipulating the node tree. Advantages of the DOM include its traversable and modifiable tree structure, while disadvantages include higher resource usage compared to SAX parsing.
This document discusses control structures in JavaScript, including if/else statements, switch statements, do/while loops, while loops, and for loops. It provides the syntax for each structure and briefly explains their usage. The if statement allows for conditional execution, switch statements evaluate an expression and execute code based on matching cases, do/while loops execute code at least once even if the condition is false, while loops execute code as long as an expression remains true, and for loops include initialization, condition checking, and iteration in a compact loop syntax.
XML and XML Applications - Lecture 04 - Web Information Systems (WE-DINF-11912)Beat Signer
This document provides an overview of XML, including its definition, structure, and related technologies. It describes XML as a standard format for structured information that uses tags to describe data. It also discusses XML's evolution from SGML, its tree structure, validation, and related specifications and languages like XML Schema, XPath, XSLT, and SAX/DOM for parsing and manipulating XML documents.
This document discusses three relationships between classes in Java: association, aggregation, and composition. Association defines a general relationship between two classes without ownership. Aggregation is a "has-a" relationship where one class contains another but either can exist independently. Composition is a stricter form where the contained class cannot exist without the container and will be deleted with it. Examples are given like a department containing employees in aggregation and a class containing students in composition.
This document contains notes on Java basics from James Tam. It introduces Java programming concepts like input, output, branching, and looping. It also discusses the history of Java's development at Sun Microsystems and how it enables programs to run on different platforms. Finally, it provides an overview of compiling and running a simple Java program from the command line.
The document appears to be a scanned copy of a legal contract for the sale of a residential property located in California. The summary outlines details of the purchase including the buyers and sellers involved in the transaction, purchase price of $1.2 million, and schedule for closing and transfer of ownership within 30 days of acceptance of the offer.
The document discusses file handling operations in Visual Basic. It defines a file as a collection of stored data and describes three types of files: sequential access, random access, and binary. It then explains various file handling operations like opening, closing, writing, reading and detecting the end of a file. It provides syntax for performing these operations and describes how to apply these concepts in a sample application for creating, appending to, reading from and writing to a file.
Packages in Java allow grouping of related classes and interfaces to avoid naming collisions. Some key points about packages include:
- Packages allow for code reusability and easy location of files. The Java API uses packages to organize core classes.
- Custom packages can be created by specifying the package name at the beginning of a Java file. The class files are then compiled to the corresponding directory structure.
- The import statement and fully qualified names can be used to access classes from other packages. The classpath variable specifies locations of package directories and classes.
Templates allow functions and classes to operate on generic types in C++. There are two types of templates: class templates and function templates. Function templates are functions that can operate on generic types, allowing code to be reused for multiple types without rewriting. Template parameters allow types to be passed to templates, similar to how regular parameters pass values. When a class, function or static member is generated from a template, it is called template instantiation.
Pipes allow for inter-process communication by connecting the standard output of one process to the standard input of another. Named pipes, also called FIFOs, are similar to pipes but can be accessed using file names. The inode structure for pipes contains fields like wait queues, buffers, and counters for reading/writing processes. Ptrace is a system call that allows a process to debug another by controlling its execution and memory. Sockets provide communication via the network or locally using functions like socket, connect, listen, accept, and send/receive messages as datagrams or streams.
Multithreading allows an application to have multiple points of execution operating concurrently within the same memory space. Each point of execution is called a thread. Threads can run tasks concurrently, improving responsiveness. They share memory and can access resources simultaneously. Synchronization is needed when threads access shared data to prevent inconsistencies.
The document discusses file handling in C++. It defines a file as a collection of information stored on a computer's disk. There are three main steps to processing a file in C++: opening the file, reading/writing information to the file, and closing the file. It also describes different file stream classes like ifstream for input and ofstream for output that are used to read from and write to files. Functions like seekg() and seekp() allow manipulating the file pointer position.
The document discusses different types of relationships that can exist between classes in object-oriented modeling, including aggregation, inheritance, association, and instantiation. Aggregation represents a part-whole or containment relationship. Inheritance defines a hierarchical relationship where subclasses inherit attributes and behaviors from parent classes. Association defines a symmetric relationship where two classes know of and can communicate with each other.
The document discusses various PHP array functions including:
- Array functions like array_combine(), array_count_values(), array_diff() for comparing and merging arrays.
- Sorting arrays with asort(), arsort(), ksort(), krsort().
- Other functions like array_search(), array_sum(), array_rand() for searching, summing and random values.
- Modifying arrays with array_push(), array_pop(), array_shift() for adding/removing elements.
The document provides examples of using each array function in PHP code snippets.
The document discusses various Java I/O streams including input streams, output streams, byte streams, character streams, buffered streams, properties class, print stream, file locking, serialization and print writer class. It provides examples of reading and writing files using FileInputStream, FileOutputStream, FileReader, FileWriter and other stream classes. Methods of different stream classes are also explained along with their usage.
1. The document discusses threads and multithreading in Java. It defines threads as independent paths of execution within a process and explains how Java supports multithreading.
2. Key concepts covered include the different states a thread can be in (new, ready, running, blocked, dead), thread priorities, synchronization to allow threads to safely access shared resources, and methods to control threads like start(), sleep(), join(), etc.
3. Examples are provided to demonstrate how to create and manage multiple threads that run concurrently and synchronize access to shared resources.
This document provides a tutorial on using the Action Bar in Android applications. It discusses what the Action Bar is, how to add actions and menu items, customize the Action Bar, use navigation features like tabs and dropdown menus, and more advanced topics like custom views, contextual action modes, and action providers. Code examples are provided throughout to demonstrate various Action Bar features and capabilities.
The document discusses the HTTP request methods GET and POST. GET requests retrieve data from a specified resource, while POST submits data to be processed by a specified resource. Both can send requests and receive responses. GET requests can be cached, bookmarked, and have data restrictions. POST requests are never cached, cannot be bookmarked, and have no data restrictions. The document compares the advantages and disadvantages of GET and POST and provides examples of appropriate uses for each.
The document discusses the XML DOM (Document Object Model). It defines the DOM as a standard for accessing and manipulating XML documents through a tree structure representation. The DOM defines all elements in an XML document as nodes that can be traversed and modified. It outlines DOM properties and methods for navigating and manipulating the node tree. Advantages of the DOM include its traversable and modifiable tree structure, while disadvantages include higher resource usage compared to SAX parsing.
This document discusses control structures in JavaScript, including if/else statements, switch statements, do/while loops, while loops, and for loops. It provides the syntax for each structure and briefly explains their usage. The if statement allows for conditional execution, switch statements evaluate an expression and execute code based on matching cases, do/while loops execute code at least once even if the condition is false, while loops execute code as long as an expression remains true, and for loops include initialization, condition checking, and iteration in a compact loop syntax.
XML and XML Applications - Lecture 04 - Web Information Systems (WE-DINF-11912)Beat Signer
This document provides an overview of XML, including its definition, structure, and related technologies. It describes XML as a standard format for structured information that uses tags to describe data. It also discusses XML's evolution from SGML, its tree structure, validation, and related specifications and languages like XML Schema, XPath, XSLT, and SAX/DOM for parsing and manipulating XML documents.
This document discusses three relationships between classes in Java: association, aggregation, and composition. Association defines a general relationship between two classes without ownership. Aggregation is a "has-a" relationship where one class contains another but either can exist independently. Composition is a stricter form where the contained class cannot exist without the container and will be deleted with it. Examples are given like a department containing employees in aggregation and a class containing students in composition.
This document contains notes on Java basics from James Tam. It introduces Java programming concepts like input, output, branching, and looping. It also discusses the history of Java's development at Sun Microsystems and how it enables programs to run on different platforms. Finally, it provides an overview of compiling and running a simple Java program from the command line.
The document appears to be a scanned copy of a legal contract for the sale of a residential property located in California. The summary outlines details of the purchase including the buyers and sellers involved in the transaction, purchase price of $1.2 million, and schedule for closing and transfer of ownership within 30 days of acceptance of the offer.
This document provides guidance on writing a more effective research abstract by making it more discoverable and appealing to a wider audience. It emphasizes targeting not just other researchers in your field, but also people outside your specialty who may find your work interesting. The document encourages writers to consider their primary and secondary audiences, use common terminology for key concepts, and include relevant Medical Subject Headings (MeSH) terms to help abstracts be found more easily online. Resources like PubMed, MeSH databases, and text analysis tools can help optimize abstracts to engage a broader group of readers.
This document discusses different types of client server models. It describes logical layers including the presentation layer, application layer, and data layer. It then defines five common client/server models: distributed presentation, remote presentation, distributed logic, remote data, and distributed data. Each model divides responsibilities between the client and server differently. For example, remote presentation puts the presentation manager on the client and the application and data layers on the server.
Introduction to datastructure and algorithmPratik Mota
Introduction to data structure and algorithm
-Basics of Data Structure and Algorithm
-Practical Examples of where Data Structure Algorithms is used
-Asymptotic Notations [ O(n), o(n), θ(n), Ω(n), ω(n) ]
-Calculation of Time and Space Complexity
-GNU gprof basic
This document provides an introduction to data structures and algorithms. It discusses key concepts like variables, data types, data structures, abstract data types, algorithms, and analysis of algorithms. The goal of algorithm analysis is to compare algorithms in terms of their running time and space usage. Commonly used rates of growth for analyzing running time include constant, logarithmic, linear, quadratic, and exponential time. Algorithm analysis helps determine which solutions are most efficient.
This document provides information about a data structures course taught using Java in 2015. It was prepared by Mahmoud Rafeek Al-farra and includes sections on course contents, description and guidelines, the lecturer, course outline, resources, assessment, important dates, activities, and tips for being successful. The lecturer is Mahmoud Rafeek Alfarra who has an MSc in computer science and is currently a lecturer and the head of the Admission and Registration Department at UCST.
Introduction to Data structure & Algorithms - Sethuonline.com | Sathyabama Un...sethuraman R
The document discusses data structures and algorithms. It provides an overview of binary trees, binary search trees, and their traversals. It then discusses graphs and poses questions related to binary trees, binary search tree traversals, and graphs.
Ebook En Sams Data Structures & Algorithms In JavaAldo Quelopana
This document summarizes the book "Data Structures & Algorithms in Java" by Robert Lafore. The book introduces data manipulation in Java through practical examples. It provides a gentle introduction to data structures and algorithms for programmers familiar with Java or C++. Examples in the book use Java to illustrate common data structures and algorithms in an accessible way.
The document discusses clients and servers, middleware, and different types of client-server architectures. It provides definitions and examples of clients, servers, middleware, fat clients, fat servers, 2-tier architectures, and 3-tier architectures. It also compares characteristics and advantages of 2-tier vs 3-tier architectures.
This document introduces key concepts in data structures and algorithms. It defines an algorithm as a set of instructions to accomplish a task, and discusses how algorithms are evaluated based on their time and space complexity. It then defines data structures as organized data with relationships and permitted operations, and lists common examples like arrays, stacks and queues. The document also introduces abstract data types as mathematical models with defined operations.
This document provides an overview of enterprise application integration (EAI), including definitions, objectives, components, advantages, and examples. EAI involves integrating independently developed applications that may use different technologies. It has become a priority for many companies and is expected to be a $50 billion market by 2001. Key components of EAI solutions include business rule/logic modules, data acquisition interfaces/adapters, development tools, message brokers, and system control/management tools. Examples demonstrate how EAI can integrate e-commerce sites with legacy systems to share order and customer data.
Pro Floors provides complete carpet flooring solutions for residential and commercial properties in Houston, TX. The store showcases a wide variety of carpets from some of the leading names including Shaw carpet, Mohawk carpet, Southwind carpet, BPI carpet, Armstrong carpet and many more. For details about the carpet store, visit - www.profloorstx.com
This document contains the resume of Nibin William for the role of IT System & Network Support Admin. It outlines his objective of being part of a near-zero downtime IT support team. It details his education qualifications which include various IT certifications. It provides over 8 years of experience in IT industry supporting various organizations in UAE and India with tasks like installing and configuring servers, networking equipment, software and providing troubleshooting support.
Ashley Granby has over 10 years of experience in healthcare, communications, and education. She has a Bachelor's degree in Psychology and some coursework towards an Associate's degree in Nursing. She has held positions in customer service, medical coding, healthcare reimbursement, line dance instruction, and preschool teaching. Her current role is a Sales/Traffic Assistant at a television news station where she performs various administrative, client relations, and event planning duties.
Pro Floors is a carpet flooring store in Houston, TX that offers a wide range of carpet options in different designs and materials. The store promotes the benefits of carpet such as providing comfort, beauty and style, improving air quality, preventing slips and falls, reducing noise, and being easy to maintain. Pro Floors also offers affordable prices, best-in-class services, accurate installation, quality products, reliability, and an extensive variety.
March 2015: Top 10 Things to Know About DC Techdctmeetup
The document provides a summary of tech news and events from March 2015 in Washington D.C., including Mayor Bowser attending SXSW, ArmorText raising $2 million in capital, Steven Overly taking on a new reporting beat, the opening of a new tech accelerator called GP Tech Labs, White House Demo Day, several acquisitions and mergers, discussions around net neutrality, the launch of Howard University's first tech innovation hub, DC FemTech's first annual awards, and LivingSocial hiring an eBay executive. It also lists resources for the DC tech community.
This short document promotes creating presentations using Haiku Deck, a tool for making slideshows. It encourages the reader to get started making their own Haiku Deck presentation and sharing it on SlideShare. In a single sentence, it pitches the idea of using Haiku Deck to easily create and share slideshow presentations online.
The document discusses key concepts in object-oriented programming in Java including classes, objects, methods, constructors, and inheritance. Specifically, it explains that in Java, classes define the structure and behavior of objects through fields and methods. Objects are instances of classes that allocate memory at runtime. Methods define the behaviors of objects, and constructors initialize objects during instantiation. Inheritance allows classes to extend the functionality of other classes.
Classes, objects, methods, constructors, this keyword in javaTharuniDiddekunta
The document discusses classes, objects, methods, constructors and the this keyword in Java. It defines that a class is a blueprint for objects and contains variables and methods, while an object is an instance of a class with state and behavior. It provides examples of creating a class with data members and methods, and then creating objects of that class. The document also covers access modifiers, different types of constructors like default, parameterized and overloaded constructors. It explains the differences between methods and constructors.
The document provides information about object-oriented programming concepts in Java including objects, classes, constructors, and access modifiers. It defines an object as having state, behavior, and identity. A class is described as a template or blueprint for creating objects that share common properties. The document discusses default and parameterized constructors. It also covers the static keyword in relation to variables, methods, blocks, and nested classes. Other topics include finalizer methods, import statements, and the four levels of access control in Java.
The document discusses object-oriented programming concepts like classes, objects, member functions, data members, constructors, and encapsulation. It explains that a class defines the structure and behavior of objects, with data members representing attributes and member functions representing behaviors. Constructors initialize an object's data when it is created. Encapsulation protects data by making it private and only accessible through public member functions.
Class is a blueprint for creating objects that share common attributes and behaviors. A class defines the data and methods that describe the object. Classes in Java can contain data members, methods, constructors, nested classes, and interfaces. Objects are instances of classes that occupy memory at runtime and can access class members like variables and methods. Constructors initialize an object when it is created and have the same name as the class. The this keyword refers to the current object in a method or constructor. Command line arguments can be passed to a program as strings and accessed via the args parameter in the main method.
This document provides an overview of object-oriented programming (OOP) concepts in Java, including classes, objects, inheritance, encapsulation, polymorphism, and dynamic binding. It explains the basic structure of a Java class, how to define methods and variables, and how to instantiate objects from classes. The document also discusses constructors and how to use inheritance to extend existing classes.
This document provides an introduction to object-oriented programming concepts in Java including objects, classes, inheritance, polymorphism, and more. It defines key terms like class, object, state, behavior, identity. It also discusses the differences between objects and classes and provides examples of declaring classes and creating objects in Java. Methods, constructors, and initialization of objects are explained. Inheritance, method overriding, and polymorphism are defined along with examples.
This class is abstract but it does not provide implementation of abstract method print(). An abstract class must be subclassed and the abstract methods must be implemented in the subclass. We cannot create an object of an abstract class directly, it has to be through its concrete subclass.
The document provides an overview of lecture 03 on objects and classes in Java, including reviewing basic concepts, declaring and using classes, implementing inheritance, and discussing abstract classes and interfaces. It also includes examples of declaring classes, using constructors and methods, and implementing inheritance and polymorphism. The lecture aims to help students understand object-oriented concepts in Java like classes, objects, inheritance and polymorphism.
The document discusses key concepts in object-oriented software engineering including objects, classes, encapsulation, inheritance, polymorphism, and abstraction. It provides examples and definitions for each concept to illustrate how they are applied in object-oriented programming.
This document discusses object-oriented programming concepts including objects, classes, inheritance, polymorphism, abstraction, and encapsulation. It provides examples of how each concept is implemented in Java, including code snippets demonstrating classes, inheritance between classes, method overloading and overriding, and abstract classes. The key advantages of OOP such as code reusability and modularity are also summarized.
Inheritance allows classes to establish a hierarchical "is-a" relationship where subclasses inherit and extend the functionality of superclasses. A subclass inherits all fields and methods from its direct superclass and inherits from all superclasses up the class hierarchy with Object at the top. Constructors must call superclass constructors to initialize inherited fields properly. Subclasses can override methods of superclasses to provide specialized implementations while preserving the original signature. Polymorphism occurs when subclass objects are referenced by superclass references and the method invoked is based on the object's actual type. Final methods and classes prevent overriding and extension respectively.
This presentation was provided by Jennifer Gibson of Dryad, during the first session of our 2025 NISO training series "Secrets to Changing Behavior in Scholarly Communications." Session One was held June 5, 2025.
THE QUIZ CLUB OF PSGCAS BRINGS T0 YOU A FUN-FILLED, SEAT EDGE BUSINESS QUIZ
DIVE INTO THE PRELIMS OF BIZCOM 2024
QM: GOWTHAM S
BCom (2022-25)
THE QUIZ CLUB OF PSGCAS
Different pricelists for different shops in odoo Point of Sale in Odoo 17Celine George
Price lists are a useful tool for managing the costs of your goods and services. This can assist you in working with other businesses effectively and maximizing your revenues. Additionally, you can provide your customers discounts by using price lists.
Parenting Teens: Supporting Trust, resilience and independencePooky Knightsmith
For more information about my speaking and training work, visit: https://www.pookyknightsmith.com/speaking/
SESSION OVERVIEW:
Parenting Teens: Supporting Trust, Resilience & Independence
The teenage years bring new challenges—for teens and for you. In this practical session, we’ll explore how to support your teen through emotional ups and downs, growing independence, and the pressures of school and social life.
You’ll gain insights into the teenage brain and why boundary-pushing is part of healthy development, along with tools to keep communication open, build trust, and support emotional resilience. Expect honest ideas, relatable examples, and space to connect with other parents.
By the end of this session, you will:
• Understand how teenage brain development affects behaviour and emotions
• Learn ways to keep communication open and supportive
• Explore tools to help your teen manage stress and bounce back from setbacks
• Reflect on how to encourage independence while staying connected
• Discover simple strategies to support emotional wellbeing
• Share experiences and ideas with other parents
Rose Cultivation Practices by Kushal Lamichhane.pdfkushallamichhame
This includes the overall cultivation practices of Rose prepared by:
Kushal Lamichhane (AKL)
Instructor
Shree Gandhi Adarsha Secondary School
Kageshowri Manohara-09, Kathmandu, Nepal
HOW YOU DOIN'?
Cool, cool, cool...
Because that's what she said after THE QUIZ CLUB OF PSGCAS' TV SHOW quiz.
Grab your popcorn and be seated.
QM: THARUN S A
BCom Accounting and Finance (2023-26)
THE QUIZ CLUB OF PSGCAS.
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecdrazelitouali
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
How to Configure Vendor Management in Lunch App of Odoo 18Celine George
The Vendor management in the Lunch app of Odoo 18 is the central hub for managing all aspects of the restaurants or caterers that provide food for your employees.
This presentation has been made keeping in mind the students of undergraduate and postgraduate level. To keep the facts in a natural form and to display the material in more detail, the help of various books, websites and online medium has been taken. Whatever medium the material or facts have been taken from, an attempt has been made by the presenter to give their reference at the end.
In the seventh century, the rule of Sindh state was in the hands of Rai dynasty. We know the names of five kings of this dynasty- Rai Divji, Rai Singhras, Rai Sahasi, Rai Sihras II and Rai Sahasi II. During the time of Rai Sihras II, Nimruz of Persia attacked Sindh and killed him. After the return of the Persians, Rai Sahasi II became the king. After killing him, one of his Brahmin ministers named Chach took over the throne. He married the widow of Rai Sahasi and became the ruler of entire Sindh by suppressing the rebellions of the governors.
Adam Grant: Transforming Work Culture Through Organizational PsychologyPrachi Shah
This presentation explores the groundbreaking work of Adam Grant, renowned organizational psychologist and bestselling author. It highlights his key theories on giving, motivation, leadership, and workplace dynamics that have revolutionized how organizations think about productivity, collaboration, and employee well-being. Ideal for students, HR professionals, and leadership enthusiasts, this deck includes insights from his major works like Give and Take, Originals, and Think Again, along with interactive elements for enhanced engagement.
How to Create an Event in Odoo 18 - Odoo 18 SlidesCeline George
Creating an event in Odoo 18 is a straightforward process that allows you to manage various aspects of your event efficiently.
Odoo 18 Events Module is a powerful tool for organizing and managing events of all sizes, from conferences and workshops to webinars and meetups.
How to Manage Maintenance Request in Odoo 18Celine George
Efficient maintenance management is crucial for keeping equipment and work centers running smoothly in any business. Odoo 18 provides a Maintenance module that helps track, schedule, and manage maintenance requests efficiently.
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptxArshad Shaikh
Diptera, commonly known as flies, is a large and diverse order of insects that includes mosquitoes, midges, gnats, and horseflies. Characterized by a single pair of wings (hindwings are modified into balancing organs called halteres), Diptera are found in almost every environment and play important roles in ecosystems as pollinators, decomposers, and food sources. Some species, however, are significant pests and disease vectors, transmitting diseases like malaria, dengue, and Zika virus.
Analysis of Quantitative Data Parametric and non-parametric tests.pptxShrutidhara2
This presentation covers the following points--
Parametric Tests
• Testing the Significance of the Difference between Means
• Analysis of Variance (ANOVA) - One way and Two way
• Analysis of Co-variance (One-way)
Non-Parametric Tests:
• Chi-Square test
• Sign test
• Median test
• Sum of Rank test
• Mann-Whitney U-test
Moreover, it includes a comparison of parametric and non-parametric tests, a comparison of one-way ANOVA, two-way ANOVA, and one-way ANCOVA.
Analysis of Quantitative Data Parametric and non-parametric tests.pptxShrutidhara2
Object Oriented Programming using JAVA Notes
1. Prof. Uzair Salman Object Oriented Programming Using JAVA
Superior Group of Collage Jauharabad 1 | P a g e
Object Oriented Programming Using JAVA
Handouts
Table of Contents
Object & Classes......................................................................................................................................2
Constructor .............................................................................................................................................3
Abstraction..............................................................................................................................................3
Encapsulation..........................................................................................................................................4
Inheritance..............................................................................................................................................5
HAS-A Relationship: ............................................................................................................................6
Single Inheritance....................................................................................................................6
Multiple Inheritance................................................................................................................7
Multilevel Inheritance .............................................................................................................7
Hierarchical Inheritance ..........................................................................................................8
Hybrid inheritance...................................................................................................................8
Up-casting & Down-casting.................................................................................................................9
Up-casting: ......................................................................................................................................9
Down-casting: .................................................................................................................................9
Interfaces ..............................................................................................................................................10
Wrapper Classes, Boxing & Unboxing, Packages..................................................................................11
Wrapper Classes........................................................................................................................11
Boxing & Unboxing....................................................................................................................12
Packages....................................................................................................................................12
Exceptions.............................................................................................................................................12
Input/Output Streaming .......................................................................................................................13
Reading Text File .......................................................................................................................14
Writing to Text File....................................................................................................................15
Java Collection ......................................................................................................................................16
For-each loop........................................................................................................................................17
Some important Programs....................................................................................................................17
2. Prof. Uzair Salman Object Oriented Programming Using JAVA
Superior Group of Collage Jauharabad 2 | P a g e
Object & Classes
A class is a blueprint or template or set of instructions to build a specific type of
object. Every object is built from a class. Each class should be designed and
programmed to accomplish some tasks.
The term ‘object’, however, refers to an actual instance of a class. Every object
must belong to a class. Objects are created and eventually destroyed – so they
only live in the program for a limited time.
Or
Object - Objects have states and behaviors. Example: A CAR has states - color,
model, speed as well as behaviors –accelerate, break. An object is an instance
of a class.
Class - A class can be defined as a template/blue print that describes the
behaviors/states that object of its type support.
Following Example illustrate class and object declaration:
public class student {
String name; //Data Members
int age; //Data Members
public void setData(String n, int a) //Member Functions
{
name = n;
age = a;
}
public void getData() //Member Functions
{
System.out.println("Name s :"+name);
System.out.println("age is :"+age);
}
public static void main (String[] arrgs) // Main function
{
student obj=new student(); // Object Creation
obj.setData("abc", 10); // Method Calling using object
obj.getData(); // Method Calling using object
}
}
3. Prof. Uzair Salman Object Oriented Programming Using JAVA
Superior Group of Collage Jauharabad 3 | P a g e
Constructor
Constructor is a function in any class that is used to initialize data variables.
Every class has a constructor. If we do not explicitly write a constructor for a
class the Java compiler builds a default constructor for that class. Each time a
new object is created, at least one constructor will be invoked. The main rule of
constructors is that they should have the same name as the class and have no
return type. A class can have more than one constructor.
Example:
Abstraction
Abstraction is a process of hiding the implementation details from the user, only
the functionality will be provided to the user. An abstract class is one that cannot
be instantiated. All their functionality of the class still exists, and its fields,
methods, and constructors are all accessed in the same manner. You just cannot
create an instance of the abstract class. In Java Abstraction is achieved using
Abstract classes, and Interfaces.
Example:
public class student {
String name;
int age;
public student() //constructor
{
name="abc";
age=0;
}
public void show()
{
System.out.println("Name s :"+name);
System.out.println("age is :"+age);
}
public static void main (String[] arrgs)
{
student obj=new student();// constructor automatically calls
obj.show();
}
}
4. Prof. Uzair Salman Object Oriented Programming Using JAVA
Superior Group of Collage Jauharabad 4 | P a g e
Encapsulation
Encapsulation in Java is a mechanism of wrapping the data (variables) and code
acting on the data (methods) together as single unit. In encapsulation the
variables of a class will be hidden from other classes, No outside class can access
private data member (variable) of other class. However if we setup public getter
and setter methods to update and read the private data fields then the outside
class can access those private data fields via public methods. This way data can
only be accessed by public methods thus making the private fields and their
implementation hidden for outside classes. That’s why encapsulation is known
as data hiding.
Example:
public abstract class student { // making class abstract using abstract keyword
String name;
int age;
public void setData(String n, int a)
{
name= n;
age= a;
}
public void getData()
{
System.out.println("Name s :"+name);
System.out.println("age is :"+age);
}
public static void main (String[] arrgs)
{
student obj=new student(); /* Following is not allowed and raise error */
obj.show();
}
}
5. Prof. Uzair Salman Object Oriented Programming Using JAVA
Superior Group of Collage Jauharabad 5 | P a g e
Inheritance
Inheritance can be defined as the process where one class acquires the
properties (methods and fields) of another. With the use of inheritance the
information is made manageable in a hierarchical order. In other words, the
derived class inherits the states and behaviors from the base class. The derived
class is also called subclass and the base class is also known as super-class. The
derived class can add its own additional variables and methods. These additional
variable and methods differentiates the derived class from the base class.
When we talk about inheritance, the most commonly used keyword would be
extends and implements. The superclass and subclass have “is-a” relationship
between them.
IS-A Relationship:
IS-A is a way of saying: This object is a type of that object. Let us see how the
extends keyword is used to achieve inheritance.
public class student {
private String name; //Private Data Members
private int age; //private Data Members
public student() //constructor
{
name="abc";
age=0;
}
public void setData(String n, int a) //Member Functions
{
name = n;
age = a;
}
public void getData() //Member Functions
{
System.out.println("Name s :"+name);
System.out.println("age is :"+age);
}
public static void main (String[] arrgs) // Main function
{
student obj=new student(); // Object Declaration
obj.setData("abc", 10); // Method Calling using object
obj.getData(); // Method Calling using object
}
6. Prof. Uzair Salman Object Oriented Programming Using JAVA
Superior Group of Collage Jauharabad 6 | P a g e
Now, if we consider the IS-A relationship, we can say:
Mammal IS-A Animal
Reptile IS-A Animal
Dog IS-A Mammal
Hence: Dog IS-A Animal as well
HAS-A Relationship:
Composition (HAS-A) simply mean use of instance variables that are references
to other objects. For example: Honda has Engine, or House has Bathroom.
Types of inheritance in Java:
Below are various types of inheritance in Java.
Single Inheritance
Single inheritance is damn easy to understand. When a class extends
another one class only then we call it a single inheritance. The below flow
diagram shows that class B extends only one class which is A. Here A is a
parent class of B and B would be a child class of A.
public class Animal{
}
public class Mammal extends Animal{
}
public class Reptile extends Animal{
}
public class Dog extends Mammal{
}
CAR
Engine
IS-A
HAS-AHonda
7. Prof. Uzair Salman Object Oriented Programming Using JAVA
Superior Group of Collage Jauharabad 7 | P a g e
Example:
Multiple Inheritance
Multiple Inheritance” refers to the concept of one class extending (Or
inherits) more than one base class. Multiple Inheritance is very rarely used
in software projects. Using multiple inheritance often leads to problems
in the hierarchy. Most of the new OOP languages like Small Talk, Java, C#
do not support Multiple inheritance. Multiple Inheritance is supported in
C++.
Multilevel Inheritance
Multilevel inheritance refers to a mechanism in OOP where one can inherit
from a derived class, thereby making this derived class the base class for the
new class. As you can see in below flow diagram C is subclass or child class of
B and B is a child class of A.
Example:
public class A
{
public void methodA()
{
System.out.println("Base class method");
}
}
public class B extends A
{
public void methodB()
{
System.out.println("Child class method");
}
public static void main(String args[])
{
B obj = new B();
obj.methodA(); //calling super class method
obj.methodB(); //calling local method
}
}
8. Prof. Uzair Salman Object Oriented Programming Using JAVA
Superior Group of Collage Jauharabad 8 | P a g e
Hierarchical Inheritance
In such kind of inheritance one class is inherited by many sub classes. In
below example class B,C and D inherits the same class A.
Hybrid inheritance
Hybrid inheritance is a combination of Single and Multiple inheritance. A
hybrid inheritance can be achieved in the java in a same way as
multiple inheritance can be!! Using interfaces. By using interfaces you can
have multiple as well as hybrid inheritance in Java.
class A
{
public void methodA()
{
System.out.println("Class A method");
}
}
class B extends A
{
public void methodB()
{
System.out.println("class B method");
}
}
class C extends B
{
public void methodC()
{
System.out.println("class C method");
}
public static void main(String arrgs[])
{
C obj = new C();
obj.methodA(); //calling grand parent class method
obj.methodB(); //calling parent class method
obj.methodC(); //calling local method
}
}
9. Prof. Uzair Salman Object Oriented Programming Using JAVA
Superior Group of Collage Jauharabad 9 | P a g e
Up-casting & Down-casting
Casting in java means converting from type to type. When it comes to the talking
about up-casting and down-casting concepts we are talking about converting
the objects references types between the child type classes and parent type
class. Suppose that we have three classes (A, B, C). Class B inherit from class A.
Class C inherit from class B. As follows
Up-casting:
The up casting is casting from the child class to base class. The up casting in java
is implicit which means that you don't have to put the braces (type) as an
indication for casting. Below is an example of up casting where we create a new
instance from class C and pass it to a reference of type A. Then we call the
function display.
Down-casting:
The up casting is casting from the base class to child class. The down-casting in
java is explicit which means that you have to put the braces (type) as an
indication for casting. Below is an example of down-casting
class A
{
void display(){}
}
class B implements A
{
public void display() {
System.out.println("Am in class B");
}
}
class C extends B
{
public void display() {
System.out.println("Am in class C");
}
}
public static void main (String[] arrgs) // Main function
{
A obj=new C(); // up-casting from subclass to super class
obj.display(); // Method Calling of class C
}
10. Prof. Uzair Salman Object Oriented Programming Using JAVA
Superior Group of Collage Jauharabad 10 | P a g e
Interfaces
Interface looks like class but it is not a class. An interface can have methods and
variables just like the class but the methods declared in interface are by default
abstract (only method signature, no body). Also, the variables declared in an
interface are public, static & final by default. We cannot instantiate an interface.
Also an interface does not have any constructor.
Since methods in interfaces are abstract and do not have body, they have to be
implemented by the class before you can access them. The class that
implements interface must implement all the methods of that interface. Also,
java programming language does not support multiple inheritances, using
interfaces we can achieve this as a class can implement more than one
interfaces.
Key Points:
We can’t instantiate an interface in java.
Interface provides complete abstraction as none of its methods can have
body.
Implements keyword is used by classes to implement an interface.
Any interface can extend any other interface but cannot implement it.
Class implements interface and interface extends interface.
A class can implements any number of interfaces.
An interface is written in a file with a .java extension, with the name of
the interface matching the name of the file.
The interface keyword is used to declare an interface.
Example:
public static void main (String[] arrgs) // Main function
{
A obj=new C(); // upcasting from subclass to
super class
obj.display(); // Method Calling of class C
B objB=(B) obj; //Downcasting of reference to
subclass reference
objB.display(); //method calling of class C
}
11. Prof. Uzair Salman Object Oriented Programming Using JAVA
Superior Group of Collage Jauharabad 11 | P a g e
Wrapper Classes, Boxing & Unboxing, Packages
Wrapper Classes
Each of Java's eight primitive data types (int, byte, shot, long, float, double,
Boolean, char) has a class dedicated to it. These are known as wrapper classes,
because they "wrap" the primitive data type into an object of that class. So there
is an Integer class that holds an int variable, there is a Double class that holds a
double variable, and so on. The wrapper classes are part of the java.lang
package, which is imported by default into all Java programs.
The following two statements illustrate the difference between a primitive
data type and an object of a wrapper class:
int x = 25;
Integer y = new Integer(33);
interface vehicle
{
/* All of the methods are abstract by default */
public void accelerate();
public void breaking();
}
class CAR implements vehicle
{
public void accelerate() {
System.out.println("Car is accelerating");
}
public void breaking() {
System.out.println("Break applied");
}
public static void main(String[] arrgs)
{
CAR obj=new CAR(); //object of Class CAR
obj.accelerate();
obj.breaking();
}
}
12. Prof. Uzair Salman Object Oriented Programming Using JAVA
Superior Group of Collage Jauharabad 12 | P a g e
The first statement declares an int variable named x and initializes it with the
value 25. The second statement instantiates an Integer object. The object is
initialized with the value 33 and a reference to the object is assigned to the
object variable y.
Boxing & Unboxing
o Conversion of a primitive type to the corresponding reference type is
called boxing, such as an int to a java.lang.Integer.
o Conversion of the reference type to the corresponding primitive type is
called unboxing, such as Byte to byte.
Packages
Packages are used in Java in order to prevent naming conflicts, to control
access, to make searching/locating and usage of classes, interfaces,
enumerations and annotations easier, etc. A Package can be defined as a
grouping of related types (classes, interfaces, enumerations and annotations)
providing access protection and name space management.
Some of the existing packages in Java are::
o java.lang - bundles the fundamental classes
o java.io - classes for input , output functions are bundled in this package
Programmers can define their own packages to bundle group of
Classes/interfaces, etc.
Exceptions
An exception (or exceptional event) is a problem that arises during the execution
of a program. When an Exception occurs the normal flow of the program is
disrupted and the program terminates abnormally, therefore these exceptions
are to be handled. An exception can occur for many different reasons, below
given are some scenarios where exception occurs.
o A user has entered invalid data.
o A file that needs to be opened cannot be found.
13. Prof. Uzair Salman Object Oriented Programming Using JAVA
Superior Group of Collage Jauharabad 13 | P a g e
A method catches an exception using a combination of the try and catch
keywords. A try/catch block is placed around the code that might generate an
exception. The syntax for using try/catch looks like the following:
try{
//Do something
}
catch(Exception ex)
{
//Catch exception hare using exception argument ex
}
The code which is prone to exceptions is placed in the try block, when an
exception occurs, that exception occurred is handled by catch block associated
with it.
Example:
public class ExceptionSample {
public static void main (String[] arrgs) // Main function
{
int no1, no2; //Data variables
no1=5; //Contain some value
no2=0; //contain some value
try // Try block
{
System.out.println(no1/no2); //attempt to divide number
by 0
}
catch (Exception ex) // Catch block receive exception
{
/* Display exception message */
System.out.println("Error with defination:
"+ex.getMessage()); }
}
}
Input/Output Streaming
The java.io package contains nearly every class you might ever need to
perform input and output (I/O) in Java. All these streams represent an input
source and an output destination. A stream can represent many different
kinds of sources and destinations, including disk files, devices, other programs,
and memory arrays. Streams support many different kinds of data, including
simple bytes, primitive data types, localized characters, and objects. Some
14. Prof. Uzair Salman Object Oriented Programming Using JAVA
Superior Group of Collage Jauharabad 14 | P a g e
streams simply pass on data; others manipulate and transform the data in
useful ways.
1: Reading information into program using StreamReader
2: Writing information from program using StreamWriter
You can read files using these classes:
• FileReader for text files in your system's default encoding (for example,
files containing Western European characters on a Western European
computer).
• FileInputStream for binary files and text files that contain 'weird'
characters
FileReader (for text files) should usually be wrapped in a BufferedFileReader.
This saves up data so you can deal with it a line at a time or whatever instead of
character by character. If you want to write files, basically all the same stuff
applies, except you'll deal with classes named FileWriter with
BufferedFileWriter for text files, or FileOutputStream for binary files.
Reading Text File
If you want to read an ordinary text file in your system's default encoding, use
FileReader and wrap it in a BufferedReader. In the following program, we read
a file called "myFile.txt" and output the file line by line on the console.
import java.io.*;
15. Prof. Uzair Salman Object Oriented Programming Using JAVA
Superior Group of Collage Jauharabad 15 | P a g e
public class fileHandling {
String textFile;
String line;
public void ReadTextFile(String FileName)
{
textFile = FileName;
try {
FileReader Reader = new FileReader(textFile);
BufferedReader bufferedReader = new BufferedReader(Reader);
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
bufferedReader.close(); // close files.
}
catch(Exception ex) {
System.out.println("Error Reading File");
}
}
public static void main (String[] arrgs)
{
fileHandling obj=new fileHandling();
obj.ReadTextFile("c:MyFile.txt");
}
}
Writing to Text File
To write a text file in Java, use FileWriter instead of FileReader, and
BufferedOutputWriter instead of BufferedOutputReader. Here's an
example program that creates a file called 'temp.txt' and writes some lines
of text to it.
import java.io.*;
public class fileHandling {
String textFile;
public void WriteFile(String File)
{
textFile = File;
try {
FileWriter Writer = new FileWriter(textFile);
BufferedWriter bufferedWriter =new BufferedWriter(Writer);
bufferedWriter.write("Hello there,");
bufferedWriter.newLine();
bufferedWriter.write("We are writing");
bufferedWriter.close(); // Always close files.
}
16. Prof. Uzair Salman Object Oriented Programming Using JAVA
Superior Group of Collage Jauharabad 16 | P a g e
catch(Exception ex) {
System.out.println("Error writing to file");
}
}
public static void main (String[] arrgs)
{
fileHandling obj=new fileHandling();
obj.WriteFile("c:MyFile.txt");
}
}
Java Collection
Collections in java is a framework that provides an architecture to store and
manipulate the group of objects. All the operations that you perform on a
data such as searching, sorting, insertion, manipulation, deletion etc. can be
performed by Java Collections.
Java Collection simply means a single unit of objects. Java Collection
framework provides many interfaces (Set, List, Queue, Deque etc.) and
classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet,
TreeSet etc).
17. Prof. Uzair Salman Object Oriented Programming Using JAVA
Superior Group of Collage Jauharabad 17 | P a g e
For-each loop
Anew way of iteration was introduced in Java 5 and offers a more convenient
way of iterating over arrays and collections. It is an extension to the classic
for loop and it is widely known as “enhanced for” or “for-each”. The main
difference between the classic for loop and the new loop is the fact that it
hides the iteration variable. As a result, usage of the for-each loop leads to a
more readable code with one less variable to consider each time we want to
create a loop thus the possibility of ending up with a logic error is smaller.
We can use it over both arrays and collections.
Example:
public static void main (String[] arrgs)
{
ArrayList arr=new ArrayList();
arr.add("A");
arr.add("B");
arr.add("C");
arr.add("D");
arr.add("E");
//Using foreach over collection
for (Object s : arr) {
System.out.println(s);
}
Some important Programs
Write a program that has three fields hours, minute, second. To initialize
these fields it has constructor getter and setter methods, and a print time
method to display time. Also override toString method in this class.
public class TimeClass{
private int hour;
private int minute;
private int second;
public TimeClass()
{
hour = minute = second = 0;
}
18. Prof. Uzair Salman Object Oriented Programming Using JAVA
Superior Group of Collage Jauharabad 18 | P a g e
public void setter(int h, int m, int s)
{
if ( ( h >= 0 && h < 24 ) && ( m >= 0 && m < 60 ) && ( s >= 0 && s < 60 ) )
{
hour = h;
minute = m;
second = s;
}
}
public int getHour() {
return hour;
}
public int getMinute() {
return minute;
}
public int getSecond() {
return second;
}
public String toString()
{
return String.format( "%d:%02d:%02d %s",
( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 ),
minute, second, ( hour < 12 ? "AM" : "PM" ) );
} // end method toString
public static void main(String[] arrgs)
{
TimeClass obj=new TimeClass();
obj.setter(12, 36, 25); // set time to 12:36:25
System.out.println(obj.toString()); // output: 12:36:25 PM
}
}
Write a java program that has two classes point and circle. Circle class
extends point class. Demonstration up casting by using circle class.
class point
{
public void display() {
System.out.println("method of class point");
}
}
class Circle extends point
{
public void display() {
System.out.println("method of class circle");
}
public static void main (String[] arrgs)
{
19. Prof. Uzair Salman Object Oriented Programming Using JAVA
Superior Group of Collage Jauharabad 19 | P a g e
point obj=new Circle(); // up-casting from subclass to super
class
obj.display(); // Method Calling of class circle
}
}
Use java swing library to create a simple four function arithmetic
calculator
import java.awt.event.*;
import javax.swing.*;
public class LoanCalc extends JFrame{
private JButton btnCalc;
private JTextField number1;
private JTextField number2;
private JTextField op;
private JTextField result;
private JLabel lable1;
private JLabel lable2;
private JLabel lable3;
private JLabel lable4;
LoanCalc()
{
setTitle("Basic Calculator");
setBounds(200,200,400,500);
btnCalc=new JButton("Calculate");
number1=new JTextField();
number2=new JTextField();
op=new JTextField();
result=new JTextField();
lable1=new JLabel("First Number");
lable2=new JLabel("Second Number");
lable3=new JLabel("Operation");
lable4=new JLabel("Result");
setLayout(null);
number1.setBounds(120, 100, 200, 50);
number2.setBounds(120, 150, 200, 50);
op.setBounds(120, 200, 200, 50);
result.setBounds(120, 350, 200, 50);
lable1.setBounds(20,100, 100,50);
lable2.setBounds(20, 150, 100, 50);
lable3.setBounds(20, 200, 100, 50);
lable4.setBounds(20, 350, 100, 50);
20. Prof. Uzair Salman Object Oriented Programming Using JAVA
Superior Group of Collage Jauharabad 20 | P a g e
btnCalc.setBounds(150, 280, 100, 50);
btnCalc.addActionListener(new listner());
btnCalc.setActionCommand("Calculate");
add(number1);
add(number2);
add(op);
add(result);
add(btnCalc);
add(lable1);
add(lable2);
add(lable3);
add(lable4);
}
public class listner implements ActionListener
{
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String btn=e.getActionCommand();
int no1,no2, ans=0;
String opration;
if(btn=="Calculate")
{
no1= Integer.parseInt(number1.getText());
no2= Integer.parseInt(number1.getText());
opration= op.getText();
switch (opration) {
case "+":
ans=no1+no2;
break;
case "-":
ans=no1-no2;
break;
case "*":
ans=no1*no2;
break;
case "/":
if(no2>0)
ans=no1/no2;
else
ans=0;
break;
default:
ans=0;
21. Prof. Uzair Salman Object Oriented Programming Using JAVA
Superior Group of Collage Jauharabad 21 | P a g e
break;
}
result.setText(Integer.toString(ans));
}
}
}
}