CONSTRUCTOR & Description. String() This initializes a newly created String object so that it represents an empty character sequence.

Size: px
Start display at page:

Download "CONSTRUCTOR & Description. String() This initializes a newly created String object so that it represents an empty character sequence."

Transcription

1 Constructor in Java 1. What are CONSTRUCTORs? Constructor in java is a special type of method that is used to initialize the object. Java constructor is invoked at the time of object creation. It constructs the values i.e. provides data for the object that is why it is known as constructor. CONSTRUCTOR: The sole purpose of having CONSTRUCTORs is to create an instance of a class. They are invoked while creating an object of a class. CONSTRUCTORs can be public, private, or protected. If a CONSTRUCTOR with arguments has been defined in a class, you can no longer use a default no-argument CONSTRUCTOR you have to write one. They are called only once when the class is being instantiated. They must have the same name as the class itself. They do not return a value and you do not have to specify the keyword void. If you do not create a CONSTRUCTOR for the class, Java helps you by using a so called default no-argument CONSTRUCTOR. public class Boss{ Boss(String input) { //This is the CONSTRUCTOR name = "Our Boss is also known as : " + input; public static void main(string args[]) { Boss p1 = new Boss("Super-Man"); CONSTRUCTOR overloading: passing different number and type of variables as arguments all of which are private variables of the class. Example snippet could be as follows: public class Boss{ Boss(String input) { //This is the CONSTRUCTOR name = "Our Boss is also known as : " + input; Boss() { name = "Our Boss is a nice man. We don t call him names. ; public static void main(string args[]) { Boss p1 = new Boss("Super-Man"); Boss p2 = new Boss(); 2. What are Class CONSTRUCTORs S.N. 1 2 CONSTRUCTOR & Description String() This initializes a newly created String object so that it represents an empty character sequence. String(byte[] bytes) This constructs a new String by decoding the specified array of bytes using the platform's default

2 charset. 3 4 String(byte[] bytes, Charset charset) This constructs a new String by decoding the specified array of bytes using the specified charset. String(byte[] bytes, int offset, int length) This constructs a new String by decoding the specified subarray of bytes using the platform's default charset 3. Wha is a Copy CONSTRUCTOR unlike C++, Java doesn t create a default copy CONSTRUCTOR you have to write your own Following is an example Java program that shows a simple use of copy CONSTRUCTOR. // filename: Main.java class Complex { private double re, im; // A normal parametrized CONSTRUCTOR public Complex(double re, double im) { this.re = re; this.im = im; // copy CONSTRUCTOR Complex(Complex c) { System.out.println("Copy CONSTRUCTOR called"); re = c.re; im = c.im; // Overriding the tostring of Object public String tostring() { return "(" + re + " + " + im + "i)"; public class Main { public static void main(string[] args) { Complex c1 = new Complex(10, 15); // Following involves a copy CONSTRUCTOR call Complex c2 = new Complex(c1); // Note that following doesn't involve a copy CONSTRUCTOR call as // non-primitive variables are just references. Complex c3 = c2;//no new, therefore don t need copy CONSTRUCTOR System.out.println(c2); // tostring() of c2 is called here 4. What are the Rules for creating java constructor There are basically two rules defined for the constructor. 1. Constructor name must be same as its class name 2. Constructor must have no explicit return type

3 5. What are the Types of java constructors There are two types of constructors: 1. Default constructor (no-arg constructor) 2. Parameterized constructor 6. What is a Java Default Constructor A constructor that have no parameter is known as default constructor. 7. What is the Syntax of default constructor: <class_name>(){ 8. Give an Example of default constructor In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time of object creation. class Bike1{ Bike1(){System.out.println("Bike is created"); Bike1 b=new Bike1(); Output: Bike is created Rule: If there is no constructor in a class, compiler automatically creates a default constructor.

4 9. What is the purpose of default constructor? Default constructor provides the default values to the object like 0, null etc. depending on the type. Example of default constructor that displays the default values class Student3{ int id; void display(){system.out.println(id+" "+name); Student3 s1=new Student3(); Student3 s2=new Student3(); s1.display(); s2.display(); Output: 0 null 0 null Explanation:In the above class,you are not creating any constructor so compiler provides you a default constructor.here 0 and null values are provided by default constructor. 10. Java parameterized constructor A constructor that have parameters is known as parameterized constructor. 11. Why use parameterized constructor? Parameterized constructor is used to provide different values to the distinct objects. 12. Example of parameterized constructor In this example, we have created the constructor of Student class that have two parameters. We can have any number of parameters in the constructor. class Student4{ int id; Student4(int i,string n){ id = i; name = n; void display(){system.out.println(id+" "+name); Student4 s1 = new Student4(111,"Karan"); Student4 s2 = new Student4(222,"Aryan"); s1.display(); s2.display();

5 Output: 111 Karan 222 Aryan

6 13. What is Constructor Overloading in Java Constructor overloading is a technique in Java in which a class can have any number of constructors that differ in parameter lists.the compiler differentiates these constructors by taking into account the number of parameters in the list and their type. Example of Constructor Overloading class Student5{ int id; int age; Student5(int i,string n){ id = i; name = n; Student5(int i,string n,int a){ id = i; name = n; age=a; void display(){system.out.println(id+" "+name+" "+age); Student5 s1 = new Student5(111,"Karan"); Student5 s2 = new Student5(222,"Aryan",25); s1.display(); s2.display(); Output: 111 Karan Aryan Differences Between Constructors and Methods The main difference is Constructor used to initialize the state of object must not have return type name same as the class name invoke implicitly compiler provide default constructor chained in particular order method expose the behaviour of object must have return type may or may not the same class name invoke explicitly compiler does't provide called unlimited number of times using the same object 15. What is a Java Copy Constructor

7 There is no copy constructor in java. But, we can copy the values of one object to another like copy constructor in C++. There are many ways to copy the values of one object into another in java. They are: By constructor By assigning the values of one object into another By clone() method of Object class In this example, we are going to copy the values of one object into another using java constructor. class Student6{ int id; Student6(int i,string n){ id = i; name = n; Student6(Student6 s){ id = s.id; name =s.name; void display(){system.out.println(id+" "+name); Student6 s1 = new Student6(111,"Karan"); Student6 s2 = new Student6(s1); s1.display(); s2.display(); Output: 111 Karan 111 Karan 16. Give an example of a Copy CONSTRUCTOR in Java // filename: Main.java class Complex { private double re, im; // A normal parametrized CONSTRUCTOR public Complex(double re, double im) { this.re = re; this.im = im; // copy CONSTRUCTOR Complex(Complex c) { System.out.println("Copy CONSTRUCTOR called"); re = c.re; im = c.im;

8 // Overriding the tostring of Object public String tostring() { return "(" + re + " + " + im + "i)"; public class Main { public static void main(string[] args) { Complex c1 = new Complex(10, 15); // Following involves a copy CONSTRUCTOR call Complex c2 = new Complex(c1); // Note that following doesn't involve a copy CONSTRUCTOR call as // non-primitive variables are just references. Complex c3 = c2; System.out.println(c2); // tostring() of c2 is called here 17. Give an example of copying without a constructor We can copy the values of one object into another by assigning the objects values to another object. In this case, there is no need to create the constructor. class Student7{ int id; Student7(int i,string n){ id = i; name = n; Student7(){ void display(){system.out.println(id+" "+name); Student7 s1 = new Student7(111,"Karan"); Student7 s2 = new Student7(); s2.id=s1.id; s2.name=s1.name; s1.display(); s2.display(); Output: 111 Karan 111 Karan 18. Q) Does constructor return any value? Ans:yes, that is current class instance (You cannot use return type yet it returns a value).

9 19. Can constructor perform other tasks instead of initialization? Yes, like object creation, starting a thread, calling method etc. You can perform any operation in the constructor as you perform in the method. 20. How are this() and super() used with CONSTRUCTORs? this() is used to invoke a CONSTRUCTOR of the same class. super() is used to invoke a superclass CONSTRUCTOR. 21. Calling a CONSTRUCTOR From a CONSTRUCTOR In Java it is possible to call a CONSTRUCTOR from inside another CONSTRUCTOR. When you call a CONSTRUCTOR from inside another CONSTRUCTOR, you use the this keyword to refer to the CONSTRUCTOR. Here is an example of calling one CONSTRUCTOR from within another CONSTRUCTOR in Jav public class Employee { private String firstname = null; private String lastname = null; private int birthyear = 0; public Employee(String first, String last, int year ) { firstname = first; lastname = last; birthyear = year; public Employee(String first, String last){ this(first, last, -1); Notice the second CONSTRUCTOR definition. Inside the body of the CONSTRUCTOR you find this Java statement: this(first, last, -1); The this keyword followed by parentheses and parameters means that another CONSTRUCTOR in the same Java class is being called. Which other CONSTRUCTOR that is being called depends on what parameters you pass to the CONSTRUCTOR call (inside the parentheses after the this keyword). In this example it is the first CONSTRUCTOR in the class that is being called. 22. Calling CONSTRUCTORs in Superclasses In Java a class can extend another class. When a class extends another class it is also said to "inherit" from the class it extends. The class that extends is called the subclass, and the class being extended is called the superclass. A class that extends another class does not inherit its CONSTRUCTORs. However, the subclass must call a CONSTRUCTOR in the superclass inside one of the subclass CONSTRUCTORs! Look at the following two Java classes. The class Car extends (inherits from) the class Vehicle. public class Vehicle { private String regno = null; public Vehicle(String no) {

10 this.regno = no; public class Car extends Vehicle { private String brand = null; public Car(String br, String no) { super(no); this.brand = br; Notice the CONSTRUCTOR in the Car class. It calls the CONSTRUCTOR in the superclass using this Java statement: super(no); Using the keyword super refers to the superclass of the class using the super keyword. When super keyword is followed by parentheses like it is here, it refers to a CONSTRUCTOR in the superclass. In this case it refers to the CONSTRUCTOR in the Vehicle class. Because Car extends Vehicle, the Car CONSTRUCTORs must all call a CONSTRUCTOR in the Vehicle. 23. Java CONSTRUCTOR Access Modifiers For instance, if a CONSTRUCTOR is declared protected then only classes in the same package, or subclasses of that class can call that CONSTRUCTOR. A class can have multiple CONSTRUCTORs, and each CONSTRUCTOR can have its own access modifier. Thus, some CONSTRUCTORs may be available to all classes in your application, while other CONSTRUCTORs are only available to classes in the same package, subclasses, or even only to the class itself (private CONSTRUCTORs). 24. Can a CONSTRUCTOR be made final? No, this is not possible. 25. What's the difference between CONSTRUCTORs and other methods? CONSTRUCTORs must have the same name as the class and cannot return a value. They are only called once while regular methods could be called many times. 26. Can you call one CONSTRUCTOR from another if a class has multiple CONSTRUCTORs? Yes, use this() syntax. 27. Can CONSTRUCTOR be inherited? No, CONSTRUCTOR cannot be inherited. 28. Where and how can you use a private CONSTRUCTOR? Private CONSTRUCTOR is used if you do not want other classes to instantiate the object and to prevent subclassing. 29. What s the point of having a private CONSTRUCTOR? This may be news to you: in Java, it is possible to have a private CONSTRUCTOR. Why one would want to use one is explored below. The private modifier when applied to a CONSTRUCTOR works in much the same way as when applied to a normal method or even an instance variable. Defining a CONSTRUCTOR with the private modifier says that only the native class (as in the class in which the private CONSTRUCTOR is defined) is allowed to create an instance of the class, and no other caller is

11 permitted to do so. There are two possible reasons why one would want to use a private CONSTRUCTOR 3. first is that you don t want any objects of your class to be created at all, and the 4. second is that you only want objects to be created internally as in only created in your class. 30. Private CONSTRUCTORs can prevent creation of objects The other possible reason for using a private CONSTRUCTOR is to prevent object construction entirely. When would it make sense to do something like that? Of course, when creating an object doesn t make sense and this occurs when the class only contains static members. And when a class contains only static members, those members can be accessed using only the class name no instance of the class needs to be created. Java always provides a default, no-argument, public CONSTRUCTOR if no programmerdefined CONSTRUCTOR exists. Creating a private no-argument CONSTRUCTOR essentially prevents the usage of that default CONSTRUCTOR, thereby preventing a caller from creating an instance of the class. Note that the private CONSTRUCTOR may even be empty 31. Can an INTERFACE extend another INTERFACE? Yes an INTERFACE can inherit another INTERFACE, for that matter an INTERFACE can extend more than one INTERFACE. 32. If a method is declared as protected, where may the method is accessed? A protected method may only be accessed by classes or INTERFACES of the same package or by subclasses of the class in which it is declared. 33. What is CONSTRUCTOR chaining and how is it achieved in Java? A child object CONSTRUCTOR always first needs to construct its parent. In Java it is done via an implicit call to the no-args CONSTRUCTOR as the first statement.

this keyword in java javatpoint

this keyword in java javatpoint this keyword in java javatpoint There can be a lot of usage of java this keyword. In java, this is a reference variable that refers to the current object. Usage of java this keyword Here is given the 6

More information

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub Lebanese University Faculty of Science Computer Science BS Degree Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub 2 Crash Course in JAVA Classes A Java

More information

Answer1. Features of Java

Answer1. Features of Java Govt Engineering College Ajmer, Rajasthan Mid Term I (2017-18) Subject: PJ Class: 6 th Sem(IT) M.M:10 Time: 1 hr Q1) Explain the features of java and how java is different from C++. [2] Q2) Explain operators

More information

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming Overview of OOP Object Oriented Programming is a programming method that combines: a) Data b) Instructions for processing that data into a self-sufficient object that can be used within a program or in

More information

Inheritance and Polymorphism

Inheritance and Polymorphism Object Oriented Programming Designed and Presented by Dr. Ayman Elshenawy Elsefy Dept. of Systems & Computer Eng.. Al-Azhar University Website: eaymanelshenawy.wordpress.com Email : eaymanelshenawy@azhar.edu.eg

More information

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity.

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity. OOPS Viva Questions 1. What is OOPS? OOPS is abbreviated as Object Oriented Programming system in which programs are considered as a collection of objects. Each object is nothing but an instance of a class.

More information

Class, Variable, Constructor, Object, Method Questions

Class, Variable, Constructor, Object, Method Questions Class, Variable, Constructor, Object, Method Questions http://www.wideskills.com/java-interview-questions/java-classes-andobjects-interview-questions https://www.careerride.com/java-objects-classes-methods.aspx

More information

ASSIGNMENT NO 13. Objectives: To learn and understand concept of Inheritance in Java

ASSIGNMENT NO 13. Objectives: To learn and understand concept of Inheritance in Java Write a program in Java to create a player class. Inherit the classes Cricket_player, Football_player and Hockey_player from player class. The objective of this assignment is to learn the concepts of inheritance

More information

Chapter 5. Inheritance

Chapter 5. Inheritance Chapter 5 Inheritance Objectives Know the difference between Inheritance and aggregation Understand how inheritance is done in Java Learn polymorphism through Method Overriding Learn the keywords : super

More information

Java Fundamentals (II)

Java Fundamentals (II) Chair of Software Engineering Languages in Depth Series: Java Programming Prof. Dr. Bertrand Meyer Java Fundamentals (II) Marco Piccioni static imports Introduced in 5.0 Imported static members of a class

More information

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor. 3.Constructors and Destructors Develop cpp program to implement constructor and destructor. Constructors A constructor is a special member function whose task is to initialize the objects of its class.

More information

C++ Important Questions with Answers

C++ Important Questions with Answers 1. Name the operators that cannot be overloaded. sizeof,.,.*,.->, ::,? 2. What is inheritance? Inheritance is property such that a parent (or super) class passes the characteristics of itself to children

More information

Inheritance. Transitivity

Inheritance. Transitivity Inheritance Classes can be organized in a hierarchical structure based on the concept of inheritance Inheritance The property that instances of a sub-class can access both data and behavior associated

More information

What is Inheritance?

What is Inheritance? Inheritance 1 Agenda What is and Why Inheritance? How to derive a sub-class? Object class Constructor calling chain super keyword Overriding methods (most important) Hiding methods Hiding fields Type casting

More information

Programming overview

Programming overview Programming overview Basic Java A Java program consists of: One or more classes A class contains one or more methods A method contains program statements Each class in a separate file MyClass defined in

More information

INHERITANCE AND EXTENDING CLASSES

INHERITANCE AND EXTENDING CLASSES INHERITANCE AND EXTENDING CLASSES Java programmers often take advantage of a feature of object-oriented programming called inheritance, which allows programmers to make one class an extension of another

More information

Arrays Classes & Methods, Inheritance

Arrays Classes & Methods, Inheritance Course Name: Advanced Java Lecture 4 Topics to be covered Arrays Classes & Methods, Inheritance INTRODUCTION TO ARRAYS The following variable declarations each allocate enough storage to hold one value

More information

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide AP Computer Science Chapter 10 Implementing and Using Classes Study Guide 1. A class that uses a given class X is called a client of X. 2. Private features of a class can be directly accessed only within

More information

Chapter 6 Introduction to Defining Classes

Chapter 6 Introduction to Defining Classes Introduction to Defining Classes Fundamentals of Java: AP Computer Science Essentials, 4th Edition 1 Objectives Design and implement a simple class from user requirements. Organize a program in terms of

More information

Instance Members and Static Members

Instance Members and Static Members Instance Members and Static Members You may notice that all the members are declared w/o static. These members belong to some specific object. They are called instance members. This implies that these

More information

20 Most Important Java Programming Interview Questions. Powered by

20 Most Important Java Programming Interview Questions. Powered by 20 Most Important Java Programming Interview Questions Powered by 1. What's the difference between an interface and an abstract class? An abstract class is a class that is only partially implemented by

More information

Name Return type Argument list. Then the new method is said to override the old one. So, what is the objective of subclass?

Name Return type Argument list. Then the new method is said to override the old one. So, what is the objective of subclass? 1. Overriding Methods A subclass can modify behavior inherited from a parent class. A subclass can create a method with different functionality than the parent s method but with the same: Name Return type

More information

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University CS5000: Foundations of Programming Mingon Kang, PhD Computer Science, Kennesaw State University Inheritance Three main programming mechanisms that constitute object-oriented programming (OOP) Encapsulation

More information

Java static keyword static keyword

Java static keyword static keyword Java static keyword The static keyword in java is used for memory management mainly. We can apply java static keyword with variables, methods, blocks and nested class. The static keyword belongs to the

More information

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance Contents Topic 04 - Inheritance I. Classes, Superclasses, and Subclasses - Inheritance Hierarchies Controlling Access to Members (public, no modifier, private, protected) Calling constructors of superclass

More information

Java Primer 1: Types, Classes and Operators

Java Primer 1: Types, Classes and Operators Java Primer 1 3/18/14 Presentation for use with the textbook Data Structures and Algorithms in Java, 6th edition, by M. T. Goodrich, R. Tamassia, and M. H. Goldwasser, Wiley, 2014 Java Primer 1: Types,

More information

COMP 110/L Lecture 19. Kyle Dewey

COMP 110/L Lecture 19. Kyle Dewey COMP 110/L Lecture 19 Kyle Dewey Outline Inheritance extends super Method overriding Automatically-generated constructors Inheritance Recap -We talked about object-oriented programming being about objects

More information

1 Shyam sir JAVA Notes

1 Shyam sir JAVA Notes 1 Shyam sir JAVA Notes 1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write

More information

CS260 Intro to Java & Android 03.Java Language Basics

CS260 Intro to Java & Android 03.Java Language Basics 03.Java Language Basics http://www.tutorialspoint.com/java/index.htm CS260 - Intro to Java & Android 1 What is the distinction between fields and variables? Java has the following kinds of variables: Instance

More information

Inheritance and Polymorphism

Inheritance and Polymorphism Inheritance and Polymorphism Dr. M. G. Abbas Malik Assistant Professor Faculty of Computing and IT (North Jeddah Branch) King Abdulaziz University, Jeddah, KSA mgmalik@kau.edu.sa www.sanlp.org/malik/cpit305/ap.html

More information

24. Inheritance. Java. Fall 2009 Instructor: Dr. Masoud Yaghini

24. Inheritance. Java. Fall 2009 Instructor: Dr. Masoud Yaghini 24. Inheritance Java Fall 2009 Instructor: Dr. Masoud Yaghini Outline Superclasses and Subclasses Using the super Keyword Overriding Methods The Object Class References Superclasses and Subclasses Inheritance

More information

Java: introduction to object-oriented features

Java: introduction to object-oriented features Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer Java: introduction to object-oriented features Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer

More information

Programming in Java, 2e Sachin Malhotra Saurabh Choudhary

Programming in Java, 2e Sachin Malhotra Saurabh Choudhary Programming in Java, 2e Sachin Malhotra Saurabh Choudhary Chapter 5 Inheritance Objectives Know the difference between Inheritance and aggregation Understand how inheritance is done in Java Learn polymorphism

More information

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University Day 4 COMP1006/1406 Summer 2016 M. Jason Hinek Carleton University today s agenda assignments questions about assignment 2 a quick look back constructors signatures and overloading encapsulation / information

More information

22. Inheritance. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

22. Inheritance. Java. Summer 2008 Instructor: Dr. Masoud Yaghini 22. Inheritance Java Summer 2008 Instructor: Dr. Masoud Yaghini Outline Superclasses and Subclasses Using the super Keyword Overriding Methods The Object Class References Inheritance Object-oriented programming

More information

INHERITANCE. Spring 2019

INHERITANCE. Spring 2019 INHERITANCE Spring 2019 INHERITANCE BASICS Inheritance is a technique that allows one class to be derived from another A derived class inherits all of the data and methods from the original class Suppose

More information

Inheritance (continued) Inheritance

Inheritance (continued) Inheritance Objectives Chapter 11 Inheritance and Polymorphism Learn about inheritance Learn about subclasses and superclasses Explore how to override the methods of a superclass Examine how constructors of superclasses

More information

Chapter 11 Inheritance and Polymorphism. Motivations. Suppose you will define classes to model circles,

Chapter 11 Inheritance and Polymorphism. Motivations. Suppose you will define classes to model circles, Chapter 11 Inheritance and Polymorphism 1 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

More information

CS-202 Introduction to Object Oriented Programming

CS-202 Introduction to Object Oriented Programming CS-202 Introduction to Object Oriented Programming California State University, Los Angeles Computer Science Department Lecture III Inheritance and Polymorphism Introduction to Inheritance Introduction

More information

Object Orientated Programming Details COMP360

Object Orientated Programming Details COMP360 Object Orientated Programming Details COMP360 The ancestor of every action is a thought. Ralph Waldo Emerson Three Pillars of OO Programming Inheritance Encapsulation Polymorphism Inheritance Inheritance

More information

Inheritance. Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L

Inheritance. Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L Inheritance Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 9.4 1 Inheritance Inheritance allows a software developer to derive

More information

ECE 122. Engineering Problem Solving with Java

ECE 122. Engineering Problem Solving with Java ECE 122 Engineering Problem Solving with Java Lecture 17 Inheritance Overview Problem: Can we create bigger classes from smaller ones without having to repeat information? Subclasses: a class inherits

More information

Questions Answer Key Questions Answer Key Questions Answer Key

Questions Answer Key Questions Answer Key Questions Answer Key Benha University Term: 2 nd (2013/2014) Class: 2 nd Year Students Subject: Object Oriented Programming Faculty of Computers & Informatics Date: 26/4/2014 Time: 1 hours Exam: Mid-Term (C) Name:. Status:

More information

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017 Inheritance Lecture 11 COP 3252 Summer 2017 May 25, 2017 Subclasses and Superclasses Inheritance is a technique that allows one class to be derived from another. A derived class inherits all of the data

More information

CS 251 Intermediate Programming Inheritance

CS 251 Intermediate Programming Inheritance CS 251 Intermediate Programming Inheritance Brooke Chenoweth University of New Mexico Spring 2018 Inheritance We don t inherit the earth from our parents, We only borrow it from our children. What is inheritance?

More information

Questions Answer Key Questions Answer Key Questions Answer Key

Questions Answer Key Questions Answer Key Questions Answer Key Benha University Term: 2 nd (2013/2014) Class: 2 nd Year Students Subject: Object Oriented Programming Faculty of Computers & Informatics Date: 26/4/2014 Time: 1 hours Exam: Mid-Term (B) Name:. Status:

More information

Tutorial 7. If it compiles, what does it print? Inheritance 1. Inheritance 2

Tutorial 7. If it compiles, what does it print? Inheritance 1. Inheritance 2 Tutorial 7 If it compiles, what does it print? Here are some exercises to practice inheritance concepts, specifically, overriding, overloading, abstract classes, constructor chaining and polymorphism.

More information

Questions Answer Key Questions Answer Key Questions Answer Key

Questions Answer Key Questions Answer Key Questions Answer Key Benha University Term: 2 nd (2013/2014) Class: 2 nd Year Students Subject: Object Oriented Programming Faculty of Computers & Informatics Date: 26/4/2014 Time: 1 hours Exam: Mid-Term (A) Name:. Status:

More information

Accelerating Information Technology Innovation

Accelerating Information Technology Innovation Accelerating Information Technology Innovation http://aiti.mit.edu Cali, Colombia Summer 2012 Lesson 09 Inheritance What is Inheritance? In the real world: We have general terms for objects in the real

More information

Starting Out with Java: From Control Structures Through Objects Sixth Edition

Starting Out with Java: From Control Structures Through Objects Sixth Edition Starting Out with Java: From Control Structures Through Objects Sixth Edition Chapter 10 Inheritance Chapter Topics (1 of 2) 10.1 What Is Inheritance? 10.2 Calling the Superclass Constructor 10.3 Overriding

More information

Declarations and Access Control SCJP tips

Declarations and Access Control  SCJP tips Declarations and Access Control www.techfaq360.com SCJP tips Write code that declares, constructs, and initializes arrays of any base type using any of the permitted forms both for declaration and for

More information

CS1150 Principles of Computer Science Objects and Classes

CS1150 Principles of Computer Science Objects and Classes CS1150 Principles of Computer Science Objects and Classes Yanyan Zhuang Department of Computer Science http://www.cs.uccs.edu/~yzhuang CS1150 UC. Colorado Springs Object-Oriented Thinking Chapters 1-8

More information

Constructor in Java. What is a Constructor? Rules for create a Java Constructor

Constructor in Java. What is a Constructor? Rules for create a Java Constructor Constructor in Java What is a Constructor? A constructor is a special method that is used to initialize a newly created object and is called just after the memory is allocated for the object. It can be

More information

What are the characteristics of Object Oriented programming language?

What are the characteristics of Object Oriented programming language? What are the various elements of OOP? Following are the various elements of OOP:- Class:- A class is a collection of data and the various operations that can be performed on that data. Object- This is

More information

Java Object Oriented Design. CSC207 Fall 2014

Java Object Oriented Design. CSC207 Fall 2014 Java Object Oriented Design CSC207 Fall 2014 Design Problem Design an application where the user can draw different shapes Lines Circles Rectangles Just high level design, don t write any detailed code

More information

COLLEGE OF ENGINEERING, NASHIK

COLLEGE OF ENGINEERING, NASHIK Pune Vidyarthi Griha s COLLEGE OF ENGINEERING, NASHIK 3. Core Java Computer Dept. 30 th June 2017 Agenda 1. What is JAVA? 2. Features of Java 3. Hello World Program 4. Brief Concept JDK, JRE and JVM 5.

More information

Rules and syntax for inheritance. The boring stuff

Rules and syntax for inheritance. The boring stuff Rules and syntax for inheritance The boring stuff The compiler adds a call to super() Unless you explicitly call the constructor of the superclass, using super(), the compiler will add such a call for

More information

M301: Software Systems & their Development. Unit 4: Inheritance, Composition and Polymorphism

M301: Software Systems & their Development. Unit 4: Inheritance, Composition and Polymorphism Block 1: Introduction to Java Unit 4: Inheritance, Composition and Polymorphism Aims of the unit: Study and use the Java mechanisms that support reuse, in particular, inheritance and composition; Analyze

More information

COP 3330 Final Exam Review

COP 3330 Final Exam Review COP 3330 Final Exam Review I. The Basics (Chapters 2, 5, 6) a. comments b. identifiers, reserved words c. white space d. compilers vs. interpreters e. syntax, semantics f. errors i. syntax ii. run-time

More information

Example: Count of Points

Example: Count of Points Example: Count of Points 1 class Point { 2... 3 private static int numofpoints = 0; 4 5 Point() { 6 numofpoints++; 7 } 8 9 Point(int x, int y) { 10 this(); // calling the constructor with no input argument;

More information

Lecture 02, Fall 2018 Friday September 7

Lecture 02, Fall 2018 Friday September 7 Anatomy of a class Oliver W. Layton CS231: Data Structures and Algorithms Lecture 02, Fall 2018 Friday September 7 Follow-up Python is also cross-platform. What s the advantage of Java? It s true: Python

More information

Darshan Institute of Engineering & Technology for Diploma Studies Unit 3

Darshan Institute of Engineering & Technology for Diploma Studies Unit 3 Class A class is a template that specifies the attributes and behavior of things or objects. A class is a blueprint or prototype from which objects are created. A class is the implementation of an abstract

More information

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved. Assoc. Prof. Marenglen Biba (C) 2010 Pearson Education, Inc. All Inheritance A form of software reuse in which a new class is created by absorbing an existing class s members and enriching them with

More information

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner. HAS-A Relationship Association is a relationship where all objects have their own lifecycle and there is no owner. For example, teacher student Aggregation is a specialized form of association where all

More information

Lecture 2: Java & Javadoc

Lecture 2: Java & Javadoc Lecture 2: Java & Javadoc CS 62 Fall 2018 Alexandra Papoutsaki & William Devanny 1 Instance Variables or member variables or fields Declared in a class, but outside of any method, constructor or block

More information

BBM 102 Introduction to Programming II Spring Inheritance

BBM 102 Introduction to Programming II Spring Inheritance BBM 102 Introduction to Programming II Spring 2018 Inheritance 1 Today Inheritance Notion of subclasses and superclasses protected members UML Class Diagrams for inheritance 2 Inheritance A form of software

More information

Inheritance & Polymorphism Recap. Inheritance & Polymorphism 1

Inheritance & Polymorphism Recap. Inheritance & Polymorphism 1 Inheritance & Polymorphism Recap Inheritance & Polymorphism 1 Introduction! Besides composition, another form of reuse is inheritance.! With inheritance, an object can inherit behavior from another object,

More information

Java. Classes 3/3/2014. Summary: Chapters 1 to 10. Java (2)

Java. Classes 3/3/2014. Summary: Chapters 1 to 10. Java (2) Summary: Chapters 1 to 10 Sharma Chakravarthy Information Technology Laboratory (IT Lab) Computer Science and Engineering Department The University of Texas at Arlington, Arlington, TX 76019 Email: sharma@cse.uta.edu

More information

CSE115 / CSE503 Introduction to Computer Science I. Dr. Carl Alphonce 343 Davis Hall Office hours:

CSE115 / CSE503 Introduction to Computer Science I. Dr. Carl Alphonce 343 Davis Hall Office hours: CSE115 / CSE503 Introduction to Computer Science I Dr. Carl Alphonce 343 Davis Hall alphonce@buffalo.edu Office hours: Thursday 12:00 PM 2:00 PM Friday 8:30 AM 10:30 AM OR request appointment via e-mail

More information

Chapter 10 Inheritance and Polymorphism. Dr. Hikmat Jaber

Chapter 10 Inheritance and Polymorphism. Dr. Hikmat Jaber Chapter 10 Inheritance and Polymorphism Dr. Hikmat Jaber 1 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common features. What is the

More information

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods.

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods. Inheritance Inheritance is the act of deriving a new class from an existing one. Inheritance allows us to extend the functionality of the object. The new class automatically contains some or all methods

More information

Object Oriented Programming. I. Object Based Programming II. Object Oriented Programming

Object Oriented Programming. I. Object Based Programming II. Object Oriented Programming Systems programming Object Oriented Programming I. Object Based Programming II. Object Oriented Programming Telematics Engineering M. Carmen Fernández Panadero mcfp@it.uc3m.es 2010 1

More information

HAS-A Relationship. If A uses B, then it is an aggregation, stating that B exists independently from A.

HAS-A Relationship. If A uses B, then it is an aggregation, stating that B exists independently from A. HAS-A Relationship Association is a weak relationship where all objects have their own lifetime and there is no ownership. For example, teacher student; doctor patient. If A uses B, then it is an aggregation,

More information

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson Introduction History, Characteristics of Java language Java Language Basics Data types, Variables, Operators and Expressions Anatomy of a Java Program

More information

More Relationships Between Classes

More Relationships Between Classes More Relationships Between Classes Inheritance: passing down states and behaviors from the parents to their children Interfaces: grouping the methods, which belongs to some classes, as an interface to

More information

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014 Lesson 10A OOP Fundamentals By John B. Owen All rights reserved 2011, revised 2014 Table of Contents Objectives Definition Pointers vs containers Object vs primitives Constructors Methods Object class

More information

Inheritance. Benefits of Java s Inheritance. 1. Reusability of code 2. Code Sharing 3. Consistency in using an interface. Classes

Inheritance. Benefits of Java s Inheritance. 1. Reusability of code 2. Code Sharing 3. Consistency in using an interface. Classes Inheritance Inheritance is the mechanism of deriving new class from old one, old class is knows as superclass and new class is known as subclass. The subclass inherits all of its instances variables and

More information

Chapter 4 Defining Classes I

Chapter 4 Defining Classes I Chapter 4 Defining Classes I This chapter introduces the idea that students can create their own classes and therefore their own objects. Introduced is the idea of methods and instance variables as the

More information

Pieter van den Hombergh Thijs Dorssers Stefan Sobek. February 10, 2017

Pieter van den Hombergh Thijs Dorssers Stefan Sobek. February 10, 2017 Inheritance and Inheritance and Pieter van den Hombergh Thijs Dorssers Stefan Sobek Fontys Hogeschool voor Techniek en Logistiek February 10, 2017 /FHTenL Inheritance and February 10, 2017 1/45 Topics

More information

Distributed Systems Recitation 1. Tamim Jabban

Distributed Systems Recitation 1. Tamim Jabban 15-440 Distributed Systems Recitation 1 Tamim Jabban Office Hours Office 1004 Tuesday: 9:30-11:59 AM Thursday: 10:30-11:59 AM Appointment: send an e-mail Open door policy Java: Object Oriented Programming

More information

F I N A L E X A M I N A T I O N

F I N A L E X A M I N A T I O N Faculty Of Computer Studies M257 Putting Java to Work F I N A L E X A M I N A T I O N Number of Exam Pages: (including this cover sheet( Spring 2011 April 4, 2011 ( 5 ) Time Allowed: ( 1.5 ) Hours Student

More information

Classes and Inheritance Extending Classes, Chapter 5.2

Classes and Inheritance Extending Classes, Chapter 5.2 Classes and Inheritance Extending Classes, Chapter 5.2 Dr. Yvon Feaster Inheritance Inheritance defines a relationship among classes. Key words often associated with inheritance are extend and implements.

More information

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved. Java How to Program, 10/e Education, Inc. All Rights Reserved. Each class you create becomes a new type that can be used to declare variables and create objects. You can declare new classes as needed;

More information

OOPs Concepts. 1. Data Hiding 2. Encapsulation 3. Abstraction 4. Is-A Relationship 5. Method Signature 6. Polymorphism 7. Constructors 8.

OOPs Concepts. 1. Data Hiding 2. Encapsulation 3. Abstraction 4. Is-A Relationship 5. Method Signature 6. Polymorphism 7. Constructors 8. OOPs Concepts 1. Data Hiding 2. Encapsulation 3. Abstraction 4. Is-A Relationship 5. Method Signature 6. Polymorphism 7. Constructors 8. Type Casting Let us discuss them in detail: 1. Data Hiding: Every

More information

OVERRIDING. 7/11/2015 Budditha Hettige 82

OVERRIDING. 7/11/2015 Budditha Hettige 82 OVERRIDING 7/11/2015 (budditha@yahoo.com) 82 What is Overriding Is a language feature Allows a subclass or child class to provide a specific implementation of a method that is already provided by one of

More information

CSCI-142 Exam 1 Review September 25, 2016 Presented by the RIT Computer Science Community

CSCI-142 Exam 1 Review September 25, 2016 Presented by the RIT Computer Science Community CSCI-12 Exam 1 Review September 25, 2016 Presented by the RIT Computer Science Community http://csc.cs.rit.edu 1. Provide a detailed explanation of what the following code does: 1 public boolean checkstring

More information

CS111: PROGRAMMING LANGUAGE II

CS111: PROGRAMMING LANGUAGE II CS111: PROGRAMMING LANGUAGE II Computer Science Department Lecture 4&5: Inheritance Lecture Contents What is Inheritance? Super-class & sub class The object class Using extends keyword @override keyword

More information

Midterm assessment - MAKEUP Fall 2010

Midterm assessment - MAKEUP Fall 2010 M257 MTA Faculty of Computer Studies Information Technology and Computing Date: /1/2011 Duration: 60 minutes 1-Version 1 M 257: Putting Java to Work Midterm assessment - MAKEUP Fall 2010 Student Name:

More information

CISC 3115 TY3. C09a: Inheritance. Hui Chen Department of Computer & Information Science CUNY Brooklyn College. 9/20/2018 CUNY Brooklyn College

CISC 3115 TY3. C09a: Inheritance. Hui Chen Department of Computer & Information Science CUNY Brooklyn College. 9/20/2018 CUNY Brooklyn College CISC 3115 TY3 C09a: Inheritance Hui Chen Department of Computer & Information Science CUNY Brooklyn College 9/20/2018 CUNY Brooklyn College 1 Outline Inheritance Superclass/supertype, subclass/subtype

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

Programming Language Concepts: Lecture 2

Programming Language Concepts: Lecture 2 Programming Language Concepts: Lecture 2 Madhavan Mukund Chennai Mathematical Institute madhavan@cmi.ac.in http://www.cmi.ac.in/~madhavan/courses/pl2009 PLC 2009, Lecture 2, 19 January 2009 Classes and

More information

Static, Final & Memory Management

Static, Final & Memory Management Static, Final & Memory Management The static keyword What if you want to have only one piece of storage regardless of how many objects are created or even no objects are created? What if you need a method

More information

Character Stream : It provides a convenient means for handling input and output of characters.

Character Stream : It provides a convenient means for handling input and output of characters. Be Perfect, Do Perfect, Live Perfect 1 1. What is the meaning of public static void main(string args[])? public keyword is an access modifier which represents visibility, it means it is visible to all.

More information

Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University

Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University Lecture 3 COMP1006/1406 (the Java course) Summer 2014 M. Jason Hinek Carleton University today s agenda assignments 1 (graded) & 2 3 (available now) & 4 (tomorrow) a quick look back primitive data types

More information

ENCAPSULATION AND POLYMORPHISM

ENCAPSULATION AND POLYMORPHISM MODULE 3 ENCAPSULATION AND POLYMORPHISM Objectives > After completing this lesson, you should be able to do the following: Use encapsulation in Java class design Model business problems using Java classes

More information

Inheritance Motivation

Inheritance Motivation Inheritance Inheritance Motivation Inheritance in Java is achieved through extending classes Inheritance enables: Code re-use Grouping similar code Flexibility to customize Inheritance Concepts Many real-life

More information

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS PAUL L. BAILEY Abstract. This documents amalgamates various descriptions found on the internet, mostly from Oracle or Wikipedia. Very little of this

More information

Data Structures (list, dictionary, tuples, sets, strings)

Data Structures (list, dictionary, tuples, sets, strings) Data Structures (list, dictionary, tuples, sets, strings) Lists are enclosed in brackets: l = [1, 2, "a"] (access by index, is mutable sequence) Tuples are enclosed in parentheses: t = (1, 2, "a") (access

More information

JAVA OBJECT-ORIENTED PROGRAMMING

JAVA OBJECT-ORIENTED PROGRAMMING SE2205B - DATA STRUCTURES AND ALGORITHMS JAVA OBJECT-ORIENTED PROGRAMMING Kevin Brightwell Thursday January 12th, 2017 Acknowledgements:Dr. Quazi Rahman 1 / 36 LECTURE OUTLINE Composition Inheritance The

More information

COMP 250 Fall inheritance Nov. 17, 2017

COMP 250 Fall inheritance Nov. 17, 2017 Inheritance In our daily lives, we classify the many things around us. The world has objects like dogs and cars and food and we are familiar with talking about these objects as classes Dogs are animals

More information