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 class and object-oriented programming (OOP) concepts in C++. It explains that OOP uses classes and objects, and defines key characteristics like abstraction, encapsulation, inheritance, and polymorphism. A class is a blueprint that defines variables and functions, while an object is an instance of a class in memory. The document provides examples of defining a class with private and public members, as well as creating and accessing objects. It also describes access specifiers like private, public, and protected that control member accessibility.
This document discusses classes and objects in C++. It defines a class as a user-defined data type that implements an abstract object by combining data members and member functions. Data members are called data fields and member functions are called methods. An abstract data type separates logical properties from implementation details and supports data abstraction, encapsulation, and hiding. Common examples of abstract data types include Boolean, integer, array, stack, queue, and tree structures. The document goes on to describe class definitions, access specifiers, static members, and how to define and access class members and methods.
This document discusses classes and objects in Java, including:
- Classes should implement object models and reflect real-world objects.
- Constructors prepare objects for use and finalizers perform cleanup before objects are discarded.
- Reference objects and the garbage collector determine how reachable objects are.
- Cloning objects allows copying but a deep copy duplicates contained objects.
- The Reflection API supports introspection to access class information at runtime.
- Nested and inner classes can be defined inside other classes.
Classes are user-defined data types that contain data members and member functions. Data members are variables inside the class and member functions are functions inside the class. Classes define common characteristics and behaviors for objects instantiated from the class. Objects are instances of a class that hold the class's data members and allow member functions to work on the object's data. Constructors initialize objects and destructors release the memory of objects when they go out of scope.
This document provides an overview of classes and objects in C++. It defines object-oriented programming as encapsulating data and functions into packages called classes. A class defines both data members (attributes) and member functions (behavior). Class members can be declared as private or public, with private only accessible within the class and public accessible outside. The document also discusses creating objects from classes, constructors, destructors, and accessing class members. Examples are provided of defining a Circle class to represent geometric circles and a Time class to represent time values.
This document discusses object-oriented programming concepts in Java including objects, classes, constructors, inheritance, polymorphism, and access modifiers.
The key points are:
1) An object represents an entity with a unique identity, state, and behaviors. A class defines common properties and behaviors of objects.
2) Constructors initialize new objects, while methods define object behaviors. Inheritance allows subclasses to inherit properties and behaviors from parent classes.
3) Access modifiers like public, private, and protected control the visibility and accessibility of classes, variables, and methods. Final and abstract modifiers are also used to restrict or require subclassing.
OOPS Concepts, Java Evolution, Class Object basic, Class Object Constructor overloading, Inheritance, Array and String, Final Abstract class and interfaces, Exceptions, Streams, GUI Applications, Applet Programming, Network Programming and Java Sockets, Multi Threading
Classes in C++ allow developers to combine data and functions that operate on that data into logical units called objects. A class defines the form and behavior of objects, while objects are individual instances of a class. Some key points:
- Classes contain data fields called data members and functions called member functions.
- Objects are instantiated from classes and allocate memory to store values for an instance.
- Access specifiers like public, private, and protected determine which parts of a class are accessible from outside the class.
- Classes can contain static members that are shared across all objects of the class rather than being unique to each object.
Object-oriented programming groups related data and functions into packages called classes. Classes define the type of an object, and objects are instantiated from classes. There are three access specifiers in C++ that control access to class members: public, private, and protected. Member functions are usually declared as public to access the privately declared data members. Classes allow data encapsulation which hides implementation details and only exposes interfaces.
This document discusses Java packages and access control. It defines packages as namespaces that group related classes, and describes how to declare packages and import other packages. It then covers the four access modifiers in Java (public, protected, no modifier, private) and their effects on class, package, subclass and other package access. Code examples are provided to demonstrate how to define packages and use different access modifiers to control visibility and accessibility of classes, variables and methods in Java.
The document provides an overview of key Java concepts including classes, objects, methods, constructors, inheritance, polymorphism, abstraction, and encapsulation. It defines classes like Circle and Shape that demonstrate these concepts. Circles have fields like radius and methods like area() and circumference(). The Shape class is abstract with abstract area() and circumference() methods that concrete subclasses like Circle must implement. Access modifiers like public, private, and protected are used to control access to class members.
The document discusses access modifiers in Java. There are four access modifiers: public, private, protected, and default. Public members are accessible everywhere, private only within the class, protected within subclasses and the package, and default only within the package. The document demonstrates how to use access modifiers with attributes and methods, including using getter and setter methods to access private attributes from other classes.
This slide is based on Object Oriented Programming Language. Here is some details about object and class. You can easily understand about object and class.
This document discusses classes, objects, and methods in Java. It defines a class as a user-defined data type that contains fields and methods. Objects are instances of classes that allocate memory at runtime. Methods define behaviors for objects and are declared within classes. The document covers defining classes, creating objects, accessing members, constructors, method overloading and overriding, static members, passing objects as parameters, recursion, and visibility control.
The document discusses classes and objects in .NET. It defines classes as templates that define an object's properties and behaviors. Objects are instances of classes that have state defined by their property values. The document provides examples of declaring classes and objects in C#, and discusses accessing fields, properties, methods, and constructors of classes and objects. It also covers the differences between instance and static members of classes.
Jeevan Jyoti is a voluntary organization established in 2007 in Lucknow, India that works on issues like women and youth empowerment, institutional development, human rights, and livelihoods. It directly benefits over 400 children and 250 women annually through 38 projects on education, healthcare, livelihood and women's empowerment across 2 states. The organization focuses on providing education, healthcare, and empowerment to disadvantaged families and communities through a lifecycle approach. Its vision is to bring a smile to every face, and its mission is to help disadvantaged communities gain access to their rights and entitlements.
El documento describe las cuatro fases finales clave para concluir un curso en línea de manera exitosa: 1) negociación para permitir que los estudiantes completen actividades atrasadas, 2) realimentación para obtener comentarios de los estudiantes, 3) reconocimiento de los esfuerzos y logros de los estudiantes, y 4) despedida para agradecer la participación de todos y recibir comentarios finales.
Las computadoras se clasifican por su tamaño en supercomputadoras, mainframes, minicomputadoras y microcomputadoras, por su forma de procesamiento en analógicas, digitales e híbridas, y por su propósito en específicas para una función determinada y generales para realizar diferentes funciones u operaciones.
Este documento describe diferentes tipos de hadas según la mitología. Explica que las hadas son criaturas etéreas que protegen la naturaleza y forman parte de la imaginación y creencias. Luego detalla varias clases de hadas como las lamias de la mitología vasca, las ninfas de la mitología griega como las náyades de los ríos y las sirenas de los mares con cola de pez, y finalmente menciona a las sílfides de los vientos, las salamandras del fuego y las drinfas de la
MÁSTER UNIVERSITARIO EN INVESTIGACIÓN EN ECONOMÍA DE LA EMPRESA (INTERUNIVERS...Oscar Herrera
Este documento presenta el plan de estudios del Máster Universitario en Investigación en Economía de la Empresa de la Universidad de Burgos para el curso 2011/2012. El máster consta de 60 créditos ECTS distribuidos en asignaturas obligatorias de fundamentos metodológicos y teóricos en el primer semestre, asignaturas optativas de especialidad y el Trabajo Fin de Máster en el segundo semestre. Los estudiantes pueden elegir entre cuatro especialidades.
The document discusses Galina Lalova's background and interests in architecture, urban design, and visualization. It provides an overview of some of her coursework and projects from 2013-2015, including a private villa design, a public building for spiritual experience, and a redesign of a public square in Lund. The document also includes a bachelor thesis examining social interactions and mixed-use environments in the city of Patras, Greece.
The document provides an overview of vector spaces and related linear algebra concepts. It defines vector spaces, subspaces, basis, dimension, and rank. Key points include:
- A vector space is a set that is closed under vector addition and scalar multiplication. It must satisfy certain axioms.
- A subspace is a subset of a vector space that is also a vector space.
- A basis is a minimal set of linearly independent vectors that span the entire vector space. The dimension of a vector space is the number of vectors in its basis.
- The rank of a matrix is the number of linearly independent rows in its row-reduced echelon form. It provides a measure of the matrix's linear
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.
The document discusses key concepts of object-oriented programming (OOP) including objects, classes, constructors, encapsulation, inheritance, and polymorphism. It provides examples to illustrate each concept. Objects contain data (states) and behaviors (methods). A class acts as a blueprint to create objects. Constructors initialize objects. Encapsulation hides implementation details and controls access via getters and setters. Inheritance allows classes to acquire properties and behaviors of other classes. Polymorphism allows the same method to process objects differently based on their data type.
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.
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...Sagar Verma
OOPS and its application in Java, Super class AND This Keyword,Java Bean, POJO ,Memory management in Java ,Packages ,Miscellaneous (Var-Args, toString(), Double equals operator(==))
This document discusses objects and classes in Java. It begins by defining what a class is - a template that defines common properties of objects. Everything in a Java program must be encapsulated within a class. A class defines an object's state via fields and behavior via methods. The document then discusses how to define classes by specifying fields, methods, and constructors. It provides examples of creating objects from classes and accessing object members. The document also covers key object-oriented programming concepts like encapsulation and inheritance.
This document discusses defining classes in Java. It covers:
1. How classes are used to define new types and encapsulate data and methods.
2. The basic structure of a class including fields, methods, and constructors.
3. How to define classes, create objects from classes, and access fields and methods of objects.
The document discusses a lecture on object-oriented programming. It covers key topics like classes, objects, fields, methods, constructors, and creating objects from classes. It provides examples of how to define classes with fields, methods, and constructors. It also explains how to compile and run a simple Java program with a main method.
This chapter discusses user-defined classes and abstract data types (ADTs) in Java. It covers defining classes with private, protected, public, and static members. Constructors and finalizers are examined. The toString method is explored. Abstract data types are introduced as data types that specify logical properties without implementation details. An example candy machine problem is presented to demonstrate defining classes for a non-GUI and GUI application to model a candy machine with items for sale, a cash register, dispenser, and other components.
This document discusses Java methods, classes, and key concepts like overloading, parameter passing, recursion, access control, static methods/variables, and nested classes. It provides examples of overloading methods based on parameters, passing objects and primitives as parameters, recursively calculating factorials, using access specifiers like public and private, defining static class members, and creating inner classes. It also covers strings, command line arguments, and common classes like String and StringBuffer.
This document summarizes a lecture on object-oriented programming concepts including classes, methods, constructors, and objects.
The lecture covered:
1) The components of a class including fields, methods, and constructors. Main(), setter, and getter methods were discussed.
2) How to call methods within the same class and between different classes.
3) How to create objects from classes and how messages are sent to objects to invoke their methods.
The document provides information about classes and objects in Java. It discusses what a class is, class naming conventions, members of a class including fields and methods, declaring objects, allocating memory to objects using the new keyword, instance variables, instance methods, and some examples. Specifically:
- A class is a blueprint from which individual objects are created. Class names follow camel casing conventions.
- Members of a class include fields (properties) and methods (behaviors). Fields can be primitives or references, methods define object interactions.
- To declare an object, use the class name and object name (e.g. Person p1). The new keyword allocates memory and returns a reference to the new
This document discusses object oriented programming concepts like classes, objects, encapsulation, and abstraction. It defines classes as blueprints for objects that can contain methods and attributes. Objects are instances of classes that contain the class's methods and properties. Encapsulation is implemented by making fields private and accessing them via public getter and setter methods to protect data. Abstraction exposes only relevant data in a class interface and hides private attributes and methods.
This document provides an overview of object-oriented programming concepts and Java programming. It discusses key OOP concepts like classes, objects, encapsulation, inheritance, and polymorphism. It then covers the history and development of Java, describing how it was initially created at Sun Microsystems in the 1990s to be a platform-independent language for programming consumer electronics. The document outlines some of Java's key features like being simple, secure, portable, robust, and architecture-neutral. It also discusses Java's object-oriented nature and support for multithreading.
1) Variables are used to store and represent data in a program. They have a name, data type, and range of values. Variable names must follow specific identifier rules.
2) Classes define the attributes (data) and behaviors (methods) of objects. An object is an instance of a class. Constructors are special methods that initialize new objects.
3) Constructors allow objects to be created and initialized with specific attribute values. Defining multiple constructors provides flexibility in how objects are instantiated.
This document discusses object-oriented programming principles like encapsulation, inheritance, polymorphism, abstract classes, and interfaces. It provides examples of how each principle is implemented in Java code. Encapsulation involves making fields private and providing public getter and setter methods. Inheritance allows new classes to inherit attributes and behaviors from existing classes in a hierarchy. Polymorphism allows a parent class reference to refer to child class objects. Abstract classes cannot be instantiated while interfaces contain only abstract methods and are implemented by classes.
Object-oriented programming (OOP) involves splitting a program into objects that contain both data and functions. OOP allows developers to define objects, their properties, and relationships. Classes are blueprints that define objects and don't use memory, while objects are instances of classes that hold both data and methods. Key concepts of OOP include inheritance, abstraction, polymorphism, and encapsulation.
1. The document discusses Java concepts like serialization, reflection, JDBC, and distributed applications.
2. Serialization allows saving object state to a file by implementing the Serializable interface. Reflection obtains runtime information about classes.
3. JDBC is used to connect to databases and store data permanently. Distributed applications run across a network and allow for data sharing between clients.
Mule applications accept and process events as messages through connected message processors in a flow. Large messages can be processed in batch jobs which split messages into records. Flows link message processors to handle message receipt, processing, and routing. Batch jobs process records asynchronously outside of flows. Mule receives messages from external sources via connectors and routes them through processors that transform data between applications.
Mule is a lightweight integration platform that enables connecting applications and systems on-premises or in the cloud. It provides out-of-the-box connectors and tools to integrate applications, build and consume APIs, create web services, and enable mobile and B2B integration. The Anypoint Platform offers tools for API development with APIkit and management with API Manager, as well as for SaaS and SOA integration using Studio and connectors. Mule deployment architecture includes on-premises or cloud deployment on CloudHub and supports configuration, routing, and basic stages of message processing.
Mule is an integration platform that allows connecting applications and systems on-premises or in the cloud. It provides out-of-the-box connectors and tools to create APIs and integration applications between SaaS systems. The Anypoint Platform is Mule's complete integration suite, including the Anypoint Studio development environment and Mule ESB runtime. It enables integrating applications via SOA, creating RESTful APIs, and connecting SaaS tools.
Classes provide templates for objects by defining attributes and behaviors. An object is an instance of a class that holds specific state through its attribute values. Classes in C# can contain fields to store data, properties for encapsulated access to fields, methods to implement behaviors, and constructors to initialize objects. Constructors are special methods that are called when an object is instantiated and assign initial field values.
This document provides an overview of object-oriented programming concepts including objects, classes, messages, encapsulation, inheritance, polymorphism, and dynamic binding. It defines objects as bundles of related variables and methods, and classes as blueprints that define common variables and methods for objects of a certain kind. The document also explains how objects communicate through messages and the requirements for a language to be object-oriented, including support for encapsulation, inheritance, and dynamic binding.
This document summarizes key concepts from a lecture on threads. It defines processes and threads, explaining that threads exist within processes and allow for multithreaded execution. It covers thread fundamentals in Java, including creating threads by extending Thread or implementing Runnable, and methods like start(), sleep(), and yield(). The document also discusses synchronizing access to shared resources using monitors, and how wait-notify allows threads to pause and resume execution. Homework includes solving producer-consumer and philosophers problems using these threading concepts.
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.
This document discusses test-driven development and unit testing with JUnit. It covers:
- Writing tests before code using stubs, so code is testable and requirements are clear.
- Key aspects of JUnit like test classes, fixtures, assertions and annotations like @Before, @Test.
- Best practices like testing individual methods, writing simple tests first, and repeating the test-code cycle until all tests pass.
- Features of JUnit in Eclipse like generating test stubs from code and viewing test results.
The overall message is that testing saves significant time versus debugging, helps write better code, and is an essential part of the development process. Tests should cover all requirements and edge cases to
This document outlines the key concepts and objectives covered in Lecture 04 on threads. It introduces processes and threads, defining them as the basic units of execution in operating systems and Java programs respectively. It discusses how multi-processing systems and multi-threading programs allow concurrent execution. The lecture then covers thread fundamentals in Java, including creating and managing threads, and synchronizing access to shared resources using monitors, locks, and wait-notify mechanisms. Students are assigned workshops on the producer-consumer problem and philosophers problem to demonstrate these concurrency concepts.
Social media management system project report.pdfKamal Acharya
The project "Social Media Platform in Object-Oriented Modeling" aims to design
and model a robust and scalable social media platform using object-oriented
modeling principles. In the age of digital communication, social media platforms
have become indispensable for connecting people, sharing content, and fostering
online communities. However, their complex nature requires meticulous planning
and organization.This project addresses the challenge of creating a feature-rich and
user-friendly social media platform by applying key object-oriented modeling
concepts. It entails the identification and definition of essential objects such as
"User," "Post," "Comment," and "Notification," each encapsulating specific
attributes and behaviors. Relationships between these objects, such as friendships,
content interactions, and notifications, are meticulously established.The project
emphasizes encapsulation to maintain data integrity, inheritance for shared behaviors
among objects, and polymorphism for flexible content handling. Use case diagrams
depict user interactions, while sequence diagrams showcase the flow of interactions
during critical scenarios. Class diagrams provide an overarching view of the system's
architecture, including classes, attributes, and methods .By undertaking this project,
we aim to create a modular, maintainable, and user-centric social media platform that
adheres to best practices in object-oriented modeling. Such a platform will offer users
a seamless and secure online social experience while facilitating future enhancements
and adaptability to changing user needs.
OCS Training Institute is pleased to co-operate with
a Global provider of Rig Inspection/Audits,
Commission-ing, Compliance & Acceptance as well as
& Engineering for Offshore Drilling Rigs, to deliver
Drilling Rig Inspec-tion Workshops (RIW) which
teaches the inspection & maintenance procedures
required to ensure equipment integrity. Candidates
learn to implement the relevant standards &
understand industry requirements so that they can
verify the condition of a rig’s equipment & improve
safety, thus reducing the number of accidents and
protecting the asset.
A vernier caliper is a precision instrument used to measure dimensions with high accuracy. It can measure internal and external dimensions, as well as depths.
Here is a detailed description of its parts and how to use it.
Literature Reivew of Student Center DesignPriyankaKarn3
It was back in 2020, during the COVID-19 lockdown Period when we were introduced to an Online learning system and had to carry out our Design studio work. The students of the Institute of Engineering, Purwanchal Campus, Dharan did the literature study and research. The team was of Prakash Roka Magar, Priyanka Karn (me), Riwaz Upreti, Sandip Seth, and Ujjwal Dev from the Department of Architecture. It was just a scratch draft made out of the initial phase of study just after the topic was introduced. It was one of the best teams I had worked with, shared lots of memories, and learned a lot.
Response & Safe AI at Summer School of AI at IIITHIIIT Hyderabad
Talk covering Guardrails , Jailbreak, What is an alignment problem? RLHF, EU AI Act, Machine & Graph unlearning, Bias, Inconsistency, Probing, Interpretability, Bias
How to Manage Internal Notes in Odoo 17 POSCeline George
In this slide, we'll explore how to leverage internal notes within Odoo 17 POS to enhance communication and streamline operations. Internal notes provide a platform for staff to exchange crucial information regarding orders, customers, or specific tasks, all while remaining invisible to the customer. This fosters improved collaboration and ensures everyone on the team is on the same page.
2. Why should we study this lecture?
This lecture will
Help you reviewing basic concepts of the object-
oriented paradigm.
Supply syntax for declaring a Java class. It can
be a normal class, a sub-class, a nested class,
abstract class or an interface.
Supply ways to use Java classes.
2
3. Review
Object: đối tượng, những sự vật, hiện tựợng cụ thể
mà con người sờ có cảm xúc về nó. Thí dụ cái xe
máy Air Blade cụ thể mà ta đang dùng
Class: lớp, là một tập các đối tượng tương tự nhau.
Con người thường dùng các danh từ chung (như xe
gắn máy) để đặt tên gọi cho một class.
Modifiers are Java keywords that give the compiler
information about the nature of code (methods), data,
classes
Access Modifiers: public, protected, private and no-
modifier (default)
Other modifiers: final, abstract, static, native,
transient, synchronized, volatile
3
4. Review
Type conversion = implicit type change
Type casting = explicit type change
Conversion allows widening type change only.
If we want a narrowing type change, we must use
an explicit casting.
Object type conformity:
fatherReferene=sonReference;
4
5. Review
Exceptions: Errors beyond the control of a program. When an
exception occurs, the program will terminate abruptly.
Exception can be caught by the try..catch..finally statement
Assertions enables the programmer to test assumptions about
the program. Assertions are introduced in Java 1.4. From Java
1.5, it is removed.
Ways of writing assertion statements are:
assert expression;
assert expression1:expression2;
Compiling a program having assertion statement:
javac –source 1.4 FileName
Running a program with assertion
java –ea Package.FileClass
java –enableassertions Package.FileClass
5
6. Review
-Knowledge from the subject OOP:
- What are methods and constructors.
- Order of memory allocations, order of executions of
constructors.
6
7. Objectives
Introduction to OO Paradigm
Benefits of OO Implementation
How to declare a class
How to use a class
How to declare a subclass
Your homework: Workshop 2 (with report)
You are requested to complete the case stydy 1 introduced
at the slide 22
Assessment: the next class
7
8. Contents
6.1- Introduction to OO Paradigm
6.2- Benefits of OO Implementation
6.3- Hints for class design
6.4- Declaring/ Using a class
6.5- Case study 1 (Managing a list of persons)
6.6- Inheritance Demonstration
6.7- Variable-length argument list
6.8- Some Tests
6.9- Nested Classes
6.10- Interfaces
6.11- Abstract Classes
6.12- Anonymous Classes
6.13- Enum Types
You are
introduced in
the subject OOP
8
9. 6.1- Introduction to OOP
Procedure-Oriented
Program
data1
data2
Function1 (data1)
Function2 (data1)
Function3
(data2)Function4
(data2)
Class A
{
}
data1
Function1 ()
Function2 ()
Class B
{
}
data2
Function3 ()
Function4()
Modifiers
Modifiers
Object = Data +
Methods
Basic
Concepts
-
Encapsulation
- Inheritance
-
Polymorphis
Particular
methods:
Constructor
s Constructor: a specific method which
is automatically called when an object
is created.
9
10. Introduction to OOP
Why OOP is introduced?
It is a easy way to describe objects in nature.
It supports
Ability to describe relationship between objects especially,
the “is a kind of” relationship The problem is described
easier and better Inheritance
Security in code Modifiers
Ability to maintain code Encapsulation
Polymorphism overloading/overriding methods
…
10
11. 6.2- Benefits of OO Impl.
Encapsulation: Aggregation
of data and behavior.
Data of a class should be
hidden from the outside. The
outside access them by
getters/setters
All behavior should be
accessed only via methods.
A method should have a
boundary condition. The if
statement is commonly used to
ensure that this access is valid
or data of the object are valid
at any time.
class A
{
}
data1
Function1 ()
Function2 ()
Modifiers
Behavior: hành vi, ability of an
object which is identified and given
a name (verb).
Method: Phương thức, cách thức để
làm: Implementation of a behavior.
11
12. Benefits of OO Impl….
Inheritance: Ability allows a class having members of an
existed class Re-used code.
ID_Num
name
yearOfBirth
address
getID_Num()
setID_Num(newID)
......
class PERSON
rollNum
score
getScore()
setSore(newScore)
......
class STUDENT
“is a”
relationshi
p
ID_Num
name
yearOfBirth
address
getID_Num()
setID_Num(newID)
......
class STUDENT
rollNum
score
getScore()
setSore(newScore)
......
inherited
extensions
Son = Father + extensions12
13. Benefits of OO Impl.…
How to implement Inheritance?
Electric Products< code, name, make, price, guaranty, voltage, power>
Ceramic Products < code, name, make, price, type >
Food Products < code, name, make, price , date, expiredDate >
Product
code
name
make
price
ElectricProduct
guaranty
voltage
power
Ceramic
type
Food
date
expiredDate
The father class
is implemented
first then it’s
subclasses
afterwards
intersection
rest
13
14. Benefits of OO Impl.…
Order of object creations:
(1) Memory block containing data inherited
from Father is allocated first.
(2) Memory block containing extension data is
allocated afterward.
GrandFather obj1 = new GrandFather();
Father obj1 = new Father();
Son obj2 = new Son();
Data gf
Data f
obj1: 1000
obj2: 800
obj3: 500
100
0
800
500
Data s
Step 1
Step 2
Data gf
Data f
Data gfStep 1
Step 2
Step 3
14
15. Benefits of OO Impl…
Polymorphism: Ability allows many versions of a method
based on overloading and overriding methods techniques.
15
16. 6.3- Hints for class design
Coupling
Is an object’s reliance on
knowledge of the internals of
another entity’s implementation.
When object A is tightly coupled
to object B, a programmer who
wants to use or modify A is
required to have an inappropriately
extensive expertise in how to use
B.
Head
Eye1
Eye2
High
coupling
( Bad
design)
Head
leftEye
rightEye
Eye
Eye
Low coupling
( Good design)
16
17. Hints for class design
Cohesion is the degree to which a class or method resists
being broken down into smaller pieces.
classA
M()
{
}
Operation 1
Operation 2
Low
cohession
( Bad design)
classA
M1()
{
}
M2()
{
}
M()
{ M1(); M2();
}
Operation 1
Operation 2
High cohesion
( Good design)17
18. 6.4- Declaring/Using a Class
[public] class ClassName [ extends FatherClass] {
[modifier] DataType dataMember [=InitialValue];
[modifier] ClassName [(args)] // constructors
{ super (args); // call to the constructor of FatherClass – first line
<code>
}
[ modifier] ReturnType methodName (args)
{ <code >
super.Method(args); // call to a method of FatherClass
}
}
// Creating an object
ClassName obj= new ClassName (args);
obj.Method(args);
Data of
Object
obj:
12000
12000
Getters
public Type getField()
Setters
public void
setField(arg)
WHY
?
What is the keyword super
used?
18
19. Key Points: Overloading Methods
A method that has an identical name and identical
number, types, and order of arguments.
Overloading methods are implemented in the same
class.
Overloading methods are the same name but their
arguments have differences.
19
20. Key points: Overriding methods
A method that has an identical name and
identical number, types, and order of arguments
as a method in a parent class is an overriding
method.
Each parent class method may be overridden
once at most in any one subclass.
An overriding method must return exactly the
same type as the method it overrides.
20
21. Overriding methods…
An overriding method must not be less
accessible than the method it overrides.
An overriding method must not throw any
checked exception (or subclasses of those
exceptions) that are not declared for the
overridden method.
An overridden method is completely replaced
by the overriding method unless the overridden
method is deliberately (cố ý) invoked from within
the subclass.
21
22. 6.5- Case study 1
To develop a program, steps must be followed:
Analysis
Design
Writing Report
Implement
Test
Goals of this case study is providing a sample
for writing a report including 2 first steps in your
notebook for each problem you are requested
to solve.
22
23. Report
1- Problem
Each person details include code, name, and age.
Write a Java program that allows users adding a new
person to the list, removing a person having a known
code from the list, updating details of a known-code
person, listing all managed persons in descending
order of ages using a simple menu.
23
24. Report…
1- Problem
….
2- Analysis
From the problem description. The following concepts will be
implemented as appropriate classes:
Class Person
Description for a person
Data: String code; String name; int age
Methods:
Constructors
Getters, setters
void input() for collecting data
String toString() to get data in string format
24
25. Report…
Class PersonList
Description for a list of persons
Data:
Person[] list; // current list
int count // current number of persons
Methods:
Constructors
Getters, setters
void add(); // add a new person. Data are collected from keyboard
int find (String aCode); // Find the index of the person whose code is known
void remove()// remove a person. His/ her code is accepted from keyboard
void sort(); // descending sort the list based on their ages
void update(); // update a person, data are accepted from keyboard
void print(); // print the list
25
26. Report…
Class Menu
Description for a menu
Data
String[] hints; // list of hints
int n; // current number of hints
Methods:
Menu(int n): constructor for initializing a menu containing n options
void add (String aHint); // add an option
int getChoice(); // get an option
Class ManagingProgram1
Description for the program
Data: none
Methods:
main(…): main method of the program
26
45. Some Tests
a) A7500
b) 500A7
c) 500
d) None of the
others
Compile-time error
( static code can not
access instance variables)
45
46. Some Tests
a) A1210
b) 10A12
c) 17
d) None of the
others
Compile-time error
( The y variable is out of
scope)
46
47. A summary
- Introduction to OO Paradigm
- Benefits of OO Implementation
- Hints for class design
- Declaring/ Using a class
- Identifying a class:
- Main noun Class
- Descriptive nouns Data/ constants
- Verbs Behaviors Methods
- Implementing a class
- Constructors
- Methods
- Getters, setters
- Methods accepting variable-length argument list
47
48. 6.9- Inner-Nested classes
Class is declared inside some
other class or inside the body of
other class’s method.
2 types of nested class: Static
Nested classes, Inner classes (
non-static)
Static nested class All
objects belong to the outer class
share one nested object(cặp song
sinh dính nhau, phần dính nhau nằm
ở bên ngoài).
Inner class: Each outer object
has it’s own inner object Outer
object must contain an instance
of the inner object then accesses
members of this nested instance
(trái tim nằm bên trong thân
người)
obj1
obj2
Static
nested obj
obj1
Inner
obj
obj2
Inner
obj
48
49. Inner-Nested classes…
A nested class violates the
recommendation “low coupling” in class
design. Why are nested classes used?
It is a way of logically grouping classes that
are only used in one place.
It increases encapsulation.
Nested classes can lead to more readable
and maintainable code.
49
50. Static Nested Classes Demo…
Class-level nested
class.
Because the static
nested object is
stored separately
from enclosing
instances, static
nested object can
be initiated without
enclosing objects.
Methods of static nested class can not
access data of enclosing instance
because it can created even when
enclosing objects do not exist.
50
51. Inner classes demo…
obj
obj: 2000
x = 5
inner:
3000
y = 7
A method of nested
class can access all
members of its
enclosing class
outerObj
x=5
innerObj
y=7
Error: inner obj do
not created yet.
200
0
300
0
51
52. Creating Inner Class instance through
enclosing instance
obj: 1000
x = 5
in1: 2000
y = 1
in2: 3000
z = 2
200
0
300
0
100
0
52
53. Inner Classes
Defined Inside Methods
Local
class
Inner-method
class can not
access normal
local variables
of the
containing
method.
53
54. 6.10- Abstract classes
The result of so-high
generalization.
Use the keyword abstract to
declare an abstract class or
an abstract method.
Abstract method is a
prototype (no body).
An instance of abstract class
can not be created but
concrete objects (all abstract
methods were implemented).
Modified
54
55. Abstract classes…
This class have no abstract method but it is
declared as an abstract class. So, we can not
initiate an object of this class.
55
57. 6.11- Interfaces
Interface: A group of methods prototypes
which will be implemented in a concrete class.
You can not create an instance of an interface.
Access modifier of a method of
an interface can be default but it
must be public in a class
implementing this interface.
Modified
.
57
class A implements Iterafce_1, Interface_2
{ ……………………….}
58. Interfaces…
When is an interface designed? When
methods must be implemented in some classes.
Advantages of interfaces:
A way to make a model (template) for a kind of
applications.
A way for designer controlling implementers.
58
59. 6.12- Anonymous Class
We can initiate concrete objects only (all methods
were implemented and they are not abstract
ones).
Java permits we create directly an object of an
interface or an abstract class if all prototypes and
abstract methods are implemented.
We can not develop a class which implements this
interface or extends the abstract class.
We can not a chance to give a class name to these
code Anonymous class.
When the program is compiled, the class name will
be given by the compiler.
59
61. Anonymous Class…
Anonymous class is a technique is
commonly used to support programmer
when only some methods are overridden
only especially in event programming.
Concrete methods but
they can not be used
because the class is
declared as abstract one.
The abstract class
can be used only
when at least one
of it’s methods is
overridden
61
62. 6.13: Enum Type
It is introduced from Java 1.5.
An enum type is a type whose fields consist of a fixed set
of constants. Common examples include compass
directions (values of NORTH, SOUTH, EAST, and WEST)
and the days of the week. Because they are constants,
the names of an enum type's fields are in uppercase
letters.
Similarities between traditional classes and enums: refer
to the page 198.
Enum type is a group of constants. It is given a name.
Each constant is given a name (name of constant).
62
64. Summary
6.1- Introduction to OO Paradigm
6.2- Benefits of OO Implementation
6.3- Hints for class design
6.4- Declaring/ Using a class
6.5- Case study 1 (Managing a list of persons)
6.6- Inheritance Demonstration
6.7- Variable-length argument list
6.8- Some Tests
6.9- Nested Classes
6.10- Interfaces
6.11- Abstract Classes
6.12- Anonymous Classes
6.13- Enum Types
64