Coding Study Guide

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

Package?

A java package is a group of similar types of classes, interfaces and sub-packages. Package in java can be categorized in two form, built-in package and user-defined package. There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.

Object

means a real-world entity such as a pen, chair, table, computer, watch, etc.

"this" : to refer current class instance variable

The this keyword can be used to refer current class instance variable. If there is ambiguity between the instance variables and parameters, this keyword resolves the problem of ambiguity.

"this" : to invoke current class constructor

The this() constructor call can be used to invoke the current class constructor. It is used to reuse the constructor. In other words, it is used for constructor chaining.

Advantages of Inheritance

For Method Overriding (so runtime polymorphism can be achieved). For Code Reusability.

Using packagename.classname

If you import package.classname then only declared class of this package will be accessible.

Advantages of Encapsulation

- By providing only a setter or getter method, you can make the class read-only or write-only. In other words, you can skip the getter or setter methods. - It provides you the control over the data. Suppose you want to set the value of id which should be greater than 100 only, you can write the logic inside the setter method. You can write the logic not to store the negative numbers in the setter methods. - It is a way to achieve data hiding in Java because other class will not be able to access the data through the private data members. - The encapsulate class is easy to test. So, it is better for unit testing.

Terms used in Inheritance

- Class: A class is a group of objects which have common properties. It is a template or blueprint from which objects are created. - Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a derived class, extended class, or child class. - Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It is also called a base class or a parent class. - Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the fields and methods of the existing class when you create a new class. You can use the same fields and methods already defined in the previous class.

Encapsulation

- Encapsulation in Java is a process of wrapping code and data together into a single unit, for example, a capsule which is mixed of several medicines. - We can create a fully encapsulated class in Java by making all the data members of the class private. Now we can use setter and getter methods to set and get the data in it. - The Java Bean class is the example of a fully encapsulated class.

Object Oriented Programming Pillars

- Inheritance - Polymorphism - Encapsulation - Abstraction

Advantages Of Packages

- Java package is used to categorize the classes and interfaces so that they can be easily maintained. - Java package provides access protection. - Java package removes naming collision.

Class

A class, in the context of Java, are templates that are used to create objects, and to define object data types and methods. Core properties include the data types and methods that may be used by the object. A class can also be defined as a blueprint from which you can create an individual object. Class doesn't consume any space.

Do..While Loop

A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time.

For Loop

A for loop is a repetition control structure that allows you to efficiently write a loop that needs to be executed a specific number of times. A for loop is useful when you know how many times a task is to be repeated.

Similarities between an interface and a class

An interface can contain any number of methods. An interface is written in a file with a .java extension, with the name of the interface matching the name of the file. The byte code of an interface appears in a .class file. Interfaces appear in packages, and their corresponding bytecode file must be in a directory structure that matches the package name.

Interface?

An interface is a reference type in Java. It is similar to class. It is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface. Along with abstract methods, an interface may also contain constants, default methods, static methods, and nested types. Method bodies exist only for default methods and static methods. Writing an interface is similar to writing a class. But a class describes the attributes and behaviors of an object. And an interface contains behaviors that a class implements. Unless the class that implements the interface is abstract, all the methods of the interface need to be defined in the class.

Object

Any entity that has state and behavior is known as an object. For example a chair, pen, table, keyboard, bike, etc. It can be physical or logical. An Object can be defined as an instance of a class. An object contains an address and takes up some space in memory. Objects can communicate without knowing the details of each other's data or code. The only necessary thing is the type of message accepted and the type of response returned by the objects. Example: A dog is an object because it has states like color, name, breed, etc. as well as behaviors like wagging the tail, barking, eating, etc.

Enhanced For Loop

As of Java 5, the enhanced for loop was introduced. This is mainly used to traverse a collection of elements including arrays. - Declaration − The newly declared block variable, is of a type compatible with the elements of the array you are accessing. The variable will be available within the for block and its value would be the same as the current array element. - Expression − This evaluates the array you need to loop through. The expression can be an array variable or a method call that returns an array.

Advantages of an Array

Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently. Random access: We can get any data located at an index position

Constructor vs Method

Constructor : - A constructor is used to initialize the state of an object. - A constructor must not have a return type. - The constructor is invoked implicitly. - The Java compiler provides a default constructor if you don't have any constructor in a class. - The constructor name must be the same as the class name. Method : - A method is used to expose the behavior of an object. - A method must have a return type. - The method is invoked explicitly. - The method is not provided by the compiler in any case. - The method name may or may not be the same as the class name.

Decision Making Structures

Decision making structures have one or more conditions to be evaluated or tested by the program, along with a statement or statements that are to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false. Java programming language provides following types of decision making statements. if statement if..else statement nested if statement switch statement

Exceptions?

Exceptions are events that occur during the execution of programs that disrupt the normal flow of instructions (e.g. divide by zero, array access out of bound, etc.). In Java, an exception is an object that wraps an error event that occurred within a method and contains: - Information about the error including its type - The state of the program when the error occurred - Optionally, other custom information Categories of Exceptions : - Checked Exceptions - Unchecked Exceptions - Errors

Generalization

Generalization is the process of extracting shared characteristics from two or more classes, and combining them into a generalized superclass. Shared characteristics can be attributes, associations, or methods.

Method Overloading

If a class has multiple methods having same name but different in parameters, it is known as Method Overloading. If we have to perform only one operation, having same name of the methods increases the readability of the program. Suppose you have to perform addition of the given numbers but there can be any number of arguments, if you write the method such as a(int,int) for two parameters, and b(int,int,int) for three parameters then it may be difficult for you as well as other programmers to understand the behavior of the method because its name differs.

The Throw/Throws Keyword

If a method does not handle a checked exception, the method must declare it using the throws keyword. The throws keyword appears at the end of a method's signature. One can throw an exception, either a newly instantiated one or an exception that you just caught, by using the throw keyword. Understand the difference between throws and throw keywords, throws is used to postpone the handling of a checked exception and throw is used to invoke an exception explicitly.

Method Overriding

If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in Java. In other words, If a subclass provides the specific implementation of the method that has been declared by one of its parent class, it is known as method overriding.

Using fully qualified name

If you use fully qualified name then only declared class of this package will be accessible. Now there is no need to import. But you need to use fully qualified name every time when you are accessing the class or interface. It is generally used when two packages have same class name e.g. java.util and java.sql packages contain Date class.

Using packagename.*

If you use package.* then all the classes and interfaces of this package will be accessible but not subpackages. The import keyword is used to make the classes and interface of another package accessible to the current package.

Constructor

In Java, a constructor is a block of codes similar to the method. It is called when an instance of the object is created, and memory is allocated for the object. It is a special type of method which is used to initialize the object.

Constructor Overloading

In Java, a constructor is just like a method but without return type. It can also be overloaded like Java methods. Constructor overloading in Java is a technique of having more than one constructor with different parameter lists. They are arranged in a way that each constructor performs a different task. They are differentiated by the compiler by the number of parameters in the list and their types.

Inheritance

Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent object. It is an important part of OOPs (Object Oriented programming system). The idea behind inheritance in Java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of the parent class. Moreover, you can add new methods and fields in your current class also. Inheritance represents the IS-A relationship which is also known as a parent-child relationship.

Method Overloading vs Method Overriding

Method Overloading : - Method overloading is used to increase the readability of the program. - Method overloading is performed within the class. - In case of method overloading, the parameter must be different. - Method overloading is an example of compile-time polymorphism. - In java, method overloading can't be performed by changing the return type of the method only. The return type can be the same or different in method overloading. But you must have to change the parameter. Method Overriding : - Method overriding is used to provide the specific implementation of the method that is already provided by its super class. - Method overriding occurs in two classes that have an IS-A (inheritance) relationship. - In case of method overriding, the parameter must be the same. - Method overriding is an example of run time polymorphism. The return type must be the same or covariant in method overriding.

Array

Normally, an array is a collection of similar type of elements that have a contiguous memory location. Java array is an object which contains elements of a similar data type. It is a data structure where we store similar elements. We can store only a fixed set of elements in a Java array. Array in java is index-based, the first element of the array is stored at the 0 index.

Advantages of OOPs over Procedure Oriented Programming

OOPs makes development and maintenance easier whereas in a procedure-oriented programming language it is not easy to manage if code grows as project size increases. OOPs provides data hiding whereas in a procedure-oriented programming language a global data can be accessed from anywhere.

Types Of Inheritance In Java

On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical. In java programming, multiple and hybrid inheritance is supported through interface only. We will learn about interfaces later.

Polymorphism

Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object. Any Java object that can pass more than one IS-A test is considered to be polymorphic. In Java, all Java objects are polymorphic since any object will pass the IS-A test for their own type and for the class Object.

Concatenating Strings

The String class includes a method for concatenating two strings: string1.concat(string2); This returns a new string that is string1 with string2 added to it at the end. You can also use the concat() method with string literals "My Name is".concat("Zara"); Strings are most commonly concatenated with the "+" operator "Hello," + " world" + "!"

Default Constructor

The default constructor is a no-args constructor that the Java compiler inserts on your behalf; it contains a default call to super(); which is the default behavior. If you implement any constructor then you no longer receive a default constructor. Note : If there is no constructor in the class, the compiler adds a default constructor

Declaring Interfaces

The interface keyword is used to declare an interface. - An interface is implicitly abstract. You do not need to use the abstract keyword while declaring an interface. - Each method in an interface is also implicitly abstract, so the abstract keyword is not needed. - Methods in an interface are implicitly public.

Creating Strings

The most direct way to create a string is to write : String greeting = "hello world"; Whenever it encounters a string literal in your code, the compiler creates a String object with its value in this case, "Hello world!'. As with any other object, you can create String objects by using the new keyword and a constructor. The String class has 11 constructors that allow you to provide the initial value of the string using different sources, such as an array of characters.

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 class than an instance of the class. The static can be: - Variable (also known as a class variable) - Method (also known as a class method) - Block - Nested class

Using "super" to invoke parent class constructor

The super keyword can also be used to invoke the parent class constructor.

Rules to remember while creating a constructor

There are three rules defined for the constructor. - Constructor name must be the same as its class name - A Constructor must have no explicit return type - A Java constructor cannot be abstract, static, final, and synchronized

Accessing a package from other packages

There are three ways to access the package from outside the package. - import package.*; - import package.classname; - fully qualified name.

Types of Array

There are two types of arrays. - Single-Dimensional Array - Multidimensional Array

Access Modifiers

There are two types of modifiers in java: access modifiers and non-access modifiers. The access modifiers in java specifies accessibility (scope) of a data member, method, constructor or class.

Ways to achieve abstraction?

There are two ways to achieve abstraction in java - Abstract class (0 to 100%) - Interface (100%)

Different ways to overload a method?

There are two ways to overload the method in java - By changing number of arguments - By changing the data type

Usage of Keywords

There can be a lot of usage of java this keyword. In java, this is a reference variable that refers to the current object. Here is given the 6 usage of java this keyword. - this can be used to refer current class instance variable. - this can be used to invoke current class method (implicitly) - this() can be used to invoke current class constructor. - this can be passed as an argument in the method call. - this can be passed as argument in the constructor call. - this can be used to return the current class instance from the method.

Loops In Java

There may be a situation when you need to execute a block of code several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on. Programming languages provide various control structures that allow for more complicated execution paths. A loop statement allows us to execute a statement or group of statements multiple times and following is the general form of a loop statement in most of the programming languages.

Errors

These are not exceptions at all, but problems that arise beyond the control of the user or the programmer. Errors are typically ignored in your code because you can rarely do anything about an error. For example, if a stack overflow occurs, an error will arise. They are also ignored at the time of compilation.

Why multiple inheritance is not supported in Java?

To reduce the complexity and simplify the language, multiple inheritance is not supported in java. Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes. If A and B classes have the same method and you call it from child class object, there will be ambiguity to call the method of A or B class. Since compile-time errors are better than runtime errors, Java renders compile-time error if you inherit 2 classes. So whether you have same method or different, there will be compile time error.

Usage and Rules for Method Overriding

Usage : - Method overriding is used to provide the specific implementation of a method which is already provided by its superclass. - Method overriding is used for runtime polymorphism. Rules : - The method must have the same name as in the parent class. - The method must have the same parameter as in the parent class. - There must be an IS-A relationship (inheritance).

Implementing Interfaces

When a class implements an interface, you can think of the class as signing a contract, agreeing to perform the specific behaviors of the interface. If a class does not perform all the behaviors of the interface, the class must declare itself as abstract. A class uses the implements keyword to implement an interface. The implements keyword appears in the class declaration following the extends portion of the declaration. Rules to Remember : - A class can implement more than one interface at a time. - A class can extend only one class, but implement many interfaces. - An interface can extend another interface, in a similar way as a class can extend another class.

When is a constructor called?

When an object is created, compiler makes sure that constructors for all of its subobjects (its member and inherited objects) are called. If members have default constructors or constructor without parameter then these constructors are called automatically, otherwise parameterized constructors can be called using initializer list. Note: It is called constructor because it constructs the values at the time of object creation. It is not necessary to write a constructor for a class. It is because java compiler creates a default constructor if your class doesn't have any.

Differences between an interface and a class

You cannot instantiate an interface. An interface does not contain any constructors. All of the methods in an interface are abstract. An interface cannot contain instance fields. The only fields that can appear in an interface must be declared both static and final. An interface is not extended by a class, it is implemented by a class. An interface can extend multiple interfaces.

"this" : to invoke current class method

You may invoke the method of the current class by using the this keyword. If you don't use the this keyword, compiler automatically adds this keyword while invoking the method.

Multilevel Inheritance

class Animal{ void eat(){System.out.println("eating...");} } class Dog extends Animal{ //Level 1 - Inheritance void bark(){System.out.println("barking...");} } class BabyDog extends Dog{ //Level 2 - Inheritance void weep(){System.out.println("weeping...");} } class TestInheritance2{ public static void main(String args[]){ BabyDog d=new BabyDog(); d.weep(); d.bark(); d.eat(); }}

OOP (Object Oriented Programming)

is a methodology or paradigm to design a program using classes and objects. It simplifies the software development and maintenance by providing some concepts: - Object - Classes - Inheritance - Polymorphism - Abstraction - Encapsulation

Abstract Method

A method which is declared as abstract and does not have implementation is known as an abstract method.

Types of Encapsulation

- Read-Only Class (A Java class which has only getter methods.) -Write-Only Class '((A Java class which has only setter methods.)

Types of constructors

- Default Constructor - Parameterized Constructor

Rules for SWITCH Statement

- The variable used in a switch statement can only be integers, convertible integers (byte, short, char), strings, and enums. - You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon. - The value for a case must be the same data type as the variable in the switch and it must be a constant or a literal. - When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached. - When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement. - Not every case needs to contain a break. If no break appears, the flow of control will fall through to subsequent cases until a break is reached. - A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case.

Some String Handling Methods

- char charAt(int index) - Returns the character at the specified index. - int compareTo(Object o) - Compares this String to another Object. - String concat(String str) - Concatenates the specified string to the end of this string. - boolean equals(Object anObject) - Compares this string to the specified object. - boolean equalsIgnoreCase(String anotherString) - Compares this String to another String, ignoring case considerations.

Four Types of Java Access Modifiers

- private - default - protected - public There are many non-access modifiers such as static, abstract, synchronized, native, volatile, transient, etc. Here, we will learn access modifiers.

Extending Multiple Interfaces

A Java class can only extend one parent class. Multiple inheritance is not allowed. Interfaces are not classes, however, and an interface can extend more than one parent interface. The extends keyword is used once, and the parent interfaces are declared in a comma-separated list.

Abstract Class

A class which is declared as abstract is known as an abstract class. It can have abstract and non-abstract methods. It needs to be extended and its method implemented. It cannot be instantiated. Some points to remember : - An abstract class must be declared with an abstract keyword. - It can have abstract and non-abstract methods. - It cannot be instantiated. - It can have constructors and static methods also. - It can have final methods which will force the subclass not to change the body of the method.

Parameterized Constructor

A constructor which has a specific number of parameters is called a parameterized constructor. The parameterized constructor is used to provide different values to the distinct objects. However, you can provide the same values also.

Catching Exceptions

A method catches an exception using a combination of the try and catch keywords. A try/catch block is placed around the code that might generate an exception. Code within a try/catch block is referred to as protected code, and the syntax for using try/catch looks like the following: try { // Protected code } catch (ExceptionName e1) { // Catch block } The code which is prone to exceptions is placed in the try block. When an exception occurs, that exception occurred is handled by catch block associated with it. Every try block should be immediately followed either by a catch block or finally block. A catch statement involves declaring the type of exception you are trying to catch. If an exception occurs in protected code, the catch block (or blocks) that follows the try is checked. If the type of exception that occurred is listed in a catch block, the exception is passed to the catch block much as an argument is passed into a method parameter.

SWITCH Statement

A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each case.

While Loop

A while loop statement in Java programming language repeatedly executes a target statement as long as a given condition is true. Here, statement(s) may be a single statement or a block of statements. The condition may be any expression, and true is any non zero value. When executing, if the boolean_expression result is true, then the actions inside the loop will be executed. This will continue as long as the expression result is true. When the condition becomes false, program control passes to the line immediately following the loop.

Abstraction

Abstraction is a process of hiding the implementation details and showing only functionality to the user. Another way, it shows only essential things to the user and hides the internal details, for example, sending SMS where you type the text and send the message. You don't know the internal processing about the message delivery. Abstraction lets you focus on what the object does instead of how it does it.

Exception Hierarchy

All exception classes are subtypes of the java.lang.Exception class. The exception class is a subclass of the Throwable class. Other than the exception class there is another subclass called Error which is derived from the Throwable class.

IF..ELSE IF Statement

An if statement can be followed by an optional else if...else statement, which is very useful to test various conditions using a single if...else if statement. When using if, else if, and else statements there are a few points to keep in mind. - An if can have zero or one else's and it must come after any else if's. - An if can have zero to many else if's and they must come before the else. - Once an else if succeeds, none of the remaining else if's or else's will be tested.

IF..ELSE Statement

An if statement can be followed by an optional else statement, which executes when the Boolean expression is false.

IF Statement

An if statement consists of a Boolean expression followed by one or more statements.

Extending Interfaces

An interface can extend another interface in the same way that a class can extend another class. The extends keyword is used to extend an interface, and the child interface inherits the methods of the parent interface.

Example of Inheritance

As displayed in the above figure, Programmer is the subclass and Employee is the superclass. The relationship between the two classes is Programmer IS-A Employee. It means that Programmer is a type of Employee.

Checked Exceptions

Checked exceptions are those that : - The compiler enforces that you handle them explicitly. - Methods that generate checked exceptions must declare that they throw them. - Methods that invoke other methods that throw checked exceptions must either handle them (they can be reasonably expected to recover) or let them propagate by declaring that they throw them.

Unchecked Exceptions

Errors and RuntimeExceptions are unchecked — that is, the compiler does not enforce (check) that you handle them explicitly. Methods do not have to declare that they throw them (in the method signatures). It is assumed that the application cannot do anything to recover from these exceptions (at runtime).

Static variable

If you declare any variable as static, it is known as a static variable. - The static variable can be used to refer to the common property of all objects (which is not unique for each object), for example, the company name of employees, college name of students, etc. - The static variable gets memory only once in the class area at the time of class loading.

Nested IF Statement

It is always legal to nest if-else statements which means you can use one if or else if statement inside another if or else if statement.

Advantages of Static variable

It makes your program memory efficient (i.e., it saves memory).

Using "super" to invoke parent class method

The super keyword can also be used to invoke parent class method. It should be used if subclass contains the same method as parent class. In other words, it is used if method is overridden.

Java

Java is a general-purpose computer-programming language that is concurrent, class-based, object-oriented, and specifically designed to have as few implementation dependencies as possible. It is intended to let application developers "write once, run anywhere" (WORA), meaning that compiled Java code can run on all platforms that support Java without the need for recompilation. Java applications are typically compiled to bytecode that can run on any Java virtual machine (JVM) regardless of computer architecture.

Types Of Loops :

Java programming language provides the following types of loops to handle looping requirements : - While loop - For loop - Do...While loop

String Length

Methods used to obtain information about an object are known as accessor methods. One accessor method that you can use with strings is the length() method, which returns the number of characters contained in the string object.

Can a static method be overridden?

No, a static method cannot be overridden. It can be proved by runtime polymorphism, so we will learn it later. It is because the static method is bound with class whereas instance method is bound with an object. Static belongs to the class area, and an instance belongs to the heap area.

Sequence of program

Sequence of the program must be package then import then class.

Disadvantages of an Array

Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its size at runtime. To solve this problem, collection framework is used in Java which grows automatically.

Specialization

Specialization means creating new subclasses from an existing class. If it turns out that certain attributes, associations, or methods only apply to some of the objects of the class, a subclass can be created.

What is a String?

Strings, which are widely used in Java programming, are a sequence of characters. In Java programming language, strings are treated as objects. The Java platform provides the String class to create and manipulate strings.

Collection Interface

The Collection interface is the foundation upon which the collections framework is built. It declares the core methods that all collections will have. A collections framework is a unified architecture for representing and manipulating collections. All collections frameworks contain the following : - Interfaces − These are abstract data types that represent collections. Interfaces allow collections to be manipulated independently of the details of their representation. In object-oriented languages, interfaces generally form a hierarchy. - Implementations, i.e., Classes − These are the concrete implementations of the collection interfaces. In essence, they are reusable data structures. - Algorithms − These are the methods that perform useful computations, such as searching and sorting, on objects that implement collection interfaces. The algorithms are said to be polymorphic: that is, the same method can be used on many different implementations of the appropriate collection interface. In addition to collections, the framework defines several map interfaces and classes. Maps store key/value pairs. Although maps are not collections in the proper use of the term, but they are fully integrated with collections.

Queue

The Queue interface is available in java.util package and extends the Collection interface. The queue collection is used to hold the elements about to be processed and provides various operations like the insertion, removal etc. It is an ordered list of objects with its use limited to insert elements at the end of the list and deleting elements from the start of list i.e. it follows the FIFO or the First-In-First-Out principle. LinkedList, ArrayBlockingQueue and PriorityQueue are the most frequently used implementations.

Final Keyword

The final keyword in java is used to restrict the user. The java final keyword can be used in many context. Final can be: - variable - method - class The final keyword can be applied with the variables, a final variable that have no value it is called blank final variable or uninitialized final variable. It can be initialized in the constructor only. The blank final variable can be static also which will be initialized in the static block only.

Finally Block

The finally block follows a try block or a catch block. A finally block of code always executes, irrespective of occurrence of an Exception. Using a finally block allows you to run any cleanup-type statements that you want to execute, no matter what happens in the protected code. A finally block appears at the end of the catch blocks and has the following syntax: try { // Protected code } catch (ExceptionType1 e1) { // Catch block } catch (ExceptionType2 e2) { // Catch block } catch (ExceptionType3 e3) { // Catch block }finally { // The finally block always executes. }

Usage of "super" keyword

The super keyword in Java is a reference variable that is used to refer to immediate parent class objects. Whenever you create the instance of a subclass, an instance of the parent class is created implicitly which is referred to by a super reference variable. - super can be used to refer immediate parent class instance variable. - super can be used to invoke the immediate parent class method. - super() can be used to invoke the immediate parent class constructor.

Usage of the "new" keyword

When you are declaring a class in java, you are just creating a new data type. A class provides the blueprint for objects. You can create an object from a class. Declaration : First, you must declare a variable of the class type. This variable does not define an object. Instantiation and Initialization : Second, you must acquire an actual, physical copy of the object and assign it to that variable. You can do this using the new operator. The new operator instantiates a class by dynamically allocating(i.e, allocation at run time) memory for a new object and returning a reference to that memory. This reference is then stored in the variable. Thus, in Java, all class objects must be dynamically allocated. The new operator is also followed by a call to a class constructor, which initializes the new object. A constructor defines what occurs when an object of a class is created. Constructors are an important part of all classes and have many significant attributes.

Hierarchical Inheritance

class Animal{ void eat(){System.out.println("eating...");} } class Dog extends Animal{ // Hierarchical Inheritance void bark(){System.out.println("barking...");} } class Cat extends Animal{ // Hierarchical Inheritance void meow(){System.out.println("meowing...");} } class TestInheritance3{ public static void main(String args[]){ Cat c=new Cat(); c.meow(); c.eat(); //c.bark(); //Error }}

single inheritance

class Animal{ void eat(){System.out.println("eating...");} } class Dog extends Animal{ //Single Inheritance void bark(){System.out.println("barking...");} } class TestInheritance{ public static void main(String args[]){ Dog d=new Dog(); d.bark(); d.eat(); }}


संबंधित स्टडी सेट्स

MNGT 301 || Chapter 16 - Control Systems and Quality Management: Techniques for Enhancing Organizational Effectiveness

View Set

Kappa Alpha Psi Founders - Test - Final, Greek Alphabet, Kappa Alpha Psi Info. Quenitn

View Set

DELAWARE LAWS, RULES & REGULATIONS: Life, Accident and Health, Property and Casual Insurance

View Set

Abdominal Vasculature Sonography Review

View Set

Omnichannel & Digital Marketing: EXAM QUESTIONS PAPERS

View Set

Comparative method - research methods

View Set