Here are the key differences between overriding and overloading:
- Overriding involves subclass and superclass, while overloading involves only one class.
- Overriding changes the implementation of an existing method in the superclass, while overloading provides multiple implementations of the same method name with different parameters.
- The parameter lists are the same for overriding but different for overloading.
- Overriding is achieved by the subclass, while overloading is achieved by a single class.
So in summary, overriding changes the implementation of a method in the subclass, while overloading provides multiple implementations of the same method name with different parameters within one class.
This document discusses inheritance and polymorphism in Java. It describes using inheritance to define subclasses that extend existing superclasses in order to avoid code redundancy when multiple classes share common properties and behaviors. The key concepts covered include defining subclasses, invoking superclass constructors and methods using the super keyword, overriding methods in subclasses, polymorphism and dynamic binding, and casting between subclasses and superclasses.
This chapter discusses object-oriented programming concepts in Java including immutable objects, scope of variables, the this keyword, class abstraction, composition relationships, and designing classes. It provides examples of how to model real-world entities like loans, BMI calculations, stacks, and dates using object-oriented design principles such as encapsulation, abstraction and separation of concerns. The key benefits of object-oriented programming highlighted are reusability, flexibility and modularity in building software.
This document introduces key concepts of object-oriented programming in Java including classes, objects, encapsulation, and inheritance. It discusses how classes are used to define objects and their properties (data fields) and behaviors (methods). Constructors are introduced as special methods used to initialize objects. The document provides examples of defining classes like Circle and TV, creating objects, and accessing object data and methods. It also discusses reference variables, the null value, default values, and differences between primitive types and reference types. Finally, core classes like Date, Random, and JFrame from the Java library are mentioned.
super.display() calls the display() method defined in the Rectangle superclass. This allows the subclass method to reuse the superclass implementation and then add additional functionality.
This document discusses Chapter 2 of an introduction to Java programming textbook. It covers elementary programming concepts such as writing simple Java programs to perform computations, using variables to store data, numeric data types, operators, and literals. The chapter objectives are to learn how to solve practical problems by working with Java primitive data types, variables, input/output, and other basic programming elements.
1. Inheritance allows one class to acquire properties of another class, supporting hierarchical classification. A subclass inherits attributes from all ancestor classes.
2. There are several types of inheritance including single, multiple, hierarchical, and multilevel. Single inheritance involves one subclass extending one superclass. Hierarchical inheritance involves one superclass and multiple subclasses.
3. Interfaces can be used to achieve multiple inheritance by implementing multiple interfaces. This avoids issues of multiple superclasses having same member names.
Object oriented programming involves modeling real-world entities as objects that encapsulate both data and behavior. Programmers define classes that specify the attributes and methods of these objects. This is a different approach than traditional procedural programming, as it focuses on objects rather than functions.
Object oriented programming involves modeling real-world entities as objects that encapsulate both data and behavior. Programmers define classes that specify the attributes and methods of these objects. This is a different approach than traditional procedural programming, as it focuses on objects rather than functions.
This document discusses inheritance and polymorphism in Java. It describes using inheritance to define subclasses that extend existing superclasses in order to avoid code redundancy when multiple classes share common properties and behaviors. The key concepts covered include defining subclasses, invoking superclass constructors and methods using the super keyword, overriding methods in subclasses, polymorphism and dynamic binding, and casting between subclasses and superclasses.
This chapter discusses object-oriented programming concepts in Java including immutable objects, scope of variables, the this keyword, class abstraction, composition relationships, and designing classes. It provides examples of how to model real-world entities like loans, BMI calculations, stacks, and dates using object-oriented design principles such as encapsulation, abstraction and separation of concerns. The key benefits of object-oriented programming highlighted are reusability, flexibility and modularity in building software.
This document introduces key concepts of object-oriented programming in Java including classes, objects, encapsulation, and inheritance. It discusses how classes are used to define objects and their properties (data fields) and behaviors (methods). Constructors are introduced as special methods used to initialize objects. The document provides examples of defining classes like Circle and TV, creating objects, and accessing object data and methods. It also discusses reference variables, the null value, default values, and differences between primitive types and reference types. Finally, core classes like Date, Random, and JFrame from the Java library are mentioned.
super.display() calls the display() method defined in the Rectangle superclass. This allows the subclass method to reuse the superclass implementation and then add additional functionality.
This document discusses Chapter 2 of an introduction to Java programming textbook. It covers elementary programming concepts such as writing simple Java programs to perform computations, using variables to store data, numeric data types, operators, and literals. The chapter objectives are to learn how to solve practical problems by working with Java primitive data types, variables, input/output, and other basic programming elements.
1. Inheritance allows one class to acquire properties of another class, supporting hierarchical classification. A subclass inherits attributes from all ancestor classes.
2. There are several types of inheritance including single, multiple, hierarchical, and multilevel. Single inheritance involves one subclass extending one superclass. Hierarchical inheritance involves one superclass and multiple subclasses.
3. Interfaces can be used to achieve multiple inheritance by implementing multiple interfaces. This avoids issues of multiple superclasses having same member names.
Object oriented programming involves modeling real-world entities as objects that encapsulate both data and behavior. Programmers define classes that specify the attributes and methods of these objects. This is a different approach than traditional procedural programming, as it focuses on objects rather than functions.
Object oriented programming involves modeling real-world entities as objects that encapsulate both data and behavior. Programmers define classes that specify the attributes and methods of these objects. This is a different approach than traditional procedural programming, as it focuses on objects rather than functions.
The document discusses selection control statements in Java including if, if-else, and switch statements. It provides examples of using boolean expressions and comparison operators to write conditional logic. Key topics covered include one-way if statements, two-way if-else statements, nested if statements, avoiding common errors, and using logical operators to combine conditions. Examples provided demonstrate how to use random numbers and selection statements to create simple math quiz programs.
This document discusses inheritance and polymorphism in Java. It begins by introducing the motivations for inheritance, which is to avoid redundancy when designing classes that share common features, like circles, rectangles, and triangles. It then lists the chapter objectives, which include defining subclasses, invoking superclass constructors and methods, overriding methods, polymorphism, and other inheritance-related concepts. The document provides an example of superclass GeometricObject and subclasses Circle and Rectangle. It also discusses that superclass constructors are not inherited by subclasses but must be invoked explicitly or implicitly using the super keyword.
Inheritance allows classes to inherit properties and methods from existing classes. This allows code reuse and avoids rewriting common functionality. The existing class is called the superclass, while the class inheriting is the subclass. The subclass inherits all non-private fields and methods from the superclass. Inheritance is implemented in Java using the "extends" keyword. The subclass can override methods from the superclass to modify their behavior. All classes in Java implicitly extend the Object class, which defines common methods like equals(), hashCode(), and toString().
Inheritance allows one class to acquire properties of another class. A subclass inherits all properties of its superclass and can add its own unique properties. When a method in a subclass has the same name and signature as a method in its superclass, it overrides that method. Dynamic method dispatch determines which version of an overridden method to call based on the actual object type at runtime rather than the reference variable type. Superclass constructors can be called from subclasses using the super keyword, and super can also be used to access hidden superclass members from subclasses.
This document provides an overview of key concepts in C++ including classes, objects, encapsulation, inheritance, and pointers. It discusses how classes can be used to model real-world entities, hiding implementation details and exposing only necessary functions. Inheritance allows code reuse by deriving specialized classes from general base classes. Pointers store the address of variables in memory and can be used to pass data between functions by reference. The document also provides an example Student class with member variables and functions to set and retrieve student data like GPA.
This document discusses Python modules, classes, inheritance, and properties. Some key points:
- Modules allow the organization of Python code into reusable libraries by saving code in files with a .py extension. Modules can contain functions, variables, and be imported into other code.
- Classes are templates that define the properties and methods common to all objects of a certain kind. The __init__() method initializes new objects. Inheritance allows child classes to inherit properties and methods from parent classes.
- Properties provide a way to control access to class attributes, allowing them to be accessed like attributes while hiding the implementation details behind getter and setter methods.
This document provides a PHP 5 cheat sheet that summarizes key PHP types, functions, and predefined variables. It covers boolean, integer, and string types; arrays; classes; date/time functions; and the $_SERVER and $_FILES predefined variables. For each section, it lists main elements and functions with brief descriptions.
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAMaulik Borsaniya
Classes and Object-oriented Programming:
Classes: Creating a Class, The Self Variable, Constructor, Types of Variables, Namespaces, Types of Methods (Instance Methods, Class Methods, Static Methods), Passing Members of One Class to Another Class, Inner Classes
Inheritance and Polymorphism: Constructors in Inheritance, Overriding Super Class Constructors and Methods, The super() Method, Types of Inheritance, Single Inheritance, Multiple Inheritance, Method Resolution Order (MRO), Polymorphism, Duck Typing Philosophy of Python, Operator Overloading, Method Overloading, Method Overriding
Abstract Classes and Interfaces: Abstract Method and Abstract Class, Interfaces in Python, Abstract Classes vs. Interfaces,
A Java agents are pluggable self contained components that run embedded in a JVM and intercept the classloading process. They were introduced in Java 5 along with the powerful java.lang.instrument package. Java agents can be loaded statically at startup or dynamically (programmatically) at runtime to attach to a running process in a fail-safe fashion.
Java agents were an awesome addition to the JVM as it opened a lot of opportunities for tool designers and changed Java tooling landscape quite drastically. In conjunction with Java bytecode manipulation libraries it is now possible to do amazing things to Java classes: we can experiment with programming models, redefine classes in runtime, record execution flow, etc.
The presentation provides an overview of Java agents’ functionality along with the usage examples and real world experiences. You will learn, how to implement an agent and apply Instrumentation API in combination with bytecode manipulation libraries to solve interesting tasks.
This document provides an overview of key concepts in object-oriented programming in Java including classes, objects, methods, constructors, arrays, strings, and vectors. It defines classes as templates that define the data and behaviors of objects. Methods represent behaviors of classes. Constructors initialize objects. Arrays are containers that hold a fixed number of values of a single type. Strings are sequences of characters that can be manipulated using methods. Vectors are dynamic arrays that can grow or shrink as needed. The document includes examples of creating objects from classes, defining methods and constructors, declaring and initializing arrays, performing string operations, and using common vector methods.
Inheritance allows one class to inherit attributes and behaviors from another existing class. This helps with code reuse by extending an existing class without modifying it. A derived class inherits from a base class, and any changes to the base class will also affect the derived classes. Abstract classes define common behaviors for other classes to inherit from but cannot be instantiated themselves, instead forcing subclasses to implement abstract methods.
The document introduces inheritance and traits in Scala. It covers topics like inheritance, traits, mix-in composition of traits into classes, ordered traits, traits as stackable modifications, and the option pattern. Inheritance allows code reuse by inheriting properties and behavior from another class. Traits are like interfaces but can have concrete methods and fields. Traits allow mixing behavior into classes and can be mixed in repeatedly. The ordered trait provides comparison methods. Traits enable stackable modifications of classes. The option pattern represents optional values using Some or None.
This document discusses object-oriented programming concepts like inheritance, polymorphism, overloading, and overriding. It provides examples of inheritance hierarchies for different types of birds. Inheritance allows subclasses to inherit attributes and methods from parent classes. Polymorphism means an object can have different implementations of the same method depending on its type. Overloading and overriding relate to creating multiple methods with the same name that differ in parameters or implementation.
This document provides a cheat sheet summarizing key concepts in Objective-C including messaging, method headers, interfaces, implementations, imports, properties and synthesis, inheritance, categories, protocols, and identifiers. It defines each concept and provides examples.
This chapter discusses creating graphical user interfaces (GUIs) in Java by introducing commonly used GUI components like JTextArea, JComboBox, JList, JScrollBar, and JSlider and providing examples of how to use each component to build user interfaces. It also covers creating multiple windows in an application by extending JFrame to create additional window subclasses and instantiating those subclasses.
The document discusses object-oriented programming concepts like class hierarchies, subclass definitions, and inheritance. It provides examples of defining superclass and subclass relationships between classes like Person, Employee, and Manager. The examples demonstrate how subclasses inherit variables and methods from parent classes and can extend them with their own attributes.
This document discusses interfaces in Java, including defining interfaces, implementing interfaces, and providing examples. It covers that an interface defines a collection of methods that a class implements, concrete classes that implement interfaces must provide code bodies for all interface methods, and interfaces allow for multiple inheritance in Java by having classes implement multiple interfaces.
The document discusses using loops to repeatedly execute blocks of code. It introduces the while loop as a way to repeatedly print a string without having to write the print statement hundreds of times. The while loop uses a condition and incrementing counter to control how many times the code block repeats. Examples are provided to trace the execution of a sample while loop.
The document discusses different selection control structures in Java like if, if-else statements and switch statements. It provides examples of using boolean expressions and comparison operators to write conditional logic. The examples include programs to check if a number is positive, guess a user's birthday, and quiz users on math problems.
The document discusses selection control statements in Java including if, if-else, and switch statements. It provides examples of using boolean expressions and comparison operators to write conditional logic. Key topics covered include one-way if statements, two-way if-else statements, nested if statements, avoiding common errors, and using logical operators to combine conditions. Examples provided demonstrate how to use random numbers and selection statements to create simple math quiz programs.
This document discusses inheritance and polymorphism in Java. It begins by introducing the motivations for inheritance, which is to avoid redundancy when designing classes that share common features, like circles, rectangles, and triangles. It then lists the chapter objectives, which include defining subclasses, invoking superclass constructors and methods, overriding methods, polymorphism, and other inheritance-related concepts. The document provides an example of superclass GeometricObject and subclasses Circle and Rectangle. It also discusses that superclass constructors are not inherited by subclasses but must be invoked explicitly or implicitly using the super keyword.
Inheritance allows classes to inherit properties and methods from existing classes. This allows code reuse and avoids rewriting common functionality. The existing class is called the superclass, while the class inheriting is the subclass. The subclass inherits all non-private fields and methods from the superclass. Inheritance is implemented in Java using the "extends" keyword. The subclass can override methods from the superclass to modify their behavior. All classes in Java implicitly extend the Object class, which defines common methods like equals(), hashCode(), and toString().
Inheritance allows one class to acquire properties of another class. A subclass inherits all properties of its superclass and can add its own unique properties. When a method in a subclass has the same name and signature as a method in its superclass, it overrides that method. Dynamic method dispatch determines which version of an overridden method to call based on the actual object type at runtime rather than the reference variable type. Superclass constructors can be called from subclasses using the super keyword, and super can also be used to access hidden superclass members from subclasses.
This document provides an overview of key concepts in C++ including classes, objects, encapsulation, inheritance, and pointers. It discusses how classes can be used to model real-world entities, hiding implementation details and exposing only necessary functions. Inheritance allows code reuse by deriving specialized classes from general base classes. Pointers store the address of variables in memory and can be used to pass data between functions by reference. The document also provides an example Student class with member variables and functions to set and retrieve student data like GPA.
This document discusses Python modules, classes, inheritance, and properties. Some key points:
- Modules allow the organization of Python code into reusable libraries by saving code in files with a .py extension. Modules can contain functions, variables, and be imported into other code.
- Classes are templates that define the properties and methods common to all objects of a certain kind. The __init__() method initializes new objects. Inheritance allows child classes to inherit properties and methods from parent classes.
- Properties provide a way to control access to class attributes, allowing them to be accessed like attributes while hiding the implementation details behind getter and setter methods.
This document provides a PHP 5 cheat sheet that summarizes key PHP types, functions, and predefined variables. It covers boolean, integer, and string types; arrays; classes; date/time functions; and the $_SERVER and $_FILES predefined variables. For each section, it lists main elements and functions with brief descriptions.
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAMaulik Borsaniya
Classes and Object-oriented Programming:
Classes: Creating a Class, The Self Variable, Constructor, Types of Variables, Namespaces, Types of Methods (Instance Methods, Class Methods, Static Methods), Passing Members of One Class to Another Class, Inner Classes
Inheritance and Polymorphism: Constructors in Inheritance, Overriding Super Class Constructors and Methods, The super() Method, Types of Inheritance, Single Inheritance, Multiple Inheritance, Method Resolution Order (MRO), Polymorphism, Duck Typing Philosophy of Python, Operator Overloading, Method Overloading, Method Overriding
Abstract Classes and Interfaces: Abstract Method and Abstract Class, Interfaces in Python, Abstract Classes vs. Interfaces,
A Java agents are pluggable self contained components that run embedded in a JVM and intercept the classloading process. They were introduced in Java 5 along with the powerful java.lang.instrument package. Java agents can be loaded statically at startup or dynamically (programmatically) at runtime to attach to a running process in a fail-safe fashion.
Java agents were an awesome addition to the JVM as it opened a lot of opportunities for tool designers and changed Java tooling landscape quite drastically. In conjunction with Java bytecode manipulation libraries it is now possible to do amazing things to Java classes: we can experiment with programming models, redefine classes in runtime, record execution flow, etc.
The presentation provides an overview of Java agents’ functionality along with the usage examples and real world experiences. You will learn, how to implement an agent and apply Instrumentation API in combination with bytecode manipulation libraries to solve interesting tasks.
This document provides an overview of key concepts in object-oriented programming in Java including classes, objects, methods, constructors, arrays, strings, and vectors. It defines classes as templates that define the data and behaviors of objects. Methods represent behaviors of classes. Constructors initialize objects. Arrays are containers that hold a fixed number of values of a single type. Strings are sequences of characters that can be manipulated using methods. Vectors are dynamic arrays that can grow or shrink as needed. The document includes examples of creating objects from classes, defining methods and constructors, declaring and initializing arrays, performing string operations, and using common vector methods.
Inheritance allows one class to inherit attributes and behaviors from another existing class. This helps with code reuse by extending an existing class without modifying it. A derived class inherits from a base class, and any changes to the base class will also affect the derived classes. Abstract classes define common behaviors for other classes to inherit from but cannot be instantiated themselves, instead forcing subclasses to implement abstract methods.
The document introduces inheritance and traits in Scala. It covers topics like inheritance, traits, mix-in composition of traits into classes, ordered traits, traits as stackable modifications, and the option pattern. Inheritance allows code reuse by inheriting properties and behavior from another class. Traits are like interfaces but can have concrete methods and fields. Traits allow mixing behavior into classes and can be mixed in repeatedly. The ordered trait provides comparison methods. Traits enable stackable modifications of classes. The option pattern represents optional values using Some or None.
This document discusses object-oriented programming concepts like inheritance, polymorphism, overloading, and overriding. It provides examples of inheritance hierarchies for different types of birds. Inheritance allows subclasses to inherit attributes and methods from parent classes. Polymorphism means an object can have different implementations of the same method depending on its type. Overloading and overriding relate to creating multiple methods with the same name that differ in parameters or implementation.
This document provides a cheat sheet summarizing key concepts in Objective-C including messaging, method headers, interfaces, implementations, imports, properties and synthesis, inheritance, categories, protocols, and identifiers. It defines each concept and provides examples.
This chapter discusses creating graphical user interfaces (GUIs) in Java by introducing commonly used GUI components like JTextArea, JComboBox, JList, JScrollBar, and JSlider and providing examples of how to use each component to build user interfaces. It also covers creating multiple windows in an application by extending JFrame to create additional window subclasses and instantiating those subclasses.
The document discusses object-oriented programming concepts like class hierarchies, subclass definitions, and inheritance. It provides examples of defining superclass and subclass relationships between classes like Person, Employee, and Manager. The examples demonstrate how subclasses inherit variables and methods from parent classes and can extend them with their own attributes.
This document discusses interfaces in Java, including defining interfaces, implementing interfaces, and providing examples. It covers that an interface defines a collection of methods that a class implements, concrete classes that implement interfaces must provide code bodies for all interface methods, and interfaces allow for multiple inheritance in Java by having classes implement multiple interfaces.
The document discusses using loops to repeatedly execute blocks of code. It introduces the while loop as a way to repeatedly print a string without having to write the print statement hundreds of times. The while loop uses a condition and incrementing counter to control how many times the code block repeats. Examples are provided to trace the execution of a sample while loop.
The document discusses different selection control structures in Java like if, if-else statements and switch statements. It provides examples of using boolean expressions and comparison operators to write conditional logic. The examples include programs to check if a number is positive, guess a user's birthday, and quiz users on math problems.
Here are the key steps to copy a file using buffered streams:
1. Create a FileInputStream on the source file
2. Create a BufferedInputStream from the FileInputStream
3. Create a FileOutputStream on the target file
4. Create a BufferedOutputStream from the FileOutputStream
5. Read bytes from the BufferedInputStream and write to the BufferedOutputStream
6. Close the streams
This uses buffered streams to improve performance by reducing the number of reads/writes through buffering. The buffered streams handle reading/writing the file contents efficiently under the hood.
This document discusses two-dimensional arrays in Java. It begins by providing motivations for using two-dimensional arrays such as to represent a matrix or table of data. It then lists the chapter objectives which are to introduce two-dimensional arrays, demonstrate how to declare, create, access elements of, and perform common operations on two-dimensional arrays. The document also covers passing two-dimensional arrays to methods, and examples of using two-dimensional arrays for problems like grading multiple choice questions and solving the closest pair problem.
This chapter introduces Java GUI programming using Swing. It discusses the motivations for using Swing over AWT, outlines the objectives to be covered, and provides examples of creating basic Swing components like buttons, labels, text fields etc. It also explains the Swing and AWT class hierarchies with Container and Helper classes.
The document discusses arrays in Java programming. It defines an array as a data structure that holds a collection of the same type of data. Arrays allow programmers to store and access multiple values in a single variable. The document covers how to declare array variables, create arrays, initialize arrays, access array elements using indexes, and perform common operations on arrays such as finding minimum/maximum values.
The document provides an introduction to computers, programs, Java, and the Java programming language. It discusses the basic components of a computer including the CPU, memory, storage devices, input/output devices, and how data is stored. It then explains what programs are, different types of programming languages, and how source code is interpreted or compiled. The document also covers operating systems, an overview of Java and its history, and characteristics of the Java programming language such as being simple, object-oriented, distributed, interpreted, robust, secure, architecture-neutral, portable, multithreaded, and dynamic.
This document introduces elementary Java programming concepts. It discusses writing Java programs to perform simple computations and obtain input from the console. The key topics covered include using variables to store data, assignment statements, constants, primitive data types, operators, expressions, and input/output. An example program is presented to demonstrate computing the area of a circle by assigning values to variables, performing calculations, and printing output.
The document introduces strings and the String class in Java, describing how to construct, compare, manipulate, and extract substrings from strings. It also covers converting between strings and other data types, as well as using regular expressions to match and replace patterns within strings. The overall goal is to provide programmers with the necessary string processing capabilities to solve problems involving text files and replacing words within files.
The document discusses Java methods. It defines a method as a collection of statements grouped to perform an operation. A method signature combines the method name and parameter list. Formal parameters are defined in the method header, while actual parameters are the values passed when invoking the method. The document provides an example method that returns the maximum of two integers.
This document discusses objects and classes in Java. It introduces object-oriented programming concepts like objects having state in the form of data fields and behavior in the form of methods. Classes are used to define objects of the same type by specifying their data fields and methods. The document provides examples of defining a Circle class and creating Circle objects that demonstrate accessing object data and using methods. It also explains concepts like constructors, which are special methods used to initialize objects when they are created.
This document provides an introduction to computer languages. It discusses low-level languages like machine language that use binary, and assembly language that uses alphanumeric codes. It also discusses high-level languages like BASIC, FORTRAN, and COBOL that more closely resemble English. High-level languages are easier for humans to read and write but require compilers or interpreters to translate them to machine language. C was developed in the 1970s at Bell Labs to build the Unix operating system and became a standard in 1989.
This talk was delivered at JavaOne 2013, together with Andrzej Grzesik. We mention the new Date APIs, changes to Collections as well as Streams APIs and of course... Lambdas!
Java was created in 1990 by James Gosling at Sun Microsystems to control microprocessors embedded in consumer devices. It was designed to be platform independent, reliable, and compact. Over time, Java expanded to support web and internet applications. Major versions included Java 1.0 in 1995, Java 1.1 in 1997, Java 1.2 in 1999, and Java 1.3 in 2002, each adding new packages, classes, and functionality. Key features of Java include being platform independent, object-oriented, having automatic memory management via garbage collection, and prioritizing security.
Presentation on the new features introduced in JDK 8, presented on the 26.02.2013 in Sofia University in front of students and members of the Bulgarian java user group.
Introduction to Java Programming Languagejaimefrozr
The document provides an introduction and history of the Java programming language. It discusses that Java was originally developed in 1991 by Sun Microsystems to be portable for consumer electronic devices. The document then summarizes the key capabilities of Java including being a general purpose language that can develop robust applications for desktops, servers, and mobile devices. It also outlines the Java language specifications, application programming interface containing predefined classes, and development tools available. Finally, it explains how Java's use of byte code and the Java Virtual Machine allows it to be highly portable across different operating systems.
This document provides an introduction and overview of the Java programming language. It discusses that Java was developed by Sun Microsystems in the 1990s as a general-purpose, object-oriented language designed for easy web and internet applications. The key principles of object-oriented programming like encapsulation, inheritance, and polymorphism are explained. Characteristics of Java like being simple, secure, portable, and having good performance are highlighted. A brief history of Java's development is also presented.
Lambdas and streams are key new features in Java 8. Lambdas allow blocks of code to be passed around as if they were objects. Streams provide an abstraction for processing collections of objects in a declarative way using lambdas. Optional is a new class that represents null-safe references and helps avoid null pointer exceptions. Checked exceptions can cause issues with lambdas, so helper methods are recommended to convert checked exceptions to unchecked exceptions.
This document is a summary of a lecture about radio advertising copywriting. It discusses common myths around radio advertising, key elements of effective radio ads including scripts, sound design and casting. It also covers how to effectively use humor in radio ads and considers the future of radio advertising. The lecture addresses topics like the high reach of radio, how to write radio scripts, the importance of sound design and casting voice talent, and how radio advertising may evolve in a multi-platform environment with more sophisticated technology.
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 inheritance and polymorphism in Java. It covers defining subclasses that inherit properties and methods from superclasses, invoking superclass constructors using the super keyword, overriding methods in subclasses, and polymorphism which allows calling the same method on objects of different types. It provides examples of defining subclasses for shapes like Circle and Rectangle that extend a GeometricObject superclass.
1) Abstract classes allow common behaviors to be defined for subclasses while leaving implementation of some methods abstract.
2) The chapter discusses using abstract classes GeometricObject and Number, and subclasses like Circle, Rectangle, and numeric wrapper classes.
3) Abstract classes can contain abstract methods that subclasses must implement, though an abstract class needs no abstract methods itself. Subclasses of abstract classes cannot be instantiated.
Object Oriented Programming_Chapter 3 (Two Lectures)
1- Let’s think on Inheritance
2- Let’s focus on Superclass’s Constructor
الكلية الجامعية للعلوم والتكنولوجيا - خان يونس
University college of science & technology
Detailed presentation on Inheritance and interfaces in JAVA. Presentation includes suitable example for better understanding the concepts such as Overriding in java and also keywords such as FINAL and SUPER.
The document discusses key concepts related to arrays in Java including:
1) Declaring and initializing arrays of primitive and object types.
2) Creating single and multi-dimensional arrays.
3) Copying elements between arrays using System.arrayCopy().
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.
Java tutorial for Beginners and Entry LevelRamrao Desai
This document provides an overview of key Java concepts including classes, objects, inheritance, interfaces, exceptions, and more. It begins with a roadmap and definitions of object-oriented concepts like class and object. It then covers class variables and methods, visibility, static vs non-static, constructors, and the this keyword. The document also discusses inheritance, polymorphism, interfaces, exceptions, and error handling in Java.
The document discusses inheritance in Java. It defines inheritance as a process where one class acquires properties of another class. The class that inherits properties is called a subclass, and the class whose properties are inherited is called a superclass. In Java, a subclass can only inherit from one superclass (single inheritance). The extends keyword is used for inheritance. The document then discusses what can be done in subclasses, such as overriding and overloading methods, and polymorphism. It also covers abstract classes, interfaces, and casting objects.
09slide.ppt oops classes and objects conceptkavitamittal18
This document discusses object-oriented programming concepts in Java, including classes, objects, and the relationships between them. It introduces the Circle class as an example, explaining that a class acts as a template for objects and defines their data fields and methods. It also discusses how to define classes, create objects from classes using constructors, and access objects' members via reference variables. Key concepts covered include objects having state represented by data fields and behavior defined through methods.
The document discusses object-oriented programming concepts in Java, including classes, objects, and constructors. It defines a class as a template that defines the data fields and methods common to all objects of that type. An object is an instance of a class that contains the object's current state data. Constructors are special methods used to initialize new objects. The document provides examples of defining a Circle class and creating Circle objects using constructors. It also shows how to define classes graphically using UML class diagrams.
This document discusses the core concepts of object-oriented programming (OOP) in Java, including inheritance, encapsulation, abstraction, and polymorphism. It provides examples of each concept: inheritance allows classes to inherit properties from parent classes; encapsulation involves hiding data and code together within classes; abstraction deals with hiding details and focusing on essentials through abstract classes and interfaces; polymorphism allows classes to take different forms. The document uses examples like vehicles and medical capsules to illustrate how each OOP concept works in Java code.
oops concept in java | object oriented programming in javaCPD INDIA
The document discusses key concepts in object-oriented programming in Java including classes, objects, inheritance, packages, interfaces, encapsulation, abstraction, and polymorphism. It provides examples to illustrate each concept. Classes define the structure and behavior of objects. Objects are instances of classes. Inheritance allows classes to extend existing classes. Packages organize related classes. Interfaces define behaviors without implementation. Encapsulation hides implementation details. Abstraction models essential features without specifics. Polymorphism allows the same method name with different signatures or overriding.
This document summarizes Chapter 10 of Liang's Introduction to Java Programming textbook. It discusses key concepts in object-oriented programming like immutable objects, scope of variables, the this keyword, class abstraction, and composition relationships. It provides examples of how to create immutable classes, use this to reference instance variables and call constructors, and model relationships between classes using composition. The chapter aims to demonstrate how to solve problems using the object-oriented paradigm in Java.
The document provides an overview of C++ vs C# by Shubhra Chauhan. It discusses the key object-oriented programming concepts like classes, objects, inheritance, polymorphism, and how they are implemented in C++ and C#. It includes code examples to demonstrate class usage and inheritance in both languages. The document also compares some similarities and differences between C++ and C# like support for pointers, preprocessors, structures, and goto statements.
Reflection in Java allows examination of classes, interfaces, fields and methods at runtime without knowing the names of the classes, fields or methods at compile time. It allows a program to create instances of classes, invoke methods, set and get field values, and execute other operations at runtime. The key classes for reflection include Class, Constructor, Field, Method and others in the java.lang.reflect package. Reflection is commonly used for activities like class browsing, debugging, testing and building extensible applications. However, it has performance and security implications and should not be used without consideration.
The document discusses object-oriented programming concepts in Java including defining classes and objects, using abstraction and encapsulation to simplify problems, and utilizing inheritance, polymorphism, abstract classes, and interfaces. It provides examples of modeling classes with UML diagrams, implementing accessors and mutators, using inheritance and polymorphism through method overloading and overriding, and defining abstract classes and interfaces to simulate multiple inheritance. The document is intended to teach learners object-oriented programming fundamentals in Java.
This document discusses inheritance in object-oriented programming. Inheritance allows new classes to inherit properties from existing parent classes, promoting code reuse. There are various forms of inheritance like single, multiple, and multi-level inheritance. Child classes can override methods and variables from the parent class. Child class constructors can invoke parent constructors using the super keyword. Inheritance is an important aspect of object-oriented design that increases efficiency and maintainability.
This chapter introduces jQuery, a commonly used JavaScript library. It allows developers to select elements, traverse the DOM, manipulate elements, and handle events with minimal code. The chapter covers including the jQuery library, selecting elements with CSS selectors, DOM traversal methods, manipulation methods, specifying event handlers, and animation methods.
This chapter discusses updating web pages with Ajax. It introduces the XMLHttpRequest object, which allows asynchronous JavaScript requests and responses between a client and server without reloading the page. It covers the steps to make HTTP requests and process responses, including opening and sending requests, receiving data, and handling synchronous vs asynchronous requests. It also discusses techniques for making cross-domain requests, such as using JSON-P or CORS.
This chapter discusses programming for touchscreens and mobile devices in JavaScript. It covers using touch, pointer, and geolocation events to integrate mouse and touch interactions. It also provides ways to optimize mobile web apps, such as minimizing file sizes and loading scripts responsively. The chapter aims to help developers make their apps accessible and functional across different mobile platforms and input types.
This chapter discusses managing state information and security in JavaScript. It covers saving state with query strings, hidden form fields, and cookies. Cookies are small pieces of information stored by the web server on the user's computer. The chapter also discusses JavaScript security issues and the same origin policy, which restricts how scripts can access other domains. Web storage is introduced as an alternative to cookies that is easier to use but has less browser support.
This chapter discusses manipulating data in strings and arrays in JavaScript. It covers string and array properties and methods for parsing, formatting, searching, extracting, replacing, sorting, and combining strings and array elements. The chapter also covers defining and using regular expressions to validate user input.
This chapter discusses object-oriented programming concepts in JavaScript like encapsulation and interfaces. It covers built-in JavaScript classes like Date, Number, and Math that can be used to manipulate dates, numbers, and perform math functions. The chapter also explains how to define custom JavaScript objects using object literals and constructor functions, and how to add methods and properties to objects.
This chapter discusses enhancing and validating forms with JavaScript. It covers customizing browser-based validation, implementing custom validation functions to check for errors, and displaying error messages. Some key points covered include validating required fields, dependent fields, and content type with custom functions. It also discusses improving form usability with techniques like removing default selections and dynamically updating fields based on user inputs.
This document provides an overview of working with the Document Object Model (DOM) and Dynamic HTML (DHTML) in JavaScript. It discusses the browser object model and DOM tree, and how to access and manipulate DOM elements using methods like getElementById(), getElementsByTagName(), and querySelectorAll(). It also covers adding, removing, and cloning DOM nodes. Finally, it discusses the Window, History, Location, and Screen objects and their properties and methods for manipulating the browser window and navigating between pages.
This chapter discusses debugging and error handling in JavaScript. It covers recognizing different types of errors like syntax errors and logic errors. It also discusses various debugging techniques like using error messages, comments, alerts, console.log(), breakpoints, and the debugger tools in browsers to trace errors. Handling exceptions gracefully with try/catch blocks and implementing custom error handling is also covered.
This chapter discusses arrays, loops, and conditional statements in JavaScript. It covers how to store data in arrays, access and modify array elements, and determine an array's length. The chapter also explains while, do/while, and for loops for repeatedly executing code. It describes if, if/else, and switch conditional statements for making decisions, including nesting statements and else if constructions.
This chapter discusses functions, data types, and operators in JavaScript. It covers defining and calling functions, variable scope, built-in and custom functions, primitive and non-primitive data types including strings, numbers, Booleans, and null/undefined. The chapter also explains arithmetic, assignment, comparison, logical, and special operators as well as operator precedence.
The document discusses the history and components of the World Wide Web and HTML. It introduces JavaScript as a client-side scripting language that allows for interactive web pages. Key points covered include the difference between client-side and server-side scripting, adding JavaScript to web pages using the <script> element, and structuring JavaScript code by placing it in the document body or an external .js file. The document also addresses writing valid JavaScript code that can be validated as XHTML.
This document discusses overloading and templates in C++. It covers operator overloading, including restrictions and syntax for overloading operators as member and nonmember functions. It also discusses function templates and class templates, explaining that templates allow writing generic code for related functions and classes. Function templates simplify function overloading, while class templates create parameterized types. The document provides examples of overloading operators and creating function and class templates.
This chapter discusses stacks and queues as data structures. It describes stack operations like push and pop and how to implement stacks as arrays and linked lists. It also covers queue operations and implementations as well as using stacks and queues to solve problems involving infix expressions, recursion removal, and simulations.
This document discusses linked lists and their implementation in C++. It covers the basic properties of linked lists, including how they are composed of nodes that contain data and a pointer to the next node. The key operations of linked lists are described, such as traversing the list, inserting and deleting nodes, and building the list in both the forward and backward directions. Implementing linked lists as an abstract data type is also covered, including defining iterator classes to iterate through the list.
This chapter discusses searching, sorting algorithms, and the vector type in C++. It covers sequential search, bubble sort, insertion sort, and binary search algorithms. It also introduces the vector type, which implements a dynamic list that can grow and shrink in size during program execution. Some key operations on vectors include accessing elements, inserting/deleting, and iterating through elements using a range-based for loop.
The document discusses recursion, including recursive definitions, algorithms, and functions. It defines recursion as solving a problem by reducing it to smaller instances of itself. A recursive definition has a base case that directly solves the simplest problem, and a general case that reduces the problem to a smaller instance. Recursive algorithms are implemented using recursive functions, which call themselves directly or indirectly. The document also compares recursion to iteration and discusses factors like efficiency to consider when choosing an approach.
The document discusses exception handling in C++. It covers try/catch blocks for handling exceptions, throwing exceptions, and creating custom exception classes. The key aspects are using try/catch blocks to handle exceptions, throwing exceptions within try blocks, and creating exception classes that inherit from the base exception class. Catch blocks specify the exception type and contain handling code. Exceptions not caught will terminate the program through stack unwinding.
This chapter covers pointers, classes, virtual functions, and abstract classes in C++. It discusses pointer variables and how to declare and manipulate them. It covers using pointers with classes and structs, as well as dynamic variables created with new and delete. The chapter also explores pointers with inheritance and polymorphism through virtual functions and abstract classes. It addresses issues like shallow vs deep copying when using pointers with classes.
This document provides an overview of inheritance and composition in C++. It discusses key concepts such as derived classes inheriting properties from base classes, redefining member functions of base classes in derived classes, how constructors and destructors work in inheritance hierarchies, and the differences between inheritance, aggregation, and composition relationships between classes. The document also covers stream class hierarchies and the three main types of inheritance: public, protected, and private.
This document provides an overview of wound healing, its functions, stages, mechanisms, factors affecting it, and complications.
A wound is a break in the integrity of the skin or tissues, which may be associated with disruption of the structure and function.
Healing is the body’s response to injury in an attempt to restore normal structure and functions.
Healing can occur in two ways: Regeneration and Repair
There are 4 phases of wound healing: hemostasis, inflammation, proliferation, and remodeling. This document also describes the mechanism of wound healing. Factors that affect healing include infection, uncontrolled diabetes, poor nutrition, age, anemia, the presence of foreign bodies, etc.
Complications of wound healing like infection, hyperpigmentation of scar, contractures, and keloid formation.
How to Make a Field Mandatory in Odoo 17Celine George
In Odoo, making a field required can be done through both Python code and XML views. When you set the required attribute to True in Python code, it makes the field required across all views where it's used. Conversely, when you set the required attribute in XML views, it makes the field required only in the context of that particular view.
Chapter wise All Notes of First year Basic Civil Engineering.pptxDenish Jangid
Chapter wise All Notes of First year Basic Civil Engineering
Syllabus
Chapter-1
Introduction to objective, scope and outcome the subject
Chapter 2
Introduction: Scope and Specialization of Civil Engineering, Role of civil Engineer in Society, Impact of infrastructural development on economy of country.
Chapter 3
Surveying: Object Principles & Types of Surveying; Site Plans, Plans & Maps; Scales & Unit of different Measurements.
Linear Measurements: Instruments used. Linear Measurement by Tape, Ranging out Survey Lines and overcoming Obstructions; Measurements on sloping ground; Tape corrections, conventional symbols. Angular Measurements: Instruments used; Introduction to Compass Surveying, Bearings and Longitude & Latitude of a Line, Introduction to total station.
Levelling: Instrument used Object of levelling, Methods of levelling in brief, and Contour maps.
Chapter 4
Buildings: Selection of site for Buildings, Layout of Building Plan, Types of buildings, Plinth area, carpet area, floor space index, Introduction to building byelaws, concept of sun light & ventilation. Components of Buildings & their functions, Basic concept of R.C.C., Introduction to types of foundation
Chapter 5
Transportation: Introduction to Transportation Engineering; Traffic and Road Safety: Types and Characteristics of Various Modes of Transportation; Various Road Traffic Signs, Causes of Accidents and Road Safety Measures.
Chapter 6
Environmental Engineering: Environmental Pollution, Environmental Acts and Regulations, Functional Concepts of Ecology, Basics of Species, Biodiversity, Ecosystem, Hydrological Cycle; Chemical Cycles: Carbon, Nitrogen & Phosphorus; Energy Flow in Ecosystems.
Water Pollution: Water Quality standards, Introduction to Treatment & Disposal of Waste Water. Reuse and Saving of Water, Rain Water Harvesting. Solid Waste Management: Classification of Solid Waste, Collection, Transportation and Disposal of Solid. Recycling of Solid Waste: Energy Recovery, Sanitary Landfill, On-Site Sanitation. Air & Noise Pollution: Primary and Secondary air pollutants, Harmful effects of Air Pollution, Control of Air Pollution. . Noise Pollution Harmful Effects of noise pollution, control of noise pollution, Global warming & Climate Change, Ozone depletion, Greenhouse effect
Text Books:
1. Palancharmy, Basic Civil Engineering, McGraw Hill publishers.
2. Satheesh Gopi, Basic Civil Engineering, Pearson Publishers.
3. Ketki Rangwala Dalal, Essentials of Civil Engineering, Charotar Publishing House.
4. BCP, Surveying volume 1
How to Setup Warehouse & Location in Odoo 17 InventoryCeline George
In this slide, we'll explore how to set up warehouses and locations in Odoo 17 Inventory. This will help us manage our stock effectively, track inventory levels, and streamline warehouse operations.
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...PECB
Denis is a dynamic and results-driven Chief Information Officer (CIO) with a distinguished career spanning information systems analysis and technical project management. With a proven track record of spearheading the design and delivery of cutting-edge Information Management solutions, he has consistently elevated business operations, streamlined reporting functions, and maximized process efficiency.
Certified as an ISO/IEC 27001: Information Security Management Systems (ISMS) Lead Implementer, Data Protection Officer, and Cyber Risks Analyst, Denis brings a heightened focus on data security, privacy, and cyber resilience to every endeavor.
His expertise extends across a diverse spectrum of reporting, database, and web development applications, underpinned by an exceptional grasp of data storage and virtualization technologies. His proficiency in application testing, database administration, and data cleansing ensures seamless execution of complex projects.
What sets Denis apart is his comprehensive understanding of Business and Systems Analysis technologies, honed through involvement in all phases of the Software Development Lifecycle (SDLC). From meticulous requirements gathering to precise analysis, innovative design, rigorous development, thorough testing, and successful implementation, he has consistently delivered exceptional results.
Throughout his career, he has taken on multifaceted roles, from leading technical project management teams to owning solutions that drive operational excellence. His conscientious and proactive approach is unwavering, whether he is working independently or collaboratively within a team. His ability to connect with colleagues on a personal level underscores his commitment to fostering a harmonious and productive workplace environment.
Date: May 29, 2024
Tags: Information Security, ISO/IEC 27001, ISO/IEC 42001, Artificial Intelligence, GDPR
-------------------------------------------------------------------------------
Find out more about ISO training and certification services
Training: ISO/IEC 27001 Information Security Management System - EN | PECB
ISO/IEC 42001 Artificial Intelligence Management System - EN | PECB
General Data Protection Regulation (GDPR) - Training Courses - EN | PECB
Webinars: https://pecb.com/webinars
Article: https://pecb.com/article
-------------------------------------------------------------------------------
For more information about PECB:
Website: https://pecb.com/
LinkedIn: https://www.linkedin.com/company/pecb/
Facebook: https://www.facebook.com/PECBInternational/
Slideshare: http://www.slideshare.net/PECBCERTIFICATION
How to Build a Module in Odoo 17 Using the Scaffold MethodCeline George
Odoo provides an option for creating a module by using a single line command. By using this command the user can make a whole structure of a module. It is very easy for a beginner to make a module. There is no need to make each file manually. This slide will show how to create a module using the scaffold method.
How to Fix the Import Error in the Odoo 17Celine George
An import error occurs when a program fails to import a module or library, disrupting its execution. In languages like Python, this issue arises when the specified module cannot be found or accessed, hindering the program's functionality. Resolving import errors is crucial for maintaining smooth software operation and uninterrupted development processes.
A workshop hosted by the South African Journal of Science aimed at postgraduate students and early career researchers with little or no experience in writing and publishing journal articles.
Walmart Business+ and Spark Good for Nonprofits.pdfTechSoup
"Learn about all the ways Walmart supports nonprofit organizations.
You will hear from Liz Willett, the Head of Nonprofits, and hear about what Walmart is doing to help nonprofits, including Walmart Business and Spark Good. Walmart Business+ is a new offer for nonprofits that offers discounts and also streamlines nonprofits order and expense tracking, saving time and money.
The webinar may also give some examples on how nonprofits can best leverage Walmart Business+.
The event will cover the following::
Walmart Business + (https://business.walmart.com/plus) is a new shopping experience for nonprofits, schools, and local business customers that connects an exclusive online shopping experience to stores. Benefits include free delivery and shipping, a 'Spend Analytics” feature, special discounts, deals and tax-exempt shopping.
Special TechSoup offer for a free 180 days membership, and up to $150 in discounts on eligible orders.
Spark Good (walmart.com/sparkgood) is a charitable platform that enables nonprofits to receive donations directly from customers and associates.
Answers about how you can do more with Walmart!"
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UPRAHUL
This Dissertation explores the particular circumstances of Mirzapur, a region located in the
core of India. Mirzapur, with its varied terrains and abundant biodiversity, offers an optimal
environment for investigating the changes in vegetation cover dynamics. Our study utilizes
advanced technologies such as GIS (Geographic Information Systems) and Remote sensing to
analyze the transformations that have taken place over the course of a decade.
The complex relationship between human activities and the environment has been the focus
of extensive research and worry. As the global community grapples with swift urbanization,
population expansion, and economic progress, the effects on natural ecosystems are becoming
more evident. A crucial element of this impact is the alteration of vegetation cover, which plays a
significant role in maintaining the ecological equilibrium of our planet.Land serves as the foundation for all human activities and provides the necessary materials for
these activities. As the most crucial natural resource, its utilization by humans results in different
'Land uses,' which are determined by both human activities and the physical characteristics of the
land.
The utilization of land is impacted by human needs and environmental factors. In countries
like India, rapid population growth and the emphasis on extensive resource exploitation can lead
to significant land degradation, adversely affecting the region's land cover.
Therefore, human intervention has significantly influenced land use patterns over many
centuries, evolving its structure over time and space. In the present era, these changes have
accelerated due to factors such as agriculture and urbanization. Information regarding land use and
cover is essential for various planning and management tasks related to the Earth's surface,
providing crucial environmental data for scientific, resource management, policy purposes, and
diverse human activities.
Accurate understanding of land use and cover is imperative for the development planning
of any area. Consequently, a wide range of professionals, including earth system scientists, land
and water managers, and urban planners, are interested in obtaining data on land use and cover
changes, conversion trends, and other related patterns. The spatial dimensions of land use and
cover support policymakers and scientists in making well-informed decisions, as alterations in
these patterns indicate shifts in economic and social conditions. Monitoring such changes with the
help of Advanced technologies like Remote Sensing and Geographic Information Systems is
crucial for coordinated efforts across different administrative levels. Advanced technologies like
Remote Sensing and Geographic Information Systems
9
Changes in vegetation cover refer to variations in the distribution, composition, and overall
structure of plant communities across different temporal and spatial scales. These changes can
occur natural.
1. Chapter 11 Inheritance and
Polymorphism
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
1
2. Motivations
Suppose you will define classes to model circles,
rectangles, and triangles. These classes have many
common features. What is the best way to design
these classes so to avoid redundancy? The answer
is to use inheritance.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
2
3. Objectives
To define a subclass from a superclass through inheritance (§11.2).
To invoke the superclass’s constructors and methods using the super keyword
(§11.3).
To override instance methods in the subclass (§11.4).
To distinguish differences between overriding and overloading (§11.5).
To explore the toString() method in the Object class (§11.6).
To discover polymorphism and dynamic binding (§§11.7–11.8).
To describe casting and explain why explicit downcasting is necessary (§11.9).
To explore the equals method in the Object class (§11.10).
To store, retrieve, and manipulate objects in an ArrayList (§11.11).
To implement a Stack class using ArrayList (§11.12).
To enable data and methods in a superclass accessible from subclasses using the
protected visibility modifier (§11.13).
To prevent class extending and method overriding using the final modifier
(§11.14).
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
3
4. Superclasses and Subclasses
GeometricObject
-color: String The color of the object (default: white).
-filled: boolean Indicates whether the object is filled with a color(default: false).
-dateCreated: java.util.Date The date when the object was created.
+GeometricObject() Creates a GeometricObject.
+GeometricObject(color: String, Creates a GeometricObject with the specified color and fill
ed
filled: boolean) values.
GeometricObject
+getColor(): String Returns the color.
+setColor(color: String): void Sets a new color.
+isFilled(): boolean Returns the filled property.
+setFilled(filled: boolean): void Sets a new filled property.
+getDateCreated(): java.util.Date Returns the dateCreated. CircleFromSimpleGeometricObject
+toString(): String Returns a string representation of this object.
RectangleFromSimpleGeometricObject
Circle Rectangle
-radius: double -width: double
+Circle() -height: double
+Circle(radius: double) +Rectangle()
+Circle(radius: double, color String,
: +Rectangle(width: double, height: double)
filled: boolean) +Rectangle(width: double, height: double
+getRadius(): double
+setRadius(radius: double): void
color: String, filled: boolean)
+getWidth(): double TestCircleRectangle
+getArea(): double +setWidth(width: double): void
+getPerimeter(): double +getHeight(): double
+getDiameter(): double
+printCircle(): void
+setHeight(height: double): void
+getArea(): double Run
+getPerimeter(): double
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
4
5. Are superclass’s Constructor
Inherited?
No. They are not inherited.
They are invoked explicitly or implicitly.
Explicitly using the super keyword.
A constructor is used to construct an instance of a class.
Unlike properties and methods, a superclass's
constructors are not inherited in the subclass. They can
only be invoked from the subclasses' constructors, using
the keyword super. If the keyword super is not explicitly
used, the superclass's no-arg constructor is
automatically invoked.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
5
6. Superclass’s Constructor Is Always Invoked
A constructor may invoke an overloaded constructor or its
superclass’s constructor. If none of them is invoked
explicitly, the compiler puts super() as the first statement
in the constructor. For example,
public A() { public A() {
is equivalent to
} super();
}
public A(double d) { public A(double d) {
// some statements is equivalent to
super();
} // some statements
}
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
6
7. Using the Keyword super
The keyword super refers to the superclass
of the class in which super appears. This
keyword can be used in two ways:
To call a superclass constructor
To call a superclass method
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
7
8. CAUTION
You must use the keyword super to call the
superclass constructor. Invoking a
superclass constructor’s name in a subclass
causes a syntax error. Java requires that the
statement that uses the keyword super
appear first in the constructor.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
8
9. Constructor Chaining
Constructing an instance of a class invokes all the superclasses’ constructors
along the inheritance chain. This is called constructor chaining.
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty();
}
public Faculty() {
System.out.println("(4) Faculty's no-arg constructor is invoked");
}
}
class Employee extends Person {
public Employee() {
this("(2) Invoke Employee’s overloaded constructor");
System.out.println("(3) Employee's no-arg constructor is invoked");
}
public Employee(String s) {
System.out.println(s);
}
}
class Person {
public Person() {
System.out.println("(1) Person's no-arg constructor is invoked");
}
} Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
9
10. animation
Trace Execution
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty(); 1. Start from the
} main method
public Faculty() {
System.out.println("(4) Faculty's no-arg constructor is invoked");
}
}
class Employee extends Person {
public Employee() {
this("(2) Invoke Employee’s overloaded constructor");
System.out.println("(3) Employee's no-arg constructor is invoked");
}
public Employee(String s) {
System.out.println(s);
}
}
class Person {
public Person() {
System.out.println("(1) Person's no-arg constructor is invoked");
}
}
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
10
11. animation
Trace Execution
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty(); 2. Invoke Faculty
} constructor
public Faculty() {
System.out.println("(4) Faculty's no-arg constructor is invoked");
}
}
class Employee extends Person {
public Employee() {
this("(2) Invoke Employee’s overloaded constructor");
System.out.println("(3) Employee's no-arg constructor is invoked");
}
public Employee(String s) {
System.out.println(s);
}
}
class Person {
public Person() {
System.out.println("(1) Person's no-arg constructor is invoked");
}
}
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
11
12. animation
Trace Execution
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty();
}
public Faculty() {
System.out.println("(4) Faculty's no-arg constructor is invoked");
}
} 3. Invoke Employee’s no-
class Employee extends Person {
arg constructor
public Employee() {
this("(2) Invoke Employee’s overloaded constructor");
System.out.println("(3) Employee's no-arg constructor is invoked");
}
public Employee(String s) {
System.out.println(s);
}
}
class Person {
public Person() {
System.out.println("(1) Person's no-arg constructor is invoked");
}
}
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
12
13. animation
Trace Execution
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty();
}
public Faculty() {
System.out.println("(4) Faculty's no-arg constructor is invoked");
}
}
4. Invoke Employee(String)
class Employee extends Person { constructor
public Employee() {
this("(2) Invoke Employee’s overloaded constructor");
System.out.println("(3) Employee's no-arg constructor is invoked");
}
public Employee(String s) {
System.out.println(s);
}
}
class Person {
public Person() {
System.out.println("(1) Person's no-arg constructor is invoked");
}
}
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
13
14. animation
Trace Execution
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty();
}
public Faculty() {
System.out.println("(4) Faculty's no-arg constructor is invoked");
}
}
class Employee extends Person {
public Employee() {
this("(2) Invoke Employee’s overloaded constructor");
System.out.println("(3) Employee's no-arg constructor is invoked");
}
public Employee(String s) {
System.out.println(s);
}
} 5. Invoke Person() constructor
class Person {
public Person() {
System.out.println("(1) Person's no-arg constructor is invoked");
}
}
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
14
15. animation
Trace Execution
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty();
}
public Faculty() {
System.out.println("(4) Faculty's no-arg constructor is invoked");
}
}
class Employee extends Person {
public Employee() {
this("(2) Invoke Employee’s overloaded constructor");
System.out.println("(3) Employee's no-arg constructor is invoked");
}
public Employee(String s) {
System.out.println(s);
}
}
6. Execute println
class Person {
public Person() {
System.out.println("(1) Person's no-arg constructor is invoked");
}
}
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
15
16. animation
Trace Execution
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty();
}
public Faculty() {
System.out.println("(4) Faculty's no-arg constructor is invoked");
}
}
class Employee extends Person {
public Employee() {
this("(2) Invoke Employee’s overloaded constructor");
System.out.println("(3) Employee's no-arg constructor is invoked");
}
public Employee(String s) {
System.out.println(s);
}
}
7. Execute println
class Person {
public Person() {
System.out.println("(1) Person's no-arg constructor is invoked");
}
}
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
16
17. animation
Trace Execution
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty();
}
public Faculty() {
System.out.println("(4) Faculty's no-arg constructor is invoked");
}
}
class Employee extends Person {
public Employee() {
this("(2) Invoke Employee’s overloaded constructor");
System.out.println("(3) Employee's no-arg constructor is invoked");
}
public Employee(String s) {
System.out.println(s);
}
}
8. Execute println
class Person {
public Person() {
System.out.println("(1) Person's no-arg constructor is invoked");
}
}
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
17
18. animation
Trace Execution
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty();
}
public Faculty() {
System.out.println("(4) Faculty's no-arg constructor is invoked");
}
}
9. Execute println
class Employee extends Person {
public Employee() {
this("(2) Invoke Employee’s overloaded constructor");
System.out.println("(3) Employee's no-arg constructor is invoked");
}
public Employee(String s) {
System.out.println(s);
}
}
class Person {
public Person() {
System.out.println("(1) Person's no-arg constructor is invoked");
}
}
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
18
19. Example on the Impact of a Superclass
without no-arg Constructor
Find out the errors in the program:
public class Apple extends Fruit {
}
class Fruit {
public Fruit(String name) {
System.out.println("Fruit's constructor is invoked");
}
}
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
19
20. Defining a Subclass
A subclass inherits from a superclass. You can also:
Add new properties
Add new methods
Override the methods of the superclass
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
20
21. Calling Superclass Methods
You could rewrite the printCircle() method in the Circle class as
follows:
public void printCircle() {
System.out.println("The circle is created " +
super.getDateCreated() + " and the radius is " + radius);
}
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
21
22. Overriding Methods in the Superclass
A subclass inherits methods from a superclass. Sometimes it is
necessary for the subclass to modify the implementation of a method
defined in the superclass. This is referred to as method overriding.
public class Circle extends GeometricObject {
// Other methods are omitted
/** Override the toString method defined in GeometricObject */
public String toString() {
return super.toString() + "nradius is " + radius;
}
}
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
22
23. NOTE
An instance method can be overridden only
if it is accessible. Thus a private method
cannot be overridden, because it is not
accessible outside its own class. If a method
defined in a subclass is private in its
superclass, the two methods are completely
unrelated.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
23
24. NOTE
Like an instance method, a static method
can be inherited. However, a static method
cannot be overridden. If a static method
defined in the superclass is redefined in a
subclass, the method defined in the
superclass is hidden.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
24
25. Overriding vs. Overloading
public class Test { public class Test {
public static void main(String[] args) { public static void main(String[] args) {
A a = new A(); A a = new A();
a.p(10); a.p(10);
a.p(10.0); a.p(10.0);
} }
} }
class B { class B {
public void p(double i) { public void p(double i) {
System.out.println(i * 2); System.out.println(i * 2);
} }
} }
class A extends B { class A extends B {
// This method overrides the method in B // This method overloads the method in B
public void p(double i) { public void p(int i) {
System.out.println(i); System.out.println(i);
} }
} }
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
25
26. The Object Class and Its Methods
Every class in Java is descended from the
java.lang.Object class. If no inheritance is
specified when a class is defined, the
superclass of the class is Object.
public class Circle { public class Circle extends Object {
... Equivalent
...
} }
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
26
27. The toString() method in Object
The toString() method returns a string representation of the
object. The default implementation returns a string consisting
of a class name of which the object is an instance, the at sign
(@), and a number representing this object.
Loan loan = new Loan();
System.out.println(loan.toString());
The code displays something like Loan@15037e5 . This
message is not very helpful or informative. Usually you should
override the toString method so that it returns a digestible string
representation of the object.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
27
28. Polymorphism, Dynamic Binding and Generic Programming
public class PolymorphismDemo {
public static void main(String[] args) {
m(new GraduateStudent());
Method m takes a parameter
m(new Student()); of the Object type. You can
m(new Person());
m(new Object()); invoke it with any object.
}
public static void m(Object x) { An object of a subtype can be used wherever its
System.out.println(x.toString());
} supertype value is required. This feature is
}
known as polymorphism.
class GraduateStudent extends Student {
}
class Student extends Person { When the method m(Object x) is executed, the
public String toString() {
return "Student";
argument x’s toString method is invoked. x
} may be an instance of GraduateStudent,
}
Student, Person, or Object. Classes
class Person extends Object {
public String toString() {
GraduateStudent, Student, Person, and Object
return "Person"; have their own implementation of the toString
}
} method. Which implementation is used will be
determined dynamically by the Java Virtual
DynamicBindingDemo Machine at runtime. This capability is known
as dynamic binding.
Run
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
28
29. Dynamic Binding
Dynamic binding works as follows: Suppose an object o is an
instance of classes C1, C2, ..., Cn-1, and Cn, where C1 is a subclass
of C2, C2 is a subclass of C3, ..., and Cn-1 is a subclass of Cn. That
is, Cn is the most general class, and C1 is the most specific class.
In Java, Cn is the Object class. If o invokes a method p, the JVM
searches the implementation for the method p in C1, C2, ..., Cn-1
and Cn, in this order, until it is found. Once an implementation is
found, the search stops and the first-found implementation is
invoked.
Cn Cn-1 ..... C2 C1
Since o is an instance of C1, o is also an
Object instance of C2, C3, …, Cn-1, and Cn
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
29
30. Method Matching vs. Binding
Matching a method signature and binding a method
implementation are two issues. The compiler finds a
matching method according to parameter type, number
of parameters, and order of the parameters at
compilation time. A method may be implemented in
several subclasses. The Java Virtual Machine
dynamically binds the implementation of the method at
runtime.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
30
31. Generic Programming
public class PolymorphismDemo { Polymorphism allows methods to be used
public static void main(String[] args) {
m(new GraduateStudent()); generically for a wide range of object
m(new Student()); arguments. This is known as generic
m(new Person());
m(new Object()); programming. If a method’s parameter
} type is a superclass (e.g., Object), you
public static void m(Object x) { may pass an object to this method of any
}
System.out.println(x.toString()); of the parameter’s subclasses (e.g.,
} Student or String). When an object (e.g., a
class GraduateStudent extends Student {
Student object or a String object) is used
} in the method, the particular
class Student extends Person {
implementation of the method of the
public String toString() { object that is invoked (e.g., toString) is
return "Student"; determined dynamically.
}
}
class Person extends Object {
public String toString() {
return "Person";
}
}
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
31
32. Casting Objects
You have already used the casting operator to convert variables of
one primitive type to another. Casting can also be used to convert an
object of one class type to another within an inheritance hierarchy. In
the preceding section, the statement
m(new Student());
assigns the object new Student() to a parameter of the Object type.
This statement is equivalent to:
Object o = new Student(); // Implicit casting
m(o);
The statement Object o = new Student(), known as
implicit casting, is legal because an instance of
Student is automatically an instance of Object.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
32
33. Why Casting Is Necessary?
Suppose you want to assign the object reference o to a variable of the
Student type using the following statement:
Student b = o;
A compile error would occur. Why does the statement Object o =
new Student() work and the statement Student b = o doesn’t? This is
because a Student object is always an instance of Object, but an
Object is not necessarily an instance of Student. Even though you can
see that o is really a Student object, the compiler is not so clever to
know it. To tell the compiler that o is a Student object, use an explicit
casting. The syntax is similar to the one used for casting among
primitive data types. Enclose the target object type in parentheses and
place it before the object to be cast, as follows:
Student b = (Student)o; // Explicit casting
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
33
34. Casting from
Superclass to Subclass
Explicit casting must be used when casting an
object from a superclass to a subclass. This type
of casting may not always succeed.
Apple x = (Apple)fruit;
Orange x = (Orange)fruit;
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
34
35. The instanceof Operator
Use the instanceof operator to test whether an object is an instance
of a class:
Object myObject = new Circle();
... // Some lines of code
/** Perform casting if myObject is an instance of
Circle */
if (myObject instanceof Circle) {
System.out.println("The circle diameter is " +
((Circle)myObject).getDiameter());
...
}
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
35
36. TIP
To help understand casting, you may also
consider the analogy of fruit, apple, and
orange with the Fruit class as the superclass
for Apple and Orange. An apple is a fruit, so
you can always safely assign an instance of
Apple to a variable for Fruit. However, a
fruit is not necessarily an apple, so you have
to use explicit casting to assign an instance
of Fruit to a variable of Apple.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
36
37. Example: Demonstrating
Polymorphism and Casting
This example creates two geometric objects: a
circle, and a rectangle, invokes the
displayGeometricObject method to display the
objects. The displayGeometricObject displays
the area and diameter if the object is a circle, and
displays area if the object is a rectangle.
CastingDemo Run
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
37
38. The equals Method
The equals() method compares the
contents of two objects. The default implementation of the
equals method in the Object class is as follows:
public boolean equals(Object obj) {
return (this == obj);
}
public boolean equals(Object o) {
For example, the if (o instanceof Circle) {
equals method is return radius == ((Circle)o).radius;
overridden in }
the Circle else
return false;
class. }
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
38
39. NOTE
The == comparison operator is used for
comparing two primitive data type values or for
determining whether two objects have the same
references. The equals method is intended to
test whether two objects have the same
contents, provided that the method is modified
in the defining class of the objects. The ==
operator is stronger than the equals method, in
that the == operator checks whether the two
reference variables refer to the same object.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
39
40. The ArrayList Class
You can create an array to store objects. But the array’s size is fixed
once the array is created. Java provides the ArrayList class that can
be used to store an unlimited number of objects.
java.util.ArrayList<E>
+ArrayList() Creates an empty list.
+add(o: E) : void Appends a new element o at the end of this list.
+add(index: int, o: E) : void Adds a new element o at the specified index in this list.
+clear(): void Removes all the elements from this list.
+contains(o: Object): boolean Returns true if this list contains the element o.
+get(index: int) : E Returns the element from this list at the specified index.
+indexOf(o: Object) : int Returns the index of the first matching element in this list.
+isEmpty(): boolean Returns true if this list contains no elements.
+lastIndexOf(o: Object) : int Returns the index of the last matching element in this list.
+remove(o: Object): boolean Removes the element o from this list.
+size(): int Returns the number of elements in this list.
+remove(index: int) : boolean Removes the element at the specified index.
+set(index: int, o: E) : E Sets the element at the specified index.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
40
41. Generic Type
ArrayList is known as a generic class with a generic
type E. You can specify a concrete type to replace E
when creating an ArrayList. For example, the
following statement creates an ArrayList and assigns
its reference to variable cities. This ArrayList object
can be used to store strings.
ArrayList<String> cities = new ArrayList<String>();
TestArrayList Run
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
41
42. Differences and Similarities between
Arrays and ArrayList
Operation Array ArrayList
Creating an array/ArrayList String[] a = new String[10] ArrayList<String> list = new ArrayList<>();
Accessing an element a[index] list.get(index);
Updating an element a[index] = "London"; list.set(index, "London");
Returning size a.length list.size();
Adding a new element list.add("London");
Inserting a new element list.add(index, "London");
Removing an element list.remove(index);
Removing an element list.remove(Object);
Removing all elements list.clear();
DistinctNumbers Run
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
42
43. The MyStack Classes
A stack to hold objects.
MyStack
MyStack
-list: ArrayList A list to store elements.
+isEmpty(): boolean Returns true if this stack is empty.
+getSize(): int Returns the number of elements in this stack.
+peek(): Object Returns the top element in this stack.
+pop(): Object Returns and removes the top element in this stack.
+push(o: Object): void Adds a new element to the top of this stack.
+search(o: Object): int Returns the position of the first element in the stack from
the top that matches the specified element.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
43
44. The protected Modifier
The protected modifier can be applied on data
and methods in a class. A protected data or a
protected method in a public class can be accessed
by any class in the same package or its subclasses,
even if the subclasses are in a different package.
private, default, protected, public
Visibility increases
private, none (if no modifier is used), protected, public
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
44
45. Accessibility Summary
Modifier Accessed Accessed Accessed Accessed
on members from the from the from a from a different
in a class same class same package subclass package
public
protected -
default - -
private - - -
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
45
46. Visibility Modifiers
package p1;
public class C1 { public class C2 {
public int x; C1 o = new C1();
protected int y; can access o.x;
int z; can access o.y;
private int u; can access o.z;
cannot access o.u;
protected void m() {
} can invoke o.m();
} }
package p2;
public class C3 public class C4 public class C5 {
extends C1 { extends C1 { C1 o = new C1();
can access x; can access x; can access o.x;
can access y; can access y; cannot access o.y;
can access z; cannot access z; cannot access o.z;
cannot access u; cannot access u; cannot access o.u;
can invoke m(); can invoke m(); cannot invoke o.m();
} } }
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
46
47. A Subclass Cannot Weaken the Accessibility
A subclass may override a protected
method in its superclass and change its
visibility to public. However, a subclass
cannot weaken the accessibility of a
method defined in the superclass. For
example, if a method is defined as public
in the superclass, it must be defined as
public in the subclass.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
47
48. NOTE
The modifiers are used on classes and
class members (data and methods), except
that the final modifier can also be used on
local variables in a method. A final local
variable is a constant inside a method.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
48
49. The final Modifier
The final class cannot be extended:
final class Math {
...
}
The final variable is a constant:
final static double PI = 3.14159;
The final method cannot be
overridden by its subclasses.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
49