This blog is a personal blog, which is about programming in Java, C#, C++, Object-Oriented Programming, and more. I hope that my blog will teach you how to become a Java, C#, C++ programmer. If you are interested in learning programming languages, then you should not miss to visit this blog!
Today, we’re going to look at one of the most important topics in object-oriented programming. Classes. Abstract classes, nested classes, methods, static members, and all the other various terms that go into class design.
We are going to be writing about abstract and nested classes in JavaScript, and the reasons why we should use them.
Modeling business problems withclasses
estate of class
When developing an object-oriented solution, you should try to avoid duplicating code. One way to avoid duplication is to create library methods and classes. Libraries act as a central point that often contains reused code. Another technique to avoid code duplication is to use class inheritance. If there is a common base type between two classes, all common code can be placed in the parent class. Use references to objects of the most common base type whenever possible. In Java, generalization and specialization enable reuse through method inheritance and virtual method invocation (VMI). VMI, sometimes called late binding, allows the caller to dynamically call a method if it is declared in a common base type. Inheritance (or sub-classification) is an inherent feature of the Java programming language. Inheritance allows for code reuse:
- Inheritance of methods : Subclasses avoid duplication of code by inheriting method implementations.
- Synopsis: Code created to use the most versatile type is easier to maintain.
Creating the conditions for mainstreaming
By coding to a common base type, new subclasses can be introduced with little or no change in the code that depends on the most common base type. ElectronicDevice dev = new Television(); dev.turnOn(); // all ElectronicDevices can be turned on. Always use the most general reference type.
Coding for generalisation
Always use the most general reference type. Java IDEs may include refactoring tools to help change existing references to a more generic base type.
Determine the need for abstract classes
Subclasses cannot inherit from the implementation of a method if it is specialized. public class Television extends ElectronicDevice { public void turnOn() { changeChannel(1); initializeScreen(); } public void turnOff() {} public change channel(int channel) {} public initializeScreen() {} }
Application of methods
When sister classes share a common method, it is usually placed in the parent class. However, in some circumstances, the implementation of a parent class should always be replaced by a specialized implementation. In this case, including a method in the parent class has both advantages and disadvantages. This allows generic reference types to be used, but developers can easily forget to subclass a specialized implementation.
Definition of abstract classes
If you declare a class as abstract, you cannot create instances of that class. Instantiating an abstract class is a compiler error. An abstract class is usually extended by a child class and can be used as a reference type. – A class can be declared abstract with the abstract class level modifier. abstract public class ElectronicDevice { } – An abstract class can be a subclass. public class Television extends ElectronicDevice { } – An abstract class cannot be instantiated. ElectronicDevice dev = new ElectronicDevice(); // Error
Definition of abstract methods
A method can be declared abstract with the abstract method level modifier. public abstract class ElectronicDevice { public abstract void turnOn(); public abstract void turnOff(); } Abstract Method :
- Can’t have a method body
- Must be declared in an abstract class
- Transcribed in subclasses
Inheritance of abstract methods
When a child class inherits from an abstract method, it inherits the method’s signature, but not the implementation. For this reason, parentheses are not allowed when defining an abstract method. An abstract method is a way to ensure that every child class contains a method with the correct signature. Message: An abstract method can take arguments and return values. For example: abstract double computeArea(double dim1, double dim2) ;
Abstract class validation
When using abstract classes and methods, the following additional rules apply:
- An abstract class can have any number of abstract and non-abstract methods.
- If you inherit from an abstract class, you must do one of the following:
- Declare the child class as abstract.
- Overrides all abstract methods inherited from the parent class. If not, a compilation error will occur.
Wrong: TV is not abstract and does not override the abstract method turnOn() in ElectronicDevice.
Use of abstract classes
It is possible to avoid implementing an abstract method by declaring the child classes as abstract, but this only postpones the inevitable. Applications need non-abstract methods to create objects. Use abstract methods to define the functionality required by the underlying classes.
Finishing methods
A method can be declared as finite. Finite methods cannot be replaced. public class MethodParentClass { public final void printMessage() { System.out.println(This is a final method); } } public class MethodChildClass extends MethodParentClass { // compile error public void printMessage() { System.out.println(method cannot be overwritten); } }
Performance myths
Declaring the method finite has almost no performance advantage. Methods should only be declared as final to prevent them from being overwritten.
Synthetic seats
The class can be declared as finite. Graduate classes cannot be renewed. public final class FinalParentClass { } // Compilation error public class ChildClass extends FinalParentClass { }
Final variables
The last modifier can be applied to variables. End variables cannot change their value once initialized. The final variables may be :
- Class Fields : Finite fields with compile-time constant expressions are constant variables. The static can eventually be combined into an always available variable, which never changes.
- Method parameters
- Local variables
Message: End references must always refer to the same object, but the content of that object can be changed.
Advantages and disadvantages of finite variables
- Error prevention : Terminal variables can never change value after they have been initialized. This behavior serves as a mechanism to avoid mistakes.
- Wire security: The immutable nature of finite variables eliminates the problems that arise when multiple threads access them simultaneously.
- Final object reference : The last reference of the object only prevents you from pointing to another object. When you design immutable objects, you must prevent the object’s fields from changing. For final referrals, it is also not possible to assign a referral to zero. Retaining references to a property prevents it from being available for waste collection.
Explanation of finite variables
Final fields
Initialization – The end fields (instance variables) must be one of the following:
- Assigns a value when declaring.
- Assigns a value in each constructor.
Static and finite combined: A field that is both static and finite is considered a constant. By convention, constant fields use identifiers consisting only of uppercase and underscores. public class VariableExampleClass { private final int field; public static final int JAVA_CONSTANT = 10 ; public VariableExampleClass() { field = 100; } public void changeValues(final int param) { param = 1; // compile error final int localVar; localVar = 42; localVar = 43; // compile error } }
Classes nested
A nested class is a class that is declared within the body of another class. Nested classes have different categories: 1. Indoor classes :
- Membership categories
- Local activities
- Anonymous classes
2. Nested static classes. Nested classes are typically used in applications with graphical user interface elements. You can limit the use of the auxiliary class to the highest level class. The nested inner class is considered part of the outer class and inherits access to all private members of the outer class. A nested static class is not an inner class, but its declaration is similar with an additional static modifier on the nested class. Static nested classes can be instantiated before the external nested class and therefore do not have access to all non-static members of the nested class. Message: Anonymous classes are covered in detail in the class Interfaces and lambda expressions.
Reasons for using nested classes
- Logical grouping of classes – If a class is only useful to another class, it makes sense to include it in that class and keep it together. Nesting these auxiliary classes makes their packaging more concise.
- Increasing encapsulation – Consider two top-level classes, A and B, where B needs access to members of A that would otherwise be declared private. By hiding class B in class A, members of A can be declared private and B can access them. Moreover, B itself can remain hidden from the outside world.
- More readable and maintainable code – Nesting small classes into higher level classes brings the code closer to where it will be used.
Example: Membership class
The following example illustrates the inner class EMICalculatorHelper defined in the class BankEMICalculator. public class BankEMICalculator { private String CustomerName; private String AccountNo; private double loanAmount; private double monthlypayment; private EMICalculatorHelper helper = new EMICalculatorHelper() ; /*institutions and recuperators*/ private class EMICalculatorHelper { int loanTerm = 60; double interestRate = 0.9; double interestpermonth=interestRate/loanTerm ; protected double calcMonthlyPayment(double loanAmount){double EMI= (loanAmount * interestpermonth) / ((1,0) – ((1,0) /Math.pow(1,0 + interestpermonth, loanTerm))));return(Math.round(EMI));}}
Lists
Java contains a type-safe enum in its language. Enums: are created with a variation of the Java class and provide scope control at compile time. public enum PowerState { OFF, ON, SUSPEND; } These are references to the only three PowerState objects that can exist. The enumeration can be used as follows: Computer comp = new computer(); comp.setState(PowerState.SUSPEND) ;
Checking routing during compilation
In the above example, the compiler performs a check at compile time to ensure that only valid PowerState instances are passed to the setState method. There is no overhead for scope control at runtime.
Use of lists
Enumerations can be used as expressions in the switch statement. public void setState(PowerState state) { switch(state) { case OFF : //… } }
Compound lists
Enumerations can have private fields, methods and constructors. You can call the PowerState constructor to initialize the public static final OFF reference. The builder may not be public or protected. public enum PowerState { OFF, ON, SUSPEND ; private String description; private PowerState(String d) { description = d; } public String getDescription() { return description; } }
EnumDesigners
You cannot create an enumeration instance with new.
Compound lists
Here’s a complex listing in action. public class ComplexEnumsMain { public static void main(String[] args) { Computer comp = new Computer(); comp.setState(PowerState.SUSPEND); System.out.println(Current Status: + comp.getState()); System.out.println(Description: + comp.getState().getDescription()); } } Exit: Current Status: SUSPEND Description: Low energy consumption
Use of lists
When an enumeration is sent for printing, the current value is printed by default. Normally, an additional call to the enumeration methods is required to retrieve the information stored in an enumeration.To many developers, object-oriented programming is a way of life. We write classes and methods, create prototypes and subclasses, and create abstractions. We pass objects around, we store them in collections, and we make everything accessible via public members. But what if we are in a hurry?. Read more about how to access static nested classes mcq and let us know what you think.
Related Tags:
nested classes c++nested classes javahow to access static nested classes?how to access static nested classes mcqnested class c#abstract class in java,People also search for,Privacy settings,How Search works,nested classes c++,nested classes java,how to access static nested classes?,how to access static nested classes mcq,nested class c#,abstract class in java,anonymous inner class in java,methods in all nested classes can be declared static