The document discusses basic object-oriented concepts in Java such as classes, objects, inheritance, and polymorphism. Some key points include:
- An object contains both data fields that represent its state and methods that operate on that data.
- A class defines the fields and methods common to all objects of that type. An object is an instance of a class.
- Inheritance allows subclasses to inherit and extend the functionality of parent classes. Subclass objects inherit all fields and methods of their parent classes.
- Methods can be overridden in subclasses to allow polymorphic behavior depending on an object's type. Sending a message to an object results in the execution of the corresponding method definition for that object's class.
This document discusses basic object-oriented programming concepts. It explains that an object contains both data and methods that manipulate that data. An object represents a real-world entity and has state represented by its data fields. Classes describe objects and act as templates for creating multiple similar objects. Objects inherit characteristics from their classes and can override methods. Constructors are used to create and initialize new objects. Access control determines which parts of a class are visible and accessible to other classes.
Infocampus Offers best Java training in Bangalore. Infocampus provides java classes with real time practical sessions. We are conducting weekdays and weekend classes and we have good infrastructure. Easy installments. 100% Placement assistance. Experienced trainers. If you are looking for training with placement assistance please do reach us @ 9738001024.visit: http://infocampus.co.in/java-training-bangalore.html
An object contains both data and methods that manipulate that data. The data represents the state of the object. Classes describe objects by defining their fields and methods. Objects inherit fields and methods from their superclass. To create an object, the appropriate constructor must be called using the new keyword. Access control determines which fields and methods are accessible to other classes.
An object has both data fields that represent its state and methods that can manipulate that state. A class defines the fields and methods for any objects instantiated from that class. Constructors are used to create objects from classes and ensure their fields are initialized properly. Inheritance allows subclasses to inherit fields and methods from their parent classes while also adding their own fields and methods.
An object contains both data and methods that manipulate that data. The data represent the state of the object. Classes describe objects by defining their fields and methods. Objects inherit fields and methods from their superclass and belong to a class. Constructors are used to create objects and initialize their fields. Access control determines which fields and methods are accessible to other classes.
An object has both data and methods that manipulate that data. The data represents the state of the object. A class describes the fields and methods of objects that belong to that class. Classes form a hierarchy where subclasses inherit fields and methods from their parent classes. Objects must be created from their classes using constructors before their fields and methods can be accessed.
It contains basic fundamental of class, object, method overloading, constructor, destructor, visibility, acess specifier, Methods, overloading, clonning of objects etc. are covered here.
Kindly look at it and give your comments to improve it as good as possible ways.
The document discusses key concepts in object-oriented programming in Java including classes, objects, methods, constructors, and inheritance. Specifically, it explains that in Java, classes define the structure and behavior of objects through fields and methods. Objects are instances of classes that allocate memory at runtime. Methods define the behaviors of objects, and constructors initialize objects during instantiation. Inheritance allows classes to extend the functionality of other classes.
This document discusses basic object-oriented programming concepts. It explains that an object contains both data and methods that manipulate that data. An object represents a real-world entity and has state represented by its data fields. Classes describe objects and act as templates for creating multiple similar objects. Objects inherit characteristics from their classes and can override methods. Constructors are used to create and initialize new objects. Access control determines which parts of a class are visible and accessible to other classes.
Infocampus Offers best Java training in Bangalore. Infocampus provides java classes with real time practical sessions. We are conducting weekdays and weekend classes and we have good infrastructure. Easy installments. 100% Placement assistance. Experienced trainers. If you are looking for training with placement assistance please do reach us @ 9738001024.visit: http://infocampus.co.in/java-training-bangalore.html
An object contains both data and methods that manipulate that data. The data represents the state of the object. Classes describe objects by defining their fields and methods. Objects inherit fields and methods from their superclass. To create an object, the appropriate constructor must be called using the new keyword. Access control determines which fields and methods are accessible to other classes.
An object has both data fields that represent its state and methods that can manipulate that state. A class defines the fields and methods for any objects instantiated from that class. Constructors are used to create objects from classes and ensure their fields are initialized properly. Inheritance allows subclasses to inherit fields and methods from their parent classes while also adding their own fields and methods.
An object contains both data and methods that manipulate that data. The data represent the state of the object. Classes describe objects by defining their fields and methods. Objects inherit fields and methods from their superclass and belong to a class. Constructors are used to create objects and initialize their fields. Access control determines which fields and methods are accessible to other classes.
An object has both data and methods that manipulate that data. The data represents the state of the object. A class describes the fields and methods of objects that belong to that class. Classes form a hierarchy where subclasses inherit fields and methods from their parent classes. Objects must be created from their classes using constructors before their fields and methods can be accessed.
It contains basic fundamental of class, object, method overloading, constructor, destructor, visibility, acess specifier, Methods, overloading, clonning of objects etc. are covered here.
Kindly look at it and give your comments to improve it as good as possible ways.
The document discusses key concepts in object-oriented programming in Java including classes, objects, methods, constructors, and inheritance. Specifically, it explains that in Java, classes define the structure and behavior of objects through fields and methods. Objects are instances of classes that allocate memory at runtime. Methods define the behaviors of objects, and constructors initialize objects during instantiation. Inheritance allows classes to extend the functionality of other classes.
This document summarizes a lecture on object-oriented programming concepts including classes, methods, constructors, and objects.
The lecture covered:
1) The components of a class including fields, methods, and constructors. Main(), setter, and getter methods were discussed.
2) How to call methods within the same class and between different classes.
3) How to create objects from classes and how messages are sent to objects to invoke their methods.
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.
Batra Computer Centre is An ISO certified 9001:2008 training Centre in Ambala.
We Provide Computer Training in Ambala. BATRA COMPUTER CENTRE provides best training in C, C++, S.E.O, Web Designing, Web Development and So many other courses are available.
The document discusses object-oriented concepts in Java including objects, classes, constructors, encapsulation, and Java source file layout. It defines objects as anything real or conceptual and classes as blueprints for objects. Constructors are special methods that initialize objects. Encapsulation hides implementation details and protects data using private attributes with public getters and setters. The Java source file layout follows a PIC order of package, import, classes. It also discusses creating JAR files to package related class files together.
The document discusses constructors in Java. It defines constructors as special methods that initialize objects. Constructors are invoked during object creation and provide initial values for object fields. The document covers default constructors that provide default values if no constructor is defined, parameterized constructors that initialize fields with passed in values, and constructor overloading which allows multiple constructors with different parameters. It provides examples of each type of constructor.
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.
This document discusses objects and classes in Java. It begins by defining what a class is - a template that defines common properties of objects. Everything in a Java program must be encapsulated within a class. A class defines an object's state via fields and behavior via methods. The document then discusses how to define classes by specifying fields, methods, and constructors. It provides examples of creating objects from classes and accessing object members. The document also covers key object-oriented programming concepts like encapsulation and inheritance.
This document summarizes key concepts in object-oriented programming (OOP) in Java, including static keyword, instance member, class member, inheritance, encapsulation, polymorphism, object, class, constructor, and more. It provides examples to illustrate static variables and methods, the this keyword, super keyword, final keyword, abstract classes vs interfaces, and method overloading as a form of compile-time polymorphism.
This document provides an overview of object-oriented programming (OOP) concepts in Java, including classes, objects, inheritance, encapsulation, polymorphism, and dynamic binding. It explains the basic structure of a Java class, how to define methods and variables, and how to instantiate objects from classes. The document also discusses constructors and how to use inheritance to extend existing classes.
Hlutbundin forritun er öflug leið til að búa til hugbúnað. Hins vegar er auðvelt að gleyma eiginleikum hlutbundinna mála. Í þessum fyrri hluta um þetta efni munum við rifja upp hugtök eins og encapsulation, skil og polymorphma. Við munum líka skoða nokkur prinsipp eins og Separtaion of Concern (SoC).
Í þessu fyrirlestri mun ég upplýsa leyndarmál sem aðeins góðir forritarar vita.
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...Sagar Verma
OOPS and its application in Java, Super class AND This Keyword,Java Bean, POJO ,Memory management in Java ,Packages ,Miscellaneous (Var-Args, toString(), Double equals operator(==))
C/C++ Programming interview questions and answers document discusses key concepts in C++ including encapsulation, inheritance, polymorphism, constructors, destructors, copy constructors, references, virtual functions, abstract classes, and memory alignment. The document provides definitions and examples to explain each concept.
Chap 3 Python Object Oriented Programming - Copy.pptmuneshwarbisen1
The document discusses object oriented programming concepts in Python including classes, objects, instances, methods, inheritance, and class attributes. It provides examples of defining classes, instantiating objects, using methods, and the difference between class and instance attributes. Key concepts covered include defining classes with the class keyword, creating object instances, using the __init__() method for initialization, and allowing derived classes to inherit from base classes.
Encapsulation isolates the internal complexity of an object's operation from the rest of the application. Inheritance allows one class to reuse the state and behavior of another class. Polymorphism allows a client to treat different objects in the same way even if they were created from different classes and exhibit different behaviors.
This document provides an overview of inheritance in object-oriented programming. It defines inheritance as a parent-child relationship between classes that allows code and behavior to be shared. The key terms discussed are superclass/parent class, subclass/child class, and extending/inheriting from another class. The document also covers inheritance in Java using the extends keyword, overriding methods, access modifiers, the super keyword, and runtime type checking with instanceof.
Inheritance allows classes to establish a hierarchical "is-a" relationship where subclasses inherit and extend the functionality of superclasses. A subclass inherits all fields and methods from its direct superclass and inherits from all superclasses up the class hierarchy with Object at the top. Constructors must call superclass constructors to initialize inherited fields properly. Subclasses can override methods of superclasses to provide specialized implementations while preserving the original signature. Polymorphism occurs when subclass objects are referenced by superclass references and the method invoked is based on the object's actual type. Final methods and classes prevent overriding and extension respectively.
The document is a test paper for the course CS2311 - Object-Oriented Programming at PERI INSTITUTE OF TECCHNOLOGY. It contains 15 questions testing concepts related to OOP such as classes, objects, inheritance, polymorphism, operator overloading, templates, and exception handling. It also includes questions about file handling and formatted I/O functions in C++. The test has a duration of 180 minutes and is worth a maximum of 100 marks, divided into multiple choice questions worth 2 marks each (Part A) and longer answer questions worth 16 marks each (Part B).
The document discusses object-oriented programming concepts including encapsulation, composition, inheritance, polymorphism, abstract classes, and interfaces. It provides examples of how these concepts are implemented in C# through classes, inheritance between base and derived classes, abstract methods, and interfaces. It also summarizes key features like polymorphism which allows treating a derived class object as its base class.
This document summarizes a lecture on object-oriented programming concepts including classes, methods, constructors, and objects.
The lecture covered:
1) The components of a class including fields, methods, and constructors. Main(), setter, and getter methods were discussed.
2) How to call methods within the same class and between different classes.
3) How to create objects from classes and how messages are sent to objects to invoke their methods.
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.
Batra Computer Centre is An ISO certified 9001:2008 training Centre in Ambala.
We Provide Computer Training in Ambala. BATRA COMPUTER CENTRE provides best training in C, C++, S.E.O, Web Designing, Web Development and So many other courses are available.
The document discusses object-oriented concepts in Java including objects, classes, constructors, encapsulation, and Java source file layout. It defines objects as anything real or conceptual and classes as blueprints for objects. Constructors are special methods that initialize objects. Encapsulation hides implementation details and protects data using private attributes with public getters and setters. The Java source file layout follows a PIC order of package, import, classes. It also discusses creating JAR files to package related class files together.
The document discusses constructors in Java. It defines constructors as special methods that initialize objects. Constructors are invoked during object creation and provide initial values for object fields. The document covers default constructors that provide default values if no constructor is defined, parameterized constructors that initialize fields with passed in values, and constructor overloading which allows multiple constructors with different parameters. It provides examples of each type of constructor.
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.
This document discusses objects and classes in Java. It begins by defining what a class is - a template that defines common properties of objects. Everything in a Java program must be encapsulated within a class. A class defines an object's state via fields and behavior via methods. The document then discusses how to define classes by specifying fields, methods, and constructors. It provides examples of creating objects from classes and accessing object members. The document also covers key object-oriented programming concepts like encapsulation and inheritance.
This document summarizes key concepts in object-oriented programming (OOP) in Java, including static keyword, instance member, class member, inheritance, encapsulation, polymorphism, object, class, constructor, and more. It provides examples to illustrate static variables and methods, the this keyword, super keyword, final keyword, abstract classes vs interfaces, and method overloading as a form of compile-time polymorphism.
This document provides an overview of object-oriented programming (OOP) concepts in Java, including classes, objects, inheritance, encapsulation, polymorphism, and dynamic binding. It explains the basic structure of a Java class, how to define methods and variables, and how to instantiate objects from classes. The document also discusses constructors and how to use inheritance to extend existing classes.
Hlutbundin forritun er öflug leið til að búa til hugbúnað. Hins vegar er auðvelt að gleyma eiginleikum hlutbundinna mála. Í þessum fyrri hluta um þetta efni munum við rifja upp hugtök eins og encapsulation, skil og polymorphma. Við munum líka skoða nokkur prinsipp eins og Separtaion of Concern (SoC).
Í þessu fyrirlestri mun ég upplýsa leyndarmál sem aðeins góðir forritarar vita.
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...Sagar Verma
OOPS and its application in Java, Super class AND This Keyword,Java Bean, POJO ,Memory management in Java ,Packages ,Miscellaneous (Var-Args, toString(), Double equals operator(==))
C/C++ Programming interview questions and answers document discusses key concepts in C++ including encapsulation, inheritance, polymorphism, constructors, destructors, copy constructors, references, virtual functions, abstract classes, and memory alignment. The document provides definitions and examples to explain each concept.
Chap 3 Python Object Oriented Programming - Copy.pptmuneshwarbisen1
The document discusses object oriented programming concepts in Python including classes, objects, instances, methods, inheritance, and class attributes. It provides examples of defining classes, instantiating objects, using methods, and the difference between class and instance attributes. Key concepts covered include defining classes with the class keyword, creating object instances, using the __init__() method for initialization, and allowing derived classes to inherit from base classes.
Encapsulation isolates the internal complexity of an object's operation from the rest of the application. Inheritance allows one class to reuse the state and behavior of another class. Polymorphism allows a client to treat different objects in the same way even if they were created from different classes and exhibit different behaviors.
This document provides an overview of inheritance in object-oriented programming. It defines inheritance as a parent-child relationship between classes that allows code and behavior to be shared. The key terms discussed are superclass/parent class, subclass/child class, and extending/inheriting from another class. The document also covers inheritance in Java using the extends keyword, overriding methods, access modifiers, the super keyword, and runtime type checking with instanceof.
Inheritance allows classes to establish a hierarchical "is-a" relationship where subclasses inherit and extend the functionality of superclasses. A subclass inherits all fields and methods from its direct superclass and inherits from all superclasses up the class hierarchy with Object at the top. Constructors must call superclass constructors to initialize inherited fields properly. Subclasses can override methods of superclasses to provide specialized implementations while preserving the original signature. Polymorphism occurs when subclass objects are referenced by superclass references and the method invoked is based on the object's actual type. Final methods and classes prevent overriding and extension respectively.
The document is a test paper for the course CS2311 - Object-Oriented Programming at PERI INSTITUTE OF TECCHNOLOGY. It contains 15 questions testing concepts related to OOP such as classes, objects, inheritance, polymorphism, operator overloading, templates, and exception handling. It also includes questions about file handling and formatted I/O functions in C++. The test has a duration of 180 minutes and is worth a maximum of 100 marks, divided into multiple choice questions worth 2 marks each (Part A) and longer answer questions worth 16 marks each (Part B).
The document discusses object-oriented programming concepts including encapsulation, composition, inheritance, polymorphism, abstract classes, and interfaces. It provides examples of how these concepts are implemented in C# through classes, inheritance between base and derived classes, abstract methods, and interfaces. It also summarizes key features like polymorphism which allows treating a derived class object as its base class.
Similar to Basic OOPs Concepts (E-next.in).pdf (20)
Temple of Asclepius in Thrace. Excavation resultsKrassimira Luka
The temple and the sanctuary around were dedicated to Asklepios Zmidrenus. This name has been known since 1875 when an inscription dedicated to him was discovered in Rome. The inscription is dated in 227 AD and was left by soldiers originating from the city of Philippopolis (modern Plovdiv).
This presentation was provided by Racquel Jemison, Ph.D., Christina MacLaughlin, Ph.D., and Paulomi Majumder. Ph.D., all of the American Chemical Society, for the second session of NISO's 2024 Training Series "DEIA in the Scholarly Landscape." Session Two: 'Expanding Pathways to Publishing Careers,' was held June 13, 2024.
The chapter Lifelines of National Economy in Class 10 Geography focuses on the various modes of transportation and communication that play a vital role in the economic development of a country. These lifelines are crucial for the movement of goods, services, and people, thereby connecting different regions and promoting economic activities.
Andreas Schleicher presents PISA 2022 Volume III - Creative Thinking - 18 Jun...EduSkills OECD
Andreas Schleicher, Director of Education and Skills at the OECD presents at the launch of PISA 2022 Volume III - Creative Minds, Creative Schools on 18 June 2024.
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!"
Gender and Mental Health - Counselling and Family Therapy Applications and In...PsychoTech Services
A proprietary approach developed by bringing together the best of learning theories from Psychology, design principles from the world of visualization, and pedagogical methods from over a decade of training experience, that enables you to: Learn better, faster!
How Barcodes Can Be Leveraged Within Odoo 17Celine George
In this presentation, we will explore how barcodes can be leveraged within Odoo 17 to streamline our manufacturing processes. We will cover the configuration steps, how to utilize barcodes in different manufacturing scenarios, and the overall benefits of implementing this technology.
2. 2
Concept: An object has behaviors
In old style programming, you had:
data, which was completely passive
functions, which could manipulate any data
An object contains both data and methods that
manipulate that data
An object is active, not passive; it does things
An object is responsible for its own data
But: it can expose that data to other objects
https://E-next.in
3. 3
Concept: An object has state
An object contains both data and methods that
manipulate that data
The data represent the state of the object
Data can also describe the relationships between this object
and other objects
Example: A CheckingAccount might have
A balance (the internal state of the account)
An owner (some object representing a person)
https://E-next.in
4. 4
Example: A “Rabbit” object
You could (in a game, for example) create an object
representing a rabbit
It would have data:
How hungry it is
How frightened it is
Where it is
And methods:
eat, hide, run, dig
https://E-next.in
5. 5
Concept: Classes describe objects
Every object belongs to (is an instance of) a class
An object may have fields, or variables
The class describes those fields
An object may have methods
The class describes those methods
A class is like a template, or cookie cutter
You use the class’s constructor to make objects
https://E-next.in
6. 6
Concept: Classes are like Abstract Data Types
An Abstract Data Type (ADT) bundles together:
some data, representing an object or "thing"
the operations on that data
The operations defined by the ADT are the only
operations permitted on its data
Example: a CheckingAccount, with operations
deposit, withdraw, getBalance, etc.
Classes enforce this bundling together
If all data values are private, a class can also enforce the
rule that its defined operations are the only ones permitted
on the data
https://E-next.in
7. 7
Example of a class
class Employee {
// Fields
private String name; //Can get but not change
private double salary; // Cannot get or set
// Constructor
Employee(String n, double s) {
name = n; salary = s;
}
// Methods
void pay () {
System.out.println("Pay to the order of " +
name + " $" + salary);
}
public String getName() { return name; } // getter
}
https://E-next.in
8. 8
Approximate Terminology
instance = object
field = instance variable
method = function
sending a message to an object =
calling a function
These are all approximately true
https://E-next.in
9. 9
Concept: Classes form a hierarchy
Classes are arranged in a treelike structure called a
hierarchy
The class at the root is named Object
Every class, except Object, has a superclass
A class may have several ancestors, up to Object
When you define a class, you specify its superclass
If you don’t specify a superclass, Object is assumed
Every class may have one or more subclasses
https://E-next.in
10. 10
Example of (part of) a hierarchy
A FileDialog is a Dialog is a Window is a Container
Container
Panel ScrollPane Window
Dialog Frame
FileDialog
https://E-next.in
11. 11
C++ is different
In C++ there may be more than one root
but not in Java!
In C++ an object may have more than one parent
(immediate superclass)
but not in Java!
Java has a single, strict hierarchy
https://E-next.in
12. 12
Concept: Objects inherit from superclasses
A class describes fields and methods
Objects of that class have those fields and methods
But an object also inherits:
the fields described in the class's superclasses
the methods described in the class's superclasses
A class is not a complete description of its objects!
https://E-next.in
13. 13
Example of inheritance
class Person {
String name;
int age;
void birthday () {
age = age + 1;
}
}
class Employee
extends Person {
double salary;
void pay () { ...}
}
Every Employee has name and age fields and
birthday method as well as a salary field and a pay
method.
https://E-next.in
14. 14
Concept: Objects must be created
int n; does two things:
It declares that n is an integer variable
It allocates space to hold a value for n
For a primitive, this is all that is needed
Employee secretary; also does two things
It declares that secretary is type Employee
It allocates space to hold a reference to an Employee
For an object, this is not all that is needed
secretary = new Employee ( );
This allocate space to hold a value for the Employee
Until you do this, the Employee is null
https://E-next.in
15. 15
Notation: How to declare and create objects
Employee secretary; // declares secretary
secretary = new Employee (); // allocates space
Employee secretary = new Employee(); // does both
But the secretary is still "blank" (null)
secretary.name = "Adele"; // dot notation
secretary.birthday (); // sends a message
https://E-next.in
16. 16
Notation: How to reference a field or method
Inside a class, no dots are necessary
class Person { ... age = age + 1; ...}
Outside a class, you need to say which object you are
talking to
if (john.age < 75) john.birthday ();
If you don't have an object, you cannot use its fields
or methods!
https://E-next.in
17. 17
Concept: this object
Inside a class, no dots are necessary, because
you are working on this object
If you wish, you can make it explicit:
class Person { ... this.age = this.age + 1; ...}
this is like an extra parameter to the method
You usually don't need to use this
https://E-next.in
18. 18
Concept: A variable can hold subclass objects
Suppose B is a subclass of A
A objects can be assigned to A variables
B objects can be assigned to B variables
B objects can be assigned to A variables, but
A objects can not be assigned to B variables
Every B is also an A but not every A is a B
You can cast: bVariable = (B) aObject;
In this case, Java does a runtime check
https://E-next.in
19. 19
Example: Assignment of subclasses
class Dog { ... }
class Poodle extends Dog { ... }
Dog myDog;
Dog rover = new Dog ();
Poodle yourPoodle;
Poodle fifi = new Poodle ();
myDog = rover; // ok
yourPoodle = fifi; // ok
myDog = fifi; //ok
yourPoodle = rover; // illegal
yourPoodle = (Poodle) rover; //runtime check
https://E-next.in
20. 20
Concept: Methods can be overridden
So birds can fly. Except penguins.
class Bird extends Animal {
void fly (String destination) {
location = destination;
}
}
class Penguin extends Bird {
void fly (String whatever) { }
}
https://E-next.in
21. 21
Concept: Don't call functions, send messages
Bird someBird = pingu;
someBird.fly ("South America");
Did pingu actually go anywhere?
You sent the message fly(...) to pingu
If pingu is a penguin, he ignored it
Otherwise he used the method defined in Bird
You did not directly call any method
You cannot tell, without studying the program, which
method actually gets used
The same statement may result in different methods being
used at different times
https://E-next.in
22. 22
Sneaky trick: How to use overridden methods
class FamilyMember extends Person {
void birthday () { // override birthday() in Person
super.birthday (); // call overridden method
givePresent (); // and add your new stuff
}
}
https://E-next.in
23. 23
Concept: Constructors make objects
Every class has a constructor to make its objects
Use the keyword new to call a constructor
secretary = new Employee ( );
You can write your own constructors; but if you don’t,
Java provides a default constructor with no arguments
It sets all the fields of the new object to zero
If this is good enough, you don’t need to write your own
The syntax for writing constructors is almost like that for
writing methods
https://E-next.in
24. 24
Syntax for constructors
Do not use a return type and a name; use only the
class name
You can supply arguments
Employee (String theName, double theSalary) {
name = theName;
salary = theSalary;
}
https://E-next.in
25. 25
Trick: Give field and parameter the same name
A parameter overrides a field with the same name
But you can use this.name to refer to the field
class Person {
String name;
int age;
Person (String name, int age) {
this.name = name;
this.age = age;
}
}
Using the same name is a common and useful convention
https://E-next.in
26. 26
Internal workings: Constructor chaining
If an Employee is a Person, and a Person is an
Object, then when you say new Employee ()
The Employee constructor calls the Person constructor
The Person constructor calls the Object constructor
The Object constructor creates a new Object
The Person constructor adds its own stuff to the Object
The Employee constructor adds its own stuff to the Person
https://E-next.in
27. 27
The case of the vanishing constructor
If you don't write a constructor for a class, Java provides
one (the default constructor)
The one Java provides has no arguments
If you write any constructor for a class, Java does not
provide a default constructor
Adding a perfectly good constructor can break a
constructor chain
You may need to fix the chain
https://E-next.in
28. 28
Example: Broken constructor chain
class Person {
String name;
Person (String name) {
this.name = name;
}
}
class Employee extends Person {
double salary;
Employee ( ) {
salary = 12.50;
}
}
cannot resolve symbol – constructor Person()
Java tries to execute
an implicit super()
at this point
super();
https://E-next.in
29. 29
Fixing a broken constructor chain
Special syntax: super(...) calls the superclass constructor
When one constructor calls another, that call must be first
class Employee {
double salary;
Employee (String name) {
super(name); // must be first
salary = 12.50;
}
}
Now you can only create Employees with names
This is fair, because you can only create Persons with names
https://E-next.in
30. 30
Trick: one constructor calling another
this(...) calls another constructor for this same class
It is poor style to have the same code more than once
If you call this(...), that call must be the first thing in your
constructor
class Something {
Something (int x, int y, int z) {
// do a lot of work here
}
Something ( ) { this (0, 0, 0); }
}
https://E-next.in
31. 31
Concept: You can control access
class Person {
public String name;
private String age;
protected double salary;
public void birthday { age++; }
}
Each object is responsible for its own data
Access control lets an object protect its data and
its methods
Access control is the subject of a different lecture
https://E-next.in
32. 32
Concept: Classes can have fields and methods
Usually a class describes fields (variables) and
methods for its objects (instances)
These are called instance variables and instance methods
A class can have its own fields and methods
These are called class variables and class methods
There is exactly one copy of a class variable, not
one per object
Use the special keyword static to say that a field
or method belongs to the class instead of to objects
https://E-next.in
33. 33
Example of a class variable
class Person {
String name;
int age;
static int population;
Person (String name) {
this.name = name;
this.age = 0;
population++;
}
}
https://E-next.in
34. 34
Advice: Restrict access
Always, always strive for a narrow interface
Follow the principle of information hiding:
the caller should know as little as possible about how the
method does its job
the method should know little or nothing about where or why
it is being called
Make as much as possible private
Your class is responsible for it’s own data; don’t
allow other classes to screw it up!
https://E-next.in
35. 35
Advice: Use setters and getters
This way the object maintains control
Setters and getters have conventional names: setDataName,
getDataName, isDataName (booleans only)
class Employee extends Person {
private double salary;
private boolean male;
public void setSalary (double newSalary) {
salary = newSalary;
}
public double getSalary () { return salary; }
public boolean isMale() { return male; }
}
https://E-next.in
36. 36
Kinds of access
Java provides four levels of access:
public: available everywhere
protected: available within the package (in the same
subdirectory) and to all subclasses
[default]: available within the package
private: only available within the class itself
The default is called package visibility
In small programs this isn't important...right?
https://E-next.in